PageRenderTime 73ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/3rd_party/llvm/lib/Bitcode/Reader/BitcodeReader.cpp

https://code.google.com/p/softart/
C++ | 3351 lines | 2729 code | 351 blank | 271 comment | 828 complexity | 047c2444de5bfa66801c5f22cbfe7456 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, JSON, MPL-2.0-no-copyleft-exception, GPL-2.0, GPL-3.0, LGPL-3.0, BSD-2-Clause
  1. //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/Bitcode/ReaderWriter.h"
  10. #include "BitcodeReader.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/AutoUpgrade.h"
  14. #include "llvm/Bitcode/LLVMBitCodes.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/IR/DerivedTypes.h"
  17. #include "llvm/IR/InlineAsm.h"
  18. #include "llvm/IR/IntrinsicInst.h"
  19. #include "llvm/IR/LLVMContext.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/IR/OperandTraits.h"
  22. #include "llvm/IR/Operator.h"
  23. #include "llvm/Support/DataStream.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. using namespace llvm;
  28. enum {
  29. SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
  30. };
  31. void BitcodeReader::materializeForwardReferencedFunctions() {
  32. while (!BlockAddrFwdRefs.empty()) {
  33. Function *F = BlockAddrFwdRefs.begin()->first;
  34. F->Materialize();
  35. }
  36. }
  37. void BitcodeReader::FreeState() {
  38. if (BufferOwned)
  39. delete Buffer;
  40. Buffer = 0;
  41. std::vector<Type*>().swap(TypeList);
  42. ValueList.clear();
  43. MDValueList.clear();
  44. std::vector<AttributeSet>().swap(MAttributes);
  45. std::vector<BasicBlock*>().swap(FunctionBBs);
  46. std::vector<Function*>().swap(FunctionsWithBodies);
  47. DeferredFunctionInfo.clear();
  48. MDKindMap.clear();
  49. assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
  50. }
  51. //===----------------------------------------------------------------------===//
  52. // Helper functions to implement forward reference resolution, etc.
  53. //===----------------------------------------------------------------------===//
  54. /// ConvertToString - Convert a string from a record into an std::string, return
  55. /// true on failure.
  56. template<typename StrTy>
  57. static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
  58. StrTy &Result) {
  59. if (Idx > Record.size())
  60. return true;
  61. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  62. Result += (char)Record[i];
  63. return false;
  64. }
  65. static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
  66. switch (Val) {
  67. default: // Map unknown/new linkages to external
  68. case 0: return GlobalValue::ExternalLinkage;
  69. case 1: return GlobalValue::WeakAnyLinkage;
  70. case 2: return GlobalValue::AppendingLinkage;
  71. case 3: return GlobalValue::InternalLinkage;
  72. case 4: return GlobalValue::LinkOnceAnyLinkage;
  73. case 5: return GlobalValue::DLLImportLinkage;
  74. case 6: return GlobalValue::DLLExportLinkage;
  75. case 7: return GlobalValue::ExternalWeakLinkage;
  76. case 8: return GlobalValue::CommonLinkage;
  77. case 9: return GlobalValue::PrivateLinkage;
  78. case 10: return GlobalValue::WeakODRLinkage;
  79. case 11: return GlobalValue::LinkOnceODRLinkage;
  80. case 12: return GlobalValue::AvailableExternallyLinkage;
  81. case 13: return GlobalValue::LinkerPrivateLinkage;
  82. case 14: return GlobalValue::LinkerPrivateWeakLinkage;
  83. }
  84. }
  85. static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
  86. switch (Val) {
  87. default: // Map unknown visibilities to default.
  88. case 0: return GlobalValue::DefaultVisibility;
  89. case 1: return GlobalValue::HiddenVisibility;
  90. case 2: return GlobalValue::ProtectedVisibility;
  91. }
  92. }
  93. static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
  94. switch (Val) {
  95. case 0: return GlobalVariable::NotThreadLocal;
  96. default: // Map unknown non-zero value to general dynamic.
  97. case 1: return GlobalVariable::GeneralDynamicTLSModel;
  98. case 2: return GlobalVariable::LocalDynamicTLSModel;
  99. case 3: return GlobalVariable::InitialExecTLSModel;
  100. case 4: return GlobalVariable::LocalExecTLSModel;
  101. }
  102. }
  103. static int GetDecodedCastOpcode(unsigned Val) {
  104. switch (Val) {
  105. default: return -1;
  106. case bitc::CAST_TRUNC : return Instruction::Trunc;
  107. case bitc::CAST_ZEXT : return Instruction::ZExt;
  108. case bitc::CAST_SEXT : return Instruction::SExt;
  109. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  110. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  111. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  112. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  113. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  114. case bitc::CAST_FPEXT : return Instruction::FPExt;
  115. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  116. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  117. case bitc::CAST_BITCAST : return Instruction::BitCast;
  118. case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
  119. }
  120. }
  121. static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
  122. switch (Val) {
  123. default: return -1;
  124. case bitc::BINOP_ADD:
  125. return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
  126. case bitc::BINOP_SUB:
  127. return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
  128. case bitc::BINOP_MUL:
  129. return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
  130. case bitc::BINOP_UDIV: return Instruction::UDiv;
  131. case bitc::BINOP_SDIV:
  132. return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
  133. case bitc::BINOP_UREM: return Instruction::URem;
  134. case bitc::BINOP_SREM:
  135. return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
  136. case bitc::BINOP_SHL: return Instruction::Shl;
  137. case bitc::BINOP_LSHR: return Instruction::LShr;
  138. case bitc::BINOP_ASHR: return Instruction::AShr;
  139. case bitc::BINOP_AND: return Instruction::And;
  140. case bitc::BINOP_OR: return Instruction::Or;
  141. case bitc::BINOP_XOR: return Instruction::Xor;
  142. }
  143. }
  144. static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
  145. switch (Val) {
  146. default: return AtomicRMWInst::BAD_BINOP;
  147. case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
  148. case bitc::RMW_ADD: return AtomicRMWInst::Add;
  149. case bitc::RMW_SUB: return AtomicRMWInst::Sub;
  150. case bitc::RMW_AND: return AtomicRMWInst::And;
  151. case bitc::RMW_NAND: return AtomicRMWInst::Nand;
  152. case bitc::RMW_OR: return AtomicRMWInst::Or;
  153. case bitc::RMW_XOR: return AtomicRMWInst::Xor;
  154. case bitc::RMW_MAX: return AtomicRMWInst::Max;
  155. case bitc::RMW_MIN: return AtomicRMWInst::Min;
  156. case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
  157. case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
  158. }
  159. }
  160. static AtomicOrdering GetDecodedOrdering(unsigned Val) {
  161. switch (Val) {
  162. case bitc::ORDERING_NOTATOMIC: return NotAtomic;
  163. case bitc::ORDERING_UNORDERED: return Unordered;
  164. case bitc::ORDERING_MONOTONIC: return Monotonic;
  165. case bitc::ORDERING_ACQUIRE: return Acquire;
  166. case bitc::ORDERING_RELEASE: return Release;
  167. case bitc::ORDERING_ACQREL: return AcquireRelease;
  168. default: // Map unknown orderings to sequentially-consistent.
  169. case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
  170. }
  171. }
  172. static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
  173. switch (Val) {
  174. case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
  175. default: // Map unknown scopes to cross-thread.
  176. case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
  177. }
  178. }
  179. namespace llvm {
  180. namespace {
  181. /// @brief A class for maintaining the slot number definition
  182. /// as a placeholder for the actual definition for forward constants defs.
  183. class ConstantPlaceHolder : public ConstantExpr {
  184. void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
  185. public:
  186. // allocate space for exactly one operand
  187. void *operator new(size_t s) {
  188. return User::operator new(s, 1);
  189. }
  190. explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
  191. : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
  192. Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
  193. }
  194. /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
  195. static bool classof(const Value *V) {
  196. return isa<ConstantExpr>(V) &&
  197. cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
  198. }
  199. /// Provide fast operand accessors
  200. //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  201. };
  202. }
  203. // FIXME: can we inherit this from ConstantExpr?
  204. template <>
  205. struct OperandTraits<ConstantPlaceHolder> :
  206. public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
  207. };
  208. }
  209. void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
  210. if (Idx == size()) {
  211. push_back(V);
  212. return;
  213. }
  214. if (Idx >= size())
  215. resize(Idx+1);
  216. WeakVH &OldV = ValuePtrs[Idx];
  217. if (OldV == 0) {
  218. OldV = V;
  219. return;
  220. }
  221. // Handle constants and non-constants (e.g. instrs) differently for
  222. // efficiency.
  223. if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
  224. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  225. OldV = V;
  226. } else {
  227. // If there was a forward reference to this value, replace it.
  228. Value *PrevVal = OldV;
  229. OldV->replaceAllUsesWith(V);
  230. delete PrevVal;
  231. }
  232. }
  233. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  234. Type *Ty) {
  235. if (Idx >= size())
  236. resize(Idx + 1);
  237. if (Value *V = ValuePtrs[Idx]) {
  238. assert(Ty == V->getType() && "Type mismatch in constant table!");
  239. return cast<Constant>(V);
  240. }
  241. // Create and return a placeholder, which will later be RAUW'd.
  242. Constant *C = new ConstantPlaceHolder(Ty, Context);
  243. ValuePtrs[Idx] = C;
  244. return C;
  245. }
  246. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
  247. if (Idx >= size())
  248. resize(Idx + 1);
  249. if (Value *V = ValuePtrs[Idx]) {
  250. assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
  251. return V;
  252. }
  253. // No type specified, must be invalid reference.
  254. if (Ty == 0) return 0;
  255. // Create and return a placeholder, which will later be RAUW'd.
  256. Value *V = new Argument(Ty);
  257. ValuePtrs[Idx] = V;
  258. return V;
  259. }
  260. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  261. /// resolves any forward references. The idea behind this is that we sometimes
  262. /// get constants (such as large arrays) which reference *many* forward ref
  263. /// constants. Replacing each of these causes a lot of thrashing when
  264. /// building/reuniquing the constant. Instead of doing this, we look at all the
  265. /// uses and rewrite all the place holders at once for any constant that uses
  266. /// a placeholder.
  267. void BitcodeReaderValueList::ResolveConstantForwardRefs() {
  268. // Sort the values by-pointer so that they are efficient to look up with a
  269. // binary search.
  270. std::sort(ResolveConstants.begin(), ResolveConstants.end());
  271. SmallVector<Constant*, 64> NewOps;
  272. while (!ResolveConstants.empty()) {
  273. Value *RealVal = operator[](ResolveConstants.back().second);
  274. Constant *Placeholder = ResolveConstants.back().first;
  275. ResolveConstants.pop_back();
  276. // Loop over all users of the placeholder, updating them to reference the
  277. // new value. If they reference more than one placeholder, update them all
  278. // at once.
  279. while (!Placeholder->use_empty()) {
  280. Value::use_iterator UI = Placeholder->use_begin();
  281. User *U = *UI;
  282. // If the using object isn't uniqued, just update the operands. This
  283. // handles instructions and initializers for global variables.
  284. if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
  285. UI.getUse().set(RealVal);
  286. continue;
  287. }
  288. // Otherwise, we have a constant that uses the placeholder. Replace that
  289. // constant with a new constant that has *all* placeholder uses updated.
  290. Constant *UserC = cast<Constant>(U);
  291. for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
  292. I != E; ++I) {
  293. Value *NewOp;
  294. if (!isa<ConstantPlaceHolder>(*I)) {
  295. // Not a placeholder reference.
  296. NewOp = *I;
  297. } else if (*I == Placeholder) {
  298. // Common case is that it just references this one placeholder.
  299. NewOp = RealVal;
  300. } else {
  301. // Otherwise, look up the placeholder in ResolveConstants.
  302. ResolveConstantsTy::iterator It =
  303. std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
  304. std::pair<Constant*, unsigned>(cast<Constant>(*I),
  305. 0));
  306. assert(It != ResolveConstants.end() && It->first == *I);
  307. NewOp = operator[](It->second);
  308. }
  309. NewOps.push_back(cast<Constant>(NewOp));
  310. }
  311. // Make the new constant.
  312. Constant *NewC;
  313. if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
  314. NewC = ConstantArray::get(UserCA->getType(), NewOps);
  315. } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
  316. NewC = ConstantStruct::get(UserCS->getType(), NewOps);
  317. } else if (isa<ConstantVector>(UserC)) {
  318. NewC = ConstantVector::get(NewOps);
  319. } else {
  320. assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
  321. NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
  322. }
  323. UserC->replaceAllUsesWith(NewC);
  324. UserC->destroyConstant();
  325. NewOps.clear();
  326. }
  327. // Update all ValueHandles, they should be the only users at this point.
  328. Placeholder->replaceAllUsesWith(RealVal);
  329. delete Placeholder;
  330. }
  331. }
  332. void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
  333. if (Idx == size()) {
  334. push_back(V);
  335. return;
  336. }
  337. if (Idx >= size())
  338. resize(Idx+1);
  339. WeakVH &OldV = MDValuePtrs[Idx];
  340. if (OldV == 0) {
  341. OldV = V;
  342. return;
  343. }
  344. // If there was a forward reference to this value, replace it.
  345. MDNode *PrevVal = cast<MDNode>(OldV);
  346. OldV->replaceAllUsesWith(V);
  347. MDNode::deleteTemporary(PrevVal);
  348. // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
  349. // value for Idx.
  350. MDValuePtrs[Idx] = V;
  351. }
  352. Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
  353. if (Idx >= size())
  354. resize(Idx + 1);
  355. if (Value *V = MDValuePtrs[Idx]) {
  356. assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
  357. return V;
  358. }
  359. // Create and return a placeholder, which will later be RAUW'd.
  360. Value *V = MDNode::getTemporary(Context, None);
  361. MDValuePtrs[Idx] = V;
  362. return V;
  363. }
  364. Type *BitcodeReader::getTypeByID(unsigned ID) {
  365. // The type table size is always specified correctly.
  366. if (ID >= TypeList.size())
  367. return 0;
  368. if (Type *Ty = TypeList[ID])
  369. return Ty;
  370. // If we have a forward reference, the only possible case is when it is to a
  371. // named struct. Just create a placeholder for now.
  372. return TypeList[ID] = StructType::create(Context);
  373. }
  374. //===----------------------------------------------------------------------===//
  375. // Functions for parsing blocks from the bitcode file
  376. //===----------------------------------------------------------------------===//
  377. /// \brief This fills an AttrBuilder object with the LLVM attributes that have
  378. /// been decoded from the given integer. This function must stay in sync with
  379. /// 'encodeLLVMAttributesForBitcode'.
  380. static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
  381. uint64_t EncodedAttrs) {
  382. // FIXME: Remove in 4.0.
  383. // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
  384. // the bits above 31 down by 11 bits.
  385. unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
  386. assert((!Alignment || isPowerOf2_32(Alignment)) &&
  387. "Alignment must be a power of two.");
  388. if (Alignment)
  389. B.addAlignmentAttr(Alignment);
  390. B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
  391. (EncodedAttrs & 0xffff));
  392. }
  393. error_code BitcodeReader::ParseAttributeBlock() {
  394. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  395. return Error(InvalidRecord);
  396. if (!MAttributes.empty())
  397. return Error(InvalidMultipleBlocks);
  398. SmallVector<uint64_t, 64> Record;
  399. SmallVector<AttributeSet, 8> Attrs;
  400. // Read all the records.
  401. while (1) {
  402. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  403. switch (Entry.Kind) {
  404. case BitstreamEntry::SubBlock: // Handled for us already.
  405. case BitstreamEntry::Error:
  406. return Error(MalformedBlock);
  407. case BitstreamEntry::EndBlock:
  408. return error_code::success();
  409. case BitstreamEntry::Record:
  410. // The interesting case.
  411. break;
  412. }
  413. // Read a record.
  414. Record.clear();
  415. switch (Stream.readRecord(Entry.ID, Record)) {
  416. default: // Default behavior: ignore.
  417. break;
  418. case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
  419. // FIXME: Remove in 4.0.
  420. if (Record.size() & 1)
  421. return Error(InvalidRecord);
  422. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  423. AttrBuilder B;
  424. decodeLLVMAttributesForBitcode(B, Record[i+1]);
  425. Attrs.push_back(AttributeSet::get(Context, Record[i], B));
  426. }
  427. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  428. Attrs.clear();
  429. break;
  430. }
  431. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
  432. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  433. Attrs.push_back(MAttributeGroups[Record[i]]);
  434. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  435. Attrs.clear();
  436. break;
  437. }
  438. }
  439. }
  440. }
  441. // Returns Attribute::None on unrecognized codes.
  442. static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
  443. switch (Code) {
  444. default:
  445. return Attribute::None;
  446. case bitc::ATTR_KIND_ALIGNMENT:
  447. return Attribute::Alignment;
  448. case bitc::ATTR_KIND_ALWAYS_INLINE:
  449. return Attribute::AlwaysInline;
  450. case bitc::ATTR_KIND_BUILTIN:
  451. return Attribute::Builtin;
  452. case bitc::ATTR_KIND_BY_VAL:
  453. return Attribute::ByVal;
  454. case bitc::ATTR_KIND_COLD:
  455. return Attribute::Cold;
  456. case bitc::ATTR_KIND_INLINE_HINT:
  457. return Attribute::InlineHint;
  458. case bitc::ATTR_KIND_IN_REG:
  459. return Attribute::InReg;
  460. case bitc::ATTR_KIND_MIN_SIZE:
  461. return Attribute::MinSize;
  462. case bitc::ATTR_KIND_NAKED:
  463. return Attribute::Naked;
  464. case bitc::ATTR_KIND_NEST:
  465. return Attribute::Nest;
  466. case bitc::ATTR_KIND_NO_ALIAS:
  467. return Attribute::NoAlias;
  468. case bitc::ATTR_KIND_NO_BUILTIN:
  469. return Attribute::NoBuiltin;
  470. case bitc::ATTR_KIND_NO_CAPTURE:
  471. return Attribute::NoCapture;
  472. case bitc::ATTR_KIND_NO_DUPLICATE:
  473. return Attribute::NoDuplicate;
  474. case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
  475. return Attribute::NoImplicitFloat;
  476. case bitc::ATTR_KIND_NO_INLINE:
  477. return Attribute::NoInline;
  478. case bitc::ATTR_KIND_NON_LAZY_BIND:
  479. return Attribute::NonLazyBind;
  480. case bitc::ATTR_KIND_NO_RED_ZONE:
  481. return Attribute::NoRedZone;
  482. case bitc::ATTR_KIND_NO_RETURN:
  483. return Attribute::NoReturn;
  484. case bitc::ATTR_KIND_NO_UNWIND:
  485. return Attribute::NoUnwind;
  486. case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
  487. return Attribute::OptimizeForSize;
  488. case bitc::ATTR_KIND_OPTIMIZE_NONE:
  489. return Attribute::OptimizeNone;
  490. case bitc::ATTR_KIND_READ_NONE:
  491. return Attribute::ReadNone;
  492. case bitc::ATTR_KIND_READ_ONLY:
  493. return Attribute::ReadOnly;
  494. case bitc::ATTR_KIND_RETURNED:
  495. return Attribute::Returned;
  496. case bitc::ATTR_KIND_RETURNS_TWICE:
  497. return Attribute::ReturnsTwice;
  498. case bitc::ATTR_KIND_S_EXT:
  499. return Attribute::SExt;
  500. case bitc::ATTR_KIND_STACK_ALIGNMENT:
  501. return Attribute::StackAlignment;
  502. case bitc::ATTR_KIND_STACK_PROTECT:
  503. return Attribute::StackProtect;
  504. case bitc::ATTR_KIND_STACK_PROTECT_REQ:
  505. return Attribute::StackProtectReq;
  506. case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
  507. return Attribute::StackProtectStrong;
  508. case bitc::ATTR_KIND_STRUCT_RET:
  509. return Attribute::StructRet;
  510. case bitc::ATTR_KIND_SANITIZE_ADDRESS:
  511. return Attribute::SanitizeAddress;
  512. case bitc::ATTR_KIND_SANITIZE_THREAD:
  513. return Attribute::SanitizeThread;
  514. case bitc::ATTR_KIND_SANITIZE_MEMORY:
  515. return Attribute::SanitizeMemory;
  516. case bitc::ATTR_KIND_UW_TABLE:
  517. return Attribute::UWTable;
  518. case bitc::ATTR_KIND_Z_EXT:
  519. return Attribute::ZExt;
  520. }
  521. }
  522. error_code BitcodeReader::ParseAttrKind(uint64_t Code,
  523. Attribute::AttrKind *Kind) {
  524. *Kind = GetAttrFromCode(Code);
  525. if (*Kind == Attribute::None)
  526. return Error(InvalidValue);
  527. return error_code::success();
  528. }
  529. error_code BitcodeReader::ParseAttributeGroupBlock() {
  530. if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
  531. return Error(InvalidRecord);
  532. if (!MAttributeGroups.empty())
  533. return Error(InvalidMultipleBlocks);
  534. SmallVector<uint64_t, 64> Record;
  535. // Read all the records.
  536. while (1) {
  537. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  538. switch (Entry.Kind) {
  539. case BitstreamEntry::SubBlock: // Handled for us already.
  540. case BitstreamEntry::Error:
  541. return Error(MalformedBlock);
  542. case BitstreamEntry::EndBlock:
  543. return error_code::success();
  544. case BitstreamEntry::Record:
  545. // The interesting case.
  546. break;
  547. }
  548. // Read a record.
  549. Record.clear();
  550. switch (Stream.readRecord(Entry.ID, Record)) {
  551. default: // Default behavior: ignore.
  552. break;
  553. case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
  554. if (Record.size() < 3)
  555. return Error(InvalidRecord);
  556. uint64_t GrpID = Record[0];
  557. uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
  558. AttrBuilder B;
  559. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  560. if (Record[i] == 0) { // Enum attribute
  561. Attribute::AttrKind Kind;
  562. if (error_code EC = ParseAttrKind(Record[++i], &Kind))
  563. return EC;
  564. B.addAttribute(Kind);
  565. } else if (Record[i] == 1) { // Align attribute
  566. Attribute::AttrKind Kind;
  567. if (error_code EC = ParseAttrKind(Record[++i], &Kind))
  568. return EC;
  569. if (Kind == Attribute::Alignment)
  570. B.addAlignmentAttr(Record[++i]);
  571. else
  572. B.addStackAlignmentAttr(Record[++i]);
  573. } else { // String attribute
  574. assert((Record[i] == 3 || Record[i] == 4) &&
  575. "Invalid attribute group entry");
  576. bool HasValue = (Record[i++] == 4);
  577. SmallString<64> KindStr;
  578. SmallString<64> ValStr;
  579. while (Record[i] != 0 && i != e)
  580. KindStr += Record[i++];
  581. assert(Record[i] == 0 && "Kind string not null terminated");
  582. if (HasValue) {
  583. // Has a value associated with it.
  584. ++i; // Skip the '0' that terminates the "kind" string.
  585. while (Record[i] != 0 && i != e)
  586. ValStr += Record[i++];
  587. assert(Record[i] == 0 && "Value string not null terminated");
  588. }
  589. B.addAttribute(KindStr.str(), ValStr.str());
  590. }
  591. }
  592. MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
  593. break;
  594. }
  595. }
  596. }
  597. }
  598. error_code BitcodeReader::ParseTypeTable() {
  599. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
  600. return Error(InvalidRecord);
  601. return ParseTypeTableBody();
  602. }
  603. error_code BitcodeReader::ParseTypeTableBody() {
  604. if (!TypeList.empty())
  605. return Error(InvalidMultipleBlocks);
  606. SmallVector<uint64_t, 64> Record;
  607. unsigned NumRecords = 0;
  608. SmallString<64> TypeName;
  609. // Read all the records for this type table.
  610. while (1) {
  611. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  612. switch (Entry.Kind) {
  613. case BitstreamEntry::SubBlock: // Handled for us already.
  614. case BitstreamEntry::Error:
  615. return Error(MalformedBlock);
  616. case BitstreamEntry::EndBlock:
  617. if (NumRecords != TypeList.size())
  618. return Error(MalformedBlock);
  619. return error_code::success();
  620. case BitstreamEntry::Record:
  621. // The interesting case.
  622. break;
  623. }
  624. // Read a record.
  625. Record.clear();
  626. Type *ResultTy = 0;
  627. switch (Stream.readRecord(Entry.ID, Record)) {
  628. default:
  629. return Error(InvalidValue);
  630. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  631. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  632. // type list. This allows us to reserve space.
  633. if (Record.size() < 1)
  634. return Error(InvalidRecord);
  635. TypeList.resize(Record[0]);
  636. continue;
  637. case bitc::TYPE_CODE_VOID: // VOID
  638. ResultTy = Type::getVoidTy(Context);
  639. break;
  640. case bitc::TYPE_CODE_HALF: // HALF
  641. ResultTy = Type::getHalfTy(Context);
  642. break;
  643. case bitc::TYPE_CODE_FLOAT: // FLOAT
  644. ResultTy = Type::getFloatTy(Context);
  645. break;
  646. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  647. ResultTy = Type::getDoubleTy(Context);
  648. break;
  649. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  650. ResultTy = Type::getX86_FP80Ty(Context);
  651. break;
  652. case bitc::TYPE_CODE_FP128: // FP128
  653. ResultTy = Type::getFP128Ty(Context);
  654. break;
  655. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  656. ResultTy = Type::getPPC_FP128Ty(Context);
  657. break;
  658. case bitc::TYPE_CODE_LABEL: // LABEL
  659. ResultTy = Type::getLabelTy(Context);
  660. break;
  661. case bitc::TYPE_CODE_METADATA: // METADATA
  662. ResultTy = Type::getMetadataTy(Context);
  663. break;
  664. case bitc::TYPE_CODE_X86_MMX: // X86_MMX
  665. ResultTy = Type::getX86_MMXTy(Context);
  666. break;
  667. case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
  668. if (Record.size() < 1)
  669. return Error(InvalidRecord);
  670. ResultTy = IntegerType::get(Context, Record[0]);
  671. break;
  672. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  673. // [pointee type, address space]
  674. if (Record.size() < 1)
  675. return Error(InvalidRecord);
  676. unsigned AddressSpace = 0;
  677. if (Record.size() == 2)
  678. AddressSpace = Record[1];
  679. ResultTy = getTypeByID(Record[0]);
  680. if (ResultTy == 0)
  681. return Error(InvalidType);
  682. ResultTy = PointerType::get(ResultTy, AddressSpace);
  683. break;
  684. }
  685. case bitc::TYPE_CODE_FUNCTION_OLD: {
  686. // FIXME: attrid is dead, remove it in LLVM 4.0
  687. // FUNCTION: [vararg, attrid, retty, paramty x N]
  688. if (Record.size() < 3)
  689. return Error(InvalidRecord);
  690. SmallVector<Type*, 8> ArgTys;
  691. for (unsigned i = 3, e = Record.size(); i != e; ++i) {
  692. if (Type *T = getTypeByID(Record[i]))
  693. ArgTys.push_back(T);
  694. else
  695. break;
  696. }
  697. ResultTy = getTypeByID(Record[2]);
  698. if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
  699. return Error(InvalidType);
  700. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  701. break;
  702. }
  703. case bitc::TYPE_CODE_FUNCTION: {
  704. // FUNCTION: [vararg, retty, paramty x N]
  705. if (Record.size() < 2)
  706. return Error(InvalidRecord);
  707. SmallVector<Type*, 8> ArgTys;
  708. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  709. if (Type *T = getTypeByID(Record[i]))
  710. ArgTys.push_back(T);
  711. else
  712. break;
  713. }
  714. ResultTy = getTypeByID(Record[1]);
  715. if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
  716. return Error(InvalidType);
  717. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  718. break;
  719. }
  720. case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
  721. if (Record.size() < 1)
  722. return Error(InvalidRecord);
  723. SmallVector<Type*, 8> EltTys;
  724. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  725. if (Type *T = getTypeByID(Record[i]))
  726. EltTys.push_back(T);
  727. else
  728. break;
  729. }
  730. if (EltTys.size() != Record.size()-1)
  731. return Error(InvalidType);
  732. ResultTy = StructType::get(Context, EltTys, Record[0]);
  733. break;
  734. }
  735. case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
  736. if (ConvertToString(Record, 0, TypeName))
  737. return Error(InvalidRecord);
  738. continue;
  739. case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
  740. if (Record.size() < 1)
  741. return Error(InvalidRecord);
  742. if (NumRecords >= TypeList.size())
  743. return Error(InvalidTYPETable);
  744. // Check to see if this was forward referenced, if so fill in the temp.
  745. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  746. if (Res) {
  747. Res->setName(TypeName);
  748. TypeList[NumRecords] = 0;
  749. } else // Otherwise, create a new struct.
  750. Res = StructType::create(Context, TypeName);
  751. TypeName.clear();
  752. SmallVector<Type*, 8> EltTys;
  753. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  754. if (Type *T = getTypeByID(Record[i]))
  755. EltTys.push_back(T);
  756. else
  757. break;
  758. }
  759. if (EltTys.size() != Record.size()-1)
  760. return Error(InvalidRecord);
  761. Res->setBody(EltTys, Record[0]);
  762. ResultTy = Res;
  763. break;
  764. }
  765. case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
  766. if (Record.size() != 1)
  767. return Error(InvalidRecord);
  768. if (NumRecords >= TypeList.size())
  769. return Error(InvalidTYPETable);
  770. // Check to see if this was forward referenced, if so fill in the temp.
  771. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  772. if (Res) {
  773. Res->setName(TypeName);
  774. TypeList[NumRecords] = 0;
  775. } else // Otherwise, create a new struct with no body.
  776. Res = StructType::create(Context, TypeName);
  777. TypeName.clear();
  778. ResultTy = Res;
  779. break;
  780. }
  781. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  782. if (Record.size() < 2)
  783. return Error(InvalidRecord);
  784. if ((ResultTy = getTypeByID(Record[1])))
  785. ResultTy = ArrayType::get(ResultTy, Record[0]);
  786. else
  787. return Error(InvalidType);
  788. break;
  789. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  790. if (Record.size() < 2)
  791. return Error(InvalidRecord);
  792. if ((ResultTy = getTypeByID(Record[1])))
  793. ResultTy = VectorType::get(ResultTy, Record[0]);
  794. else
  795. return Error(InvalidType);
  796. break;
  797. }
  798. if (NumRecords >= TypeList.size())
  799. return Error(InvalidTYPETable);
  800. assert(ResultTy && "Didn't read a type?");
  801. assert(TypeList[NumRecords] == 0 && "Already read type?");
  802. TypeList[NumRecords++] = ResultTy;
  803. }
  804. }
  805. error_code BitcodeReader::ParseValueSymbolTable() {
  806. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  807. return Error(InvalidRecord);
  808. SmallVector<uint64_t, 64> Record;
  809. // Read all the records for this value table.
  810. SmallString<128> ValueName;
  811. while (1) {
  812. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  813. switch (Entry.Kind) {
  814. case BitstreamEntry::SubBlock: // Handled for us already.
  815. case BitstreamEntry::Error:
  816. return Error(MalformedBlock);
  817. case BitstreamEntry::EndBlock:
  818. return error_code::success();
  819. case BitstreamEntry::Record:
  820. // The interesting case.
  821. break;
  822. }
  823. // Read a record.
  824. Record.clear();
  825. switch (Stream.readRecord(Entry.ID, Record)) {
  826. default: // Default behavior: unknown type.
  827. break;
  828. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  829. if (ConvertToString(Record, 1, ValueName))
  830. return Error(InvalidRecord);
  831. unsigned ValueID = Record[0];
  832. if (ValueID >= ValueList.size())
  833. return Error(InvalidRecord);
  834. Value *V = ValueList[ValueID];
  835. V->setName(StringRef(ValueName.data(), ValueName.size()));
  836. ValueName.clear();
  837. break;
  838. }
  839. case bitc::VST_CODE_BBENTRY: {
  840. if (ConvertToString(Record, 1, ValueName))
  841. return Error(InvalidRecord);
  842. BasicBlock *BB = getBasicBlock(Record[0]);
  843. if (BB == 0)
  844. return Error(InvalidRecord);
  845. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  846. ValueName.clear();
  847. break;
  848. }
  849. }
  850. }
  851. }
  852. error_code BitcodeReader::ParseMetadata() {
  853. unsigned NextMDValueNo = MDValueList.size();
  854. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  855. return Error(InvalidRecord);
  856. SmallVector<uint64_t, 64> Record;
  857. // Read all the records.
  858. while (1) {
  859. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  860. switch (Entry.Kind) {
  861. case BitstreamEntry::SubBlock: // Handled for us already.
  862. case BitstreamEntry::Error:
  863. return Error(MalformedBlock);
  864. case BitstreamEntry::EndBlock:
  865. return error_code::success();
  866. case BitstreamEntry::Record:
  867. // The interesting case.
  868. break;
  869. }
  870. bool IsFunctionLocal = false;
  871. // Read a record.
  872. Record.clear();
  873. unsigned Code = Stream.readRecord(Entry.ID, Record);
  874. switch (Code) {
  875. default: // Default behavior: ignore.
  876. break;
  877. case bitc::METADATA_NAME: {
  878. // Read name of the named metadata.
  879. SmallString<8> Name(Record.begin(), Record.end());
  880. Record.clear();
  881. Code = Stream.ReadCode();
  882. // METADATA_NAME is always followed by METADATA_NAMED_NODE.
  883. unsigned NextBitCode = Stream.readRecord(Code, Record);
  884. assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
  885. // Read named metadata elements.
  886. unsigned Size = Record.size();
  887. NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
  888. for (unsigned i = 0; i != Size; ++i) {
  889. MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
  890. if (MD == 0)
  891. return Error(InvalidRecord);
  892. NMD->addOperand(MD);
  893. }
  894. break;
  895. }
  896. case bitc::METADATA_FN_NODE:
  897. IsFunctionLocal = true;
  898. // fall-through
  899. case bitc::METADATA_NODE: {
  900. if (Record.size() % 2 == 1)
  901. return Error(InvalidRecord);
  902. unsigned Size = Record.size();
  903. SmallVector<Value*, 8> Elts;
  904. for (unsigned i = 0; i != Size; i += 2) {
  905. Type *Ty = getTypeByID(Record[i]);
  906. if (!Ty)
  907. return Error(InvalidRecord);
  908. if (Ty->isMetadataTy())
  909. Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
  910. else if (!Ty->isVoidTy())
  911. Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
  912. else
  913. Elts.push_back(NULL);
  914. }
  915. Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
  916. IsFunctionLocal = false;
  917. MDValueList.AssignValue(V, NextMDValueNo++);
  918. break;
  919. }
  920. case bitc::METADATA_STRING: {
  921. SmallString<8> String(Record.begin(), Record.end());
  922. Value *V = MDString::get(Context, String);
  923. MDValueList.AssignValue(V, NextMDValueNo++);
  924. break;
  925. }
  926. case bitc::METADATA_KIND: {
  927. if (Record.size() < 2)
  928. return Error(InvalidRecord);
  929. unsigned Kind = Record[0];
  930. SmallString<8> Name(Record.begin()+1, Record.end());
  931. unsigned NewKind = TheModule->getMDKindID(Name.str());
  932. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  933. return Error(ConflictingMETADATA_KINDRecords);
  934. break;
  935. }
  936. }
  937. }
  938. }
  939. /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
  940. /// the LSB for dense VBR encoding.
  941. uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
  942. if ((V & 1) == 0)
  943. return V >> 1;
  944. if (V != 1)
  945. return -(V >> 1);
  946. // There is no such thing as -0 with integers. "-0" really means MININT.
  947. return 1ULL << 63;
  948. }
  949. /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
  950. /// values and aliases that we can.
  951. error_code BitcodeReader::ResolveGlobalAndAliasInits() {
  952. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  953. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  954. std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
  955. GlobalInitWorklist.swap(GlobalInits);
  956. AliasInitWorklist.swap(AliasInits);
  957. FunctionPrefixWorklist.swap(FunctionPrefixes);
  958. while (!GlobalInitWorklist.empty()) {
  959. unsigned ValID = GlobalInitWorklist.back().second;
  960. if (ValID >= ValueList.size()) {
  961. // Not ready to resolve this yet, it requires something later in the file.
  962. GlobalInits.push_back(GlobalInitWorklist.back());
  963. } else {
  964. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  965. GlobalInitWorklist.back().first->setInitializer(C);
  966. else
  967. return Error(ExpectedConstant);
  968. }
  969. GlobalInitWorklist.pop_back();
  970. }
  971. while (!AliasInitWorklist.empty()) {
  972. unsigned ValID = AliasInitWorklist.back().second;
  973. if (ValID >= ValueList.size()) {
  974. AliasInits.push_back(AliasInitWorklist.back());
  975. } else {
  976. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  977. AliasInitWorklist.back().first->setAliasee(C);
  978. else
  979. return Error(ExpectedConstant);
  980. }
  981. AliasInitWorklist.pop_back();
  982. }
  983. while (!FunctionPrefixWorklist.empty()) {
  984. unsigned ValID = FunctionPrefixWorklist.back().second;
  985. if (ValID >= ValueList.size()) {
  986. FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
  987. } else {
  988. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  989. FunctionPrefixWorklist.back().first->setPrefixData(C);
  990. else
  991. return Error(ExpectedConstant);
  992. }
  993. FunctionPrefixWorklist.pop_back();
  994. }
  995. return error_code::success();
  996. }
  997. static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
  998. SmallVector<uint64_t, 8> Words(Vals.size());
  999. std::transform(Vals.begin(), Vals.end(), Words.begin(),
  1000. BitcodeReader::decodeSignRotatedValue);
  1001. return APInt(TypeBits, Words);
  1002. }
  1003. error_code BitcodeReader::ParseConstants() {
  1004. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  1005. return Error(InvalidRecord);
  1006. SmallVector<uint64_t, 64> Record;
  1007. // Read all the records for this value table.
  1008. Type *CurTy = Type::getInt32Ty(Context);
  1009. unsigned NextCstNo = ValueList.size();
  1010. while (1) {
  1011. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1012. switch (Entry.Kind) {
  1013. case BitstreamEntry::SubBlock: // Handled for us already.
  1014. case BitstreamEntry::Error:
  1015. return Error(MalformedBlock);
  1016. case BitstreamEntry::EndBlock:
  1017. if (NextCstNo != ValueList.size())
  1018. return Error(InvalidConstantReference);
  1019. // Once all the constants have been read, go through and resolve forward
  1020. // references.
  1021. ValueList.ResolveConstantForwardRefs();
  1022. return error_code::success();
  1023. case BitstreamEntry::Record:
  1024. // The interesting case.
  1025. break;
  1026. }
  1027. // Read a record.
  1028. Record.clear();
  1029. Value *V = 0;
  1030. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  1031. switch (BitCode) {
  1032. default: // Default behavior: unknown constant
  1033. case bitc::CST_CODE_UNDEF: // UNDEF
  1034. V = UndefValue::get(CurTy);
  1035. break;
  1036. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  1037. if (Record.empty())
  1038. return Error(InvalidRecord);
  1039. if (Record[0] >= TypeList.size())
  1040. return Error(InvalidRecord);
  1041. CurTy = TypeList[Record[0]];
  1042. continue; // Skip the ValueList manipulation.
  1043. case bitc::CST_CODE_NULL: // NULL
  1044. V = Constant::getNullValue(CurTy);
  1045. break;
  1046. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  1047. if (!CurTy->isIntegerTy() || Record.empty())
  1048. return Error(InvalidRecord);
  1049. V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
  1050. break;
  1051. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  1052. if (!CurTy->isIntegerTy() || Record.empty())
  1053. return Error(InvalidRecord);
  1054. APInt VInt = ReadWideAPInt(Record,
  1055. cast<IntegerType>(CurTy)->getBitWidth());
  1056. V = ConstantInt::get(Context, VInt);
  1057. break;
  1058. }
  1059. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  1060. if (Record.empty())
  1061. return Error(InvalidRecord);
  1062. if (CurTy->isHalfTy())
  1063. V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
  1064. APInt(16, (uint16_t)Record[0])));
  1065. else if (CurTy->isFloatTy())
  1066. V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
  1067. APInt(32, (uint32_t)Record[0])));
  1068. else if (CurTy->isDoubleTy())
  1069. V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
  1070. APInt(64, Record[0])));
  1071. else if (CurTy->isX86_FP80Ty()) {
  1072. // Bits are not stored the same way as a normal i80 APInt, compensate.
  1073. uint64_t Rearrange[2];
  1074. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  1075. Rearrange[1] = Record[0] >> 48;
  1076. V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
  1077. APInt(80, Rearrange)));
  1078. } else if (CurTy->isFP128Ty())
  1079. V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
  1080. APInt(128, Record)));
  1081. else if (CurTy->isPPC_FP128Ty())
  1082. V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
  1083. APInt(128, Record)));
  1084. else
  1085. V = UndefValue::get(CurTy);
  1086. break;
  1087. }
  1088. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  1089. if (Record.empty())
  1090. return Error(InvalidRecord);
  1091. unsigned Size = Record.size();
  1092. SmallVector<Constant*, 16> Elts;
  1093. if (StructType *STy = dyn_cast<StructType>(CurTy)) {
  1094. for (unsigned i = 0; i != Size; ++i)
  1095. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  1096. STy->getElementType(i)));
  1097. V = ConstantStruct::get(STy, Elts);
  1098. } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  1099. Type *EltTy = ATy->getElementType();
  1100. for (unsigned i = 0; i != Size; ++i)
  1101. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  1102. V = ConstantArray::get(ATy, Elts);
  1103. } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  1104. Type *EltTy = VTy->getElementType();
  1105. for (unsigned i = 0; i != Size; ++i)
  1106. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  1107. V = ConstantVector::get(Elts);
  1108. } else {
  1109. V = UndefValue::get(CurTy);
  1110. }
  1111. break;
  1112. }
  1113. case bitc::CST_CODE_STRING: // STRING: [values]
  1114. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  1115. if (Record.empty())
  1116. return Error(InvalidRecord);
  1117. SmallString<16> Elts(Record.begin(), Record.end());
  1118. V = ConstantDataArray::getString(Context, Elts,
  1119. BitCode == bitc::CST_CODE_CSTRING);
  1120. break;
  1121. }
  1122. case bitc::CST_CODE_DATA: {// DATA: [n x value]
  1123. if (Record.empty())
  1124. return Error(InvalidRecord);
  1125. Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
  1126. unsigned Size = Record.size();
  1127. if (EltTy->isIntegerTy(8)) {
  1128. SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
  1129. if (isa<VectorType>(CurTy))
  1130. V = ConstantDataVector::get(Context, Elts);
  1131. else
  1132. V = ConstantDataArray::get(Context, Elts);
  1133. } else if (EltTy->isIntegerTy(16)) {
  1134. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  1135. if (isa<VectorType>(CurTy))
  1136. V = ConstantDataVector::get(Context, Elts);
  1137. else
  1138. V = ConstantDataArray::get(Context, Elts);
  1139. } else if (EltTy->isIntegerTy(32)) {
  1140. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  1141. if (isa<VectorType>(CurTy))
  1142. V = ConstantDataVector::get(Context, Elts);
  1143. else
  1144. V = ConstantDataArray::get(Context, Elts);
  1145. } else if (EltTy->isIntegerTy(64)) {
  1146. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  1147. if (isa<VectorType>(CurTy))
  1148. V = ConstantDataVector::get(Context, Elts);
  1149. else
  1150. V = ConstantDataArray::get(Context, Elts);
  1151. } else if (EltTy->isFloatTy()) {
  1152. SmallVector<float, 16> Elts(Size);
  1153. std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
  1154. if (isa<VectorType>(CurTy))
  1155. V = ConstantDataVector::get(Context, Elts);
  1156. else
  1157. V = ConstantDataArray::get(Context, Elts);
  1158. } else if (EltTy->isDoubleTy()) {
  1159. SmallVector<double, 16> Elts(Size);
  1160. std::transform(Record.begin(), Record.end(), Elts.begin(),
  1161. BitsToDouble);
  1162. if (isa<VectorType>(CurTy))
  1163. V = ConstantDataVector::get(Context, Elts);
  1164. else
  1165. V = ConstantDataArray::get(Context, Elts);
  1166. } else {
  1167. return Error(InvalidTypeForValue);
  1168. }
  1169. break;
  1170. }
  1171. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  1172. if (Record.size() < 3)
  1173. return Error(InvalidRecord);
  1174. int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
  1175. if (Opc < 0) {
  1176. V = UndefValue::get(CurTy); // Unknown binop.
  1177. } else {
  1178. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  1179. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  1180. unsigned Flags = 0;
  1181. if (Record.size() >= 4) {
  1182. if (Opc == Instruction::Add ||
  1183. Opc == Instruction::Sub ||
  1184. Opc == Instruction::Mul ||
  1185. Opc == Instruction::Shl) {
  1186. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  1187. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  1188. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  1189. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  1190. } else if (Opc == Instruction::SDiv ||
  1191. Opc == Instruction::UDiv ||
  1192. Opc == Instruction::LShr ||
  1193. Opc == Instruction::AShr) {
  1194. if (Record[3] & (1 << bitc::PEO_EXACT))
  1195. Flags |= SDivOperator::IsExact;
  1196. }
  1197. }
  1198. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  1199. }
  1200. break;
  1201. }
  1202. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  1203. if (Record.size() < 3)
  1204. return Error(InvalidRecord);
  1205. int Opc = GetDecodedCastOpcode(Record[0]);
  1206. if (Opc < 0) {
  1207. V = UndefValue::get(CurTy); // Unknown cast.
  1208. } else {
  1209. Type *OpTy = getTypeByID(Record[1]);
  1210. if (!OpTy)
  1211. return Error(InvalidRecord);
  1212. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  1213. V = UpgradeBitCastExpr(Opc, Op, CurTy);
  1214. if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
  1215. }
  1216. break;
  1217. }
  1218. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  1219. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  1220. if (Record.size() & 1)
  1221. return Error(InvalidRecord);
  1222. SmallVector<Constant*, 16> Elts;
  1223. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  1224. Type *ElTy = getTypeByID(Record[i]);
  1225. if (!ElTy)
  1226. return Error(InvalidRecord);
  1227. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
  1228. }
  1229. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  1230. V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
  1231. BitCode ==
  1232. bitc::CST_CODE_CE_INBOUNDS_GEP);
  1233. break;
  1234. }
  1235. case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
  1236. if (Record.size() < 3)
  1237. return Error(InvalidRecord);
  1238. Type *SelectorTy = Type::getInt1Ty(Context);
  1239. // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
  1240. // vector. Otherwise, it must be a single bit.
  1241. if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
  1242. SelectorTy = VectorType::get(Type::getInt1Ty(Context),
  1243. VTy->getNumElements());
  1244. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  1245. SelectorTy),
  1246. ValueList.getConstantFwdRef(Record[1],CurTy),
  1247. ValueList.getConstantFwdRef(Record[2],CurTy));
  1248. break;
  1249. }
  1250. case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
  1251. if (Record.size() < 3)
  1252. return Error(InvalidRecord);
  1253. VectorType *OpTy =
  1254. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1255. if (OpTy == 0)
  1256. return Error(InvalidRecord);
  1257. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1258. Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
  1259. Type::getInt32Ty(Context));
  1260. V = ConstantExpr::getExtractElement(Op0, Op1);
  1261. break;
  1262. }
  1263. case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
  1264. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1265. if (Record.size() < 3 || OpTy == 0)
  1266. return Error(InvalidRecord);
  1267. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1268. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  1269. OpTy->getElementType());
  1270. Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
  1271. Type::getInt32Ty(Context));
  1272. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  1273. break;
  1274. }
  1275. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  1276. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1277. if (Record.size() < 3 || OpTy == 0)
  1278. return Error(InvalidRecord);
  1279. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1280. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1281. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1282. OpTy->getNumElements());
  1283. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  1284. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1285. break;
  1286. }
  1287. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  1288. VectorType *RTy = dyn_cast<VectorType>(CurTy);
  1289. VectorType *OpTy =
  1290. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1291. if (Record.size() < 4 || RTy == 0 || OpTy == 0)
  1292. return Error(InvalidRecord);
  1293. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1294. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1295. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1296. RTy->getNumElements());
  1297. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  1298. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1299. break;
  1300. }
  1301. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  1302. if (Record.size() < 4)
  1303. return Error(InvalidRecord);
  1304. Type *OpTy = getTypeByID(Record[0]);
  1305. if (OpTy == 0)
  1306. return Error(InvalidRecord);
  1307. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1308. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1309. if (OpTy->isFPOrFPVectorTy())
  1310. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  1311. else
  1312. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  1313. break;
  1314. }
  1315. // This maintains backward compatibility, pre-asm dialect keywords.
  1316. // FIXME: Remove with the 4.0 release.
  1317. case bitc::CST_CODE_INLINEASM_OLD: {
  1318. if (Record.size() < 2)
  1319. return Error(InvalidRecord);
  1320. std::string AsmStr, ConstrStr;
  1321. bool HasSideEffects = Record[0] & 1;
  1322. bool IsAlignStack = Record[0] >> 1;
  1323. unsigned AsmStrSize = Record[1];
  1324. if (2+AsmStrSize >= Record.size())
  1325. return Error(InvalidRecord);
  1326. unsigned ConstStrSize = Record[2+AsmStrSize];
  1327. if (3+AsmStrSize+ConstStrSize > Record.size())
  1328. return Error(InvalidRecord);
  1329. for (unsigned i = 0; i != AsmStrSize; ++i)
  1330. AsmStr += (char)Record[2+i];
  1331. for (unsigned i = 0; i != ConstStrSize; ++i)
  1332. ConstrStr += (char)Record[3+AsmStrSize+i];
  1333. PointerType *PTy = cast<PointerType>(CurTy);
  1334. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  1335. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  1336. break;
  1337. }
  1338. // This version adds support for the asm dialect keywords (e.g.,
  1339. // inteldialect).
  1340. case bitc::CST_CODE_INLINEASM: {
  1341. if (Record.size() < 2)
  1342. return Error(InvalidRecord);
  1343. std::string AsmStr, ConstrStr;
  1344. bool HasSideEffects = Record[0] & 1;
  1345. bool IsAlignStack = (Record[0] >> 1) & 1;
  1346. unsigned AsmDialect = Record[0] >> 2;
  1347. unsigned AsmStrSize = Record[1];
  1348. if (2+AsmStrSize >= Record.size())
  1349. return Error(InvalidRecord);
  1350. unsigned ConstStrSize = Record[2+AsmStrSize];
  1351. if (3+AsmStrSize+ConstStrSize > Record.size())
  1352. return Error(InvalidRecord);
  1353. for (unsigned i = 0; i != AsmStrSize; ++i)
  1354. AsmStr += (char)Record[2+i];
  1355. for (unsigned i = 0; i != ConstStrSize; ++i)
  1356. ConstrStr += (char)Record[3+AsmStrSize+i];
  1357. PointerType *PTy = cast<PointerType>(CurTy);
  1358. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  1359. AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
  1360. InlineAsm::AsmDialect(AsmDialect));
  1361. break;
  1362. }
  1363. case bitc::CST_CODE_BLOCKADDRESS:{
  1364. if (Record.size() < 3)
  1365. return Error(InvalidRecord);
  1366. Type *FnTy = getTypeByID(Record[0]);
  1367. if (FnTy == 0)
  1368. return Error(InvalidRecord);
  1369. Function *Fn =
  1370. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  1371. if (Fn == 0)
  1372. return Error(InvalidRecord);
  1373. // If the function is already parsed we can insert the block address right
  1374. // away.
  1375. if (!Fn->empty()) {
  1376. Function::iterator BBI = Fn->begin(), BBE = Fn->end();
  1377. for (size_t I = 0, E = Record[2]; I != E; ++I) {
  1378. if (BBI == BBE)
  1379. return Error(InvalidID);
  1380. ++BBI;
  1381. }
  1382. V = BlockAddress::get(Fn, BBI);
  1383. } else {
  1384. // Otherwise insert a placeholder and remember it so it can be inserted
  1385. // when the function is parsed.
  1386. GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
  1387. Type::getInt8Ty(Context),
  1388. false, GlobalValue::InternalLinkage,
  1389. 0, "");
  1390. BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
  1391. V = FwdRef;
  1392. }
  1393. break;
  1394. }
  1395. }
  1396. ValueList.AssignValue(V, NextCstNo);
  1397. ++NextCstNo;
  1398. }
  1399. }
  1400. error_code BitcodeReader::ParseUseLists() {
  1401. if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
  1402. return Error(InvalidRecord);
  1403. SmallVector<uint64_t, 64> Record;
  1404. // Read all the records.
  1405. while (1) {
  1406. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1407. switch (Entry.Kind) {
  1408. case BitstreamEntry::SubBlock: // Handled for us already.
  1409. case BitstreamEntry::Error:
  1410. return Error(MalformedBlock);
  1411. case BitstreamEntry::EndBlock:
  1412. return error_code::success();
  1413. case BitstreamEntry::Record:
  1414. // The interesting case.
  1415. break;
  1416. }
  1417. // Read a use list record.
  1418. Record.clear();
  1419. switch (Stream.readRecord(Entry.ID, Record)) {
  1420. default: // Default behavior: unknown type.
  1421. break;
  1422. case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
  1423. unsigned RecordLength = Record.size();
  1424. if (RecordLength < 1)
  1425. return Error(InvalidRecord);
  1426. UseListRecords.push_back(Record);
  1427. break;
  1428. }
  1429. }
  1430. }
  1431. }
  1432. /// RememberAndSkipFunctionBody - When we see the block for a function body,
  1433. /// remember where it is and then skip it. This lets us lazily deserialize the
  1434. /// functions.
  1435. error_code BitcodeReader::RememberAndSkipFunctionBody() {
  1436. // Get the function we are talking about.
  1437. if (FunctionsWithBodies.empty())
  1438. return Error(InsufficientFunctionProtos);
  1439. Function *Fn = FunctionsWithBodies.back();
  1440. FunctionsWithBodies.pop_back();
  1441. // Save the current stream state.
  1442. uint64_t CurBit = Stream.GetCurrentBitNo();
  1443. DeferredFunctionInfo[Fn] = CurBit;
  1444. // Skip over the function block for now.
  1445. if (Stream.SkipBlock())
  1446. return Error(InvalidRecord);
  1447. return error_code::success();
  1448. }
  1449. error_code BitcodeReader::GlobalCleanup() {
  1450. // Patch the initializers for globals and aliases up.
  1451. ResolveGlobalAndAliasInits();
  1452. if (!GlobalInits.empty() || !AliasInits.empty())
  1453. return Error(MalformedGlobalInitializerSet);
  1454. // Look for intrinsic functions which need to be upgraded at some point
  1455. for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
  1456. FI != FE; ++FI) {
  1457. Function *NewFn;
  1458. if (UpgradeIntrinsicFunction(FI, NewFn))
  1459. UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
  1460. }
  1461. // Look for global variables which need to be renamed.
  1462. for (Module::global_iterator
  1463. GI = TheModule->global_begin(), GE = TheModule->global_end();
  1464. GI != GE; ++GI)
  1465. UpgradeGlobalVariable(GI);
  1466. // Force deallocation of memory for these vectors to favor the client that
  1467. // want lazy deserialization.
  1468. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  1469. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  1470. return error_code::success();
  1471. }
  1472. error_code BitcodeReader::ParseModule(bool Resume) {
  1473. if (Resume)
  1474. Stream.JumpToBit(NextUnreadBit);
  1475. else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  1476. return Error(InvalidRecord);
  1477. SmallVector<uint64_t, 64> Record;
  1478. std::vector<std::string> SectionTable;
  1479. std::vector<std::string> GCTable;
  1480. // Read all the records for this module.
  1481. while (1) {
  1482. BitstreamEntry Entry = Stream.advance();
  1483. switch (Entry.Kind) {
  1484. case BitstreamEntry::Error:
  1485. return Error(MalformedBlock);
  1486. case BitstreamEntry::EndBlock:
  1487. return GlobalCleanup();
  1488. case BitstreamEntry::SubBlock:
  1489. switch (Entry.ID) {
  1490. default: // Skip unknown content.
  1491. if (Stream.SkipBlock())
  1492. return Error(InvalidRecord);
  1493. break;
  1494. case bitc::BLOCKINFO_BLOCK_ID:
  1495. if (Stream.ReadBlockInfoBlock())
  1496. return Error(MalformedBlock);
  1497. break;
  1498. case bitc::PARAMATTR_BLOCK_ID:
  1499. if (error_code EC = ParseAttributeBlock())
  1500. return EC;
  1501. break;
  1502. case bitc::PARAMATTR_GROUP_BLOCK_ID:
  1503. if (error_code EC = ParseAttributeGroupBlock())
  1504. return EC;
  1505. break;
  1506. case bitc::TYPE_BLOCK_ID_NEW:
  1507. if (error_code EC = ParseTypeTable())
  1508. return EC;
  1509. break;
  1510. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1511. if (error_code EC = ParseValueSymbolTable())
  1512. return EC;
  1513. SeenValueSymbolTable = true;
  1514. break;
  1515. case bitc::CONSTANTS_BLOCK_ID:
  1516. if (error_code EC = ParseConstants())
  1517. return EC;
  1518. if (error_code EC = ResolveGlobalAndAliasInits())
  1519. return EC;
  1520. break;
  1521. case bitc::METADATA_BLOCK_ID:
  1522. if (error_code EC = ParseMetadata())
  1523. return EC;
  1524. break;
  1525. case bitc::FUNCTION_BLOCK_ID:
  1526. // If this is the first function body we've seen, reverse the
  1527. // FunctionsWithBodies list.
  1528. if (!SeenFirstFunctionBody) {
  1529. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  1530. if (error_code EC = GlobalCleanup())
  1531. return EC;
  1532. SeenFirstFunctionBody = true;
  1533. }
  1534. if (error_code EC = RememberAndSkipFunctionBody())
  1535. return EC;
  1536. // For streaming bitcode, suspend parsing when we reach the function
  1537. // bodies. Subsequent materialization calls will resume it when
  1538. // necessary. For streaming, the function bodies must be at the end of
  1539. // the bitcode. If the bitcode file is old, the symbol table will be
  1540. // at the end instead and will not have been seen yet. In this case,
  1541. // just finish the parse now.
  1542. if (LazyStreamer && SeenValueSymbolTable) {
  1543. NextUnreadBit = Stream.GetCurrentBitNo();
  1544. return error_code::success();
  1545. }
  1546. break;
  1547. case bitc::USELIST_BLOCK_ID:
  1548. if (error_code EC = ParseUseLists())
  1549. return EC;
  1550. break;
  1551. }
  1552. continue;
  1553. case BitstreamEntry::Record:
  1554. // The interesting case.
  1555. break;
  1556. }
  1557. // Read a record.
  1558. switch (Stream.readRecord(Entry.ID, Record)) {
  1559. default: break; // Default behavior, ignore unknown content.
  1560. case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
  1561. if (Record.size() < 1)
  1562. return Error(InvalidRecord);
  1563. // Only version #0 and #1 are supported so far.
  1564. unsigned module_version = Record[0];
  1565. switch (module_version) {
  1566. default:
  1567. return Error(InvalidValue);
  1568. case 0:
  1569. UseRelativeIDs = false;
  1570. break;
  1571. case 1:
  1572. UseRelativeIDs = true;
  1573. break;
  1574. }
  1575. break;
  1576. }
  1577. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  1578. std::string S;
  1579. if (ConvertToString(Record, 0, S))
  1580. return Error(InvalidRecord);
  1581. TheModule->setTargetTriple(S);
  1582. break;
  1583. }
  1584. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  1585. std::string S;
  1586. if (ConvertToString(Record, 0, S))
  1587. return Error(InvalidRecord);
  1588. TheModule->setDataLayout(S);
  1589. break;
  1590. }
  1591. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  1592. std::string S;
  1593. if (ConvertToString(Record, 0, S))
  1594. return Error(InvalidRecord);
  1595. TheModule->setModuleInlineAsm(S);
  1596. break;
  1597. }
  1598. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  1599. // FIXME: Remove in 4.0.
  1600. std::string S;
  1601. if (ConvertToString(Record, 0, S))
  1602. return Error(InvalidRecord);
  1603. // Ignore value.
  1604. break;
  1605. }
  1606. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  1607. std::string S;
  1608. if (ConvertToString(Record, 0, S))
  1609. return Error(InvalidRecord);
  1610. SectionTable.push_back(S);
  1611. break;
  1612. }
  1613. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  1614. std::string S;
  1615. if (ConvertToString(Record, 0, S))
  1616. return Error(InvalidRecord);
  1617. GCTable.push_back(S);
  1618. break;
  1619. }
  1620. // GLOBALVAR: [pointer type, isconst, initid,
  1621. // linkage, alignment, section, visibility, threadlocal,
  1622. // unnamed_addr]
  1623. case bitc::MODULE_CODE_GLOBALVAR: {
  1624. if (Record.size() < 6)
  1625. return Error(InvalidRecord);
  1626. Type *Ty = getTypeByID(Record[0]);
  1627. if (!Ty)
  1628. return Error(InvalidRecord);
  1629. if (!Ty->isPointerTy())
  1630. return Error(InvalidTypeForValue);
  1631. unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  1632. Ty = cast<PointerType>(Ty)->getElementType();
  1633. bool isConstant = Record[1];
  1634. GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
  1635. unsigned Alignment = (1 << Record[4]) >> 1;
  1636. std::string Section;
  1637. if (Record[5]) {
  1638. if (Record[5]-1 >= SectionTable.size())
  1639. return Error(InvalidID);
  1640. Section = SectionTable[Record[5]-1];
  1641. }
  1642. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  1643. if (Record.size() > 6)
  1644. Visibility = GetDecodedVisibility(Record[6]);
  1645. GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
  1646. if (Record.size() > 7)
  1647. TLM = GetDecodedThreadLocalMode(Record[7]);
  1648. bool UnnamedAddr = false;
  1649. if (Record.size() > 8)
  1650. UnnamedAddr = Record[8];
  1651. bool ExternallyInitialized = false;
  1652. if (Record.size() > 9)
  1653. ExternallyInitialized = Record[9];
  1654. GlobalVariable *NewGV =
  1655. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
  1656. TLM, AddressSpace, ExternallyInitialized);
  1657. NewGV->setAlignment(Alignment);
  1658. if (!Section.empty())
  1659. NewGV->setSection(Section);
  1660. NewGV->setVisibility(Visibility);
  1661. NewGV->setUnnamedAddr(UnnamedAddr);
  1662. ValueList.push_back(NewGV);
  1663. // Remember which value to use for the global initializer.
  1664. if (unsigned InitID = Record[2])
  1665. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  1666. break;
  1667. }
  1668. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  1669. // alignment, section, visibility, gc, unnamed_addr]
  1670. case bitc::MODULE_CODE_FUNCTION: {
  1671. if (Record.size() < 8)
  1672. return Error(InvalidRecord);
  1673. Type *Ty = getTypeByID(Record[0]);
  1674. if (!Ty)
  1675. return Error(InvalidRecord);
  1676. if (!Ty->isPointerTy())
  1677. return Error(InvalidTypeForValue);
  1678. FunctionType *FTy =
  1679. dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  1680. if (!FTy)
  1681. return Error(InvalidTypeForValue);
  1682. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  1683. "", TheModule);
  1684. Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
  1685. bool isProto = Record[2];
  1686. Func->setLinkage(GetDecodedLinkage(Record[3]));
  1687. Func->setAttributes(getAttributes(Record[4]));
  1688. Func->setAlignment((1 << Record[5]) >> 1);
  1689. if (Record[6]) {
  1690. if (Record[6]-1 >= SectionTable.size())
  1691. return Error(InvalidID);
  1692. Func->setSection(SectionTable[Record[6]-1]);
  1693. }
  1694. Func->setVisibility(GetDecodedVisibility(Record[7]));
  1695. if (Record.size() > 8 && Record[8]) {
  1696. if (Record[8]-1 > GCTable.size())
  1697. return Error(InvalidID);
  1698. Func->setGC(GCTable[Record[8]-1].c_str());
  1699. }
  1700. bool UnnamedAddr = false;
  1701. if (Record.size() > 9)
  1702. UnnamedAddr = Record[9];
  1703. Func->setUnnamedAddr(UnnamedAddr);
  1704. if (Record.size() > 10 && Record[10] != 0)
  1705. FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
  1706. ValueList.push_back(Func);
  1707. // If this is a function with a body, remember the prototype we are
  1708. // creating now, so that we can match up the body with them later.
  1709. if (!isProto) {
  1710. FunctionsWithBodies.push_back(Func);
  1711. if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
  1712. }
  1713. break;
  1714. }
  1715. // ALIAS: [alias type, aliasee val#, linkage]
  1716. // ALIAS: [alias type, aliasee val#, linkage, visibility]
  1717. case bitc::MODULE_CODE_ALIAS: {
  1718. if (Record.size() < 3)
  1719. return Error(InvalidRecord);
  1720. Type *Ty = getTypeByID(Record[0]);
  1721. if (!Ty)
  1722. return Error(InvalidRecord);
  1723. if (!Ty->isPointerTy())
  1724. return Error(InvalidTypeForValue);
  1725. GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
  1726. "", 0, TheModule);
  1727. // Old bitcode files didn't have visibility field.
  1728. if (Record.size() > 3)
  1729. NewGA->setVisibility(GetDecodedVisibility(Record[3]));
  1730. ValueList.push_back(NewGA);
  1731. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  1732. break;
  1733. }
  1734. /// MODULE_CODE_PURGEVALS: [numvals]
  1735. case bitc::MODULE_CODE_PURGEVALS:
  1736. // Trim down the value list to the specified size.
  1737. if (Record.size() < 1 || Record[0] > ValueList.size())
  1738. return Error(InvalidRecord);
  1739. ValueList.shrinkTo(Record[0]);
  1740. break;
  1741. }
  1742. Record.clear();
  1743. }
  1744. }
  1745. error_code BitcodeReader::ParseBitcodeInto(Module *M) {
  1746. TheModule = 0;
  1747. if (error_code EC = InitStream())
  1748. return EC;
  1749. // Sniff for the signature.
  1750. if (Stream.Read(8) != 'B' ||
  1751. Stream.Read(8) != 'C' ||
  1752. Stream.Read(4) != 0x0 ||
  1753. Stream.Read(4) != 0xC ||
  1754. Stream.Read(4) != 0xE ||
  1755. Stream.Read(4) != 0xD)
  1756. return Error(InvalidBitcodeSignature);
  1757. // We expect a number of well-defined blocks, though we don't necessarily
  1758. // need to understand them all.
  1759. while (1) {
  1760. if (Stream.AtEndOfStream())
  1761. return error_code::success();
  1762. BitstreamEntry Entry =
  1763. Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
  1764. switch (Entry.Kind) {
  1765. case BitstreamEntry::Error:
  1766. return Error(MalformedBlock);
  1767. case BitstreamEntry::EndBlock:
  1768. return error_code::success();
  1769. case BitstreamEntry::SubBlock:
  1770. switch (Entry.ID) {
  1771. case bitc::BLOCKINFO_BLOCK_ID:
  1772. if (Stream.ReadBlockInfoBlock())
  1773. return Error(MalformedBlock);
  1774. break;
  1775. case bitc::MODULE_BLOCK_ID:
  1776. // Reject multiple MODULE_BLOCK's in a single bitstream.
  1777. if (TheModule)
  1778. return Error(InvalidMultipleBlocks);
  1779. TheModule = M;
  1780. if (error_code EC = ParseModule(false))
  1781. return EC;
  1782. if (LazyStreamer)
  1783. return error_code::success();
  1784. break;
  1785. default:
  1786. if (Stream.SkipBlock())
  1787. return Error(InvalidRecord);
  1788. break;
  1789. }
  1790. continue;
  1791. case BitstreamEntry::Record:
  1792. // There should be no records in the top-level of blocks.
  1793. // The ranlib in Xcode 4 will align archive members by appending newlines
  1794. // to the end of them. If this file size is a multiple of 4 but not 8, we
  1795. // have to read and ignore these final 4 bytes :-(
  1796. if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
  1797. Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
  1798. Stream.AtEndOfStream())
  1799. return error_code::success();
  1800. return Error(InvalidRecord);
  1801. }
  1802. }
  1803. }
  1804. error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
  1805. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  1806. return Error(InvalidRecord);
  1807. SmallVector<uint64_t, 64> Record;
  1808. // Read all the records for this module.
  1809. while (1) {
  1810. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1811. switch (Entry.Kind) {
  1812. case BitstreamEntry::SubBlock: // Handled for us already.
  1813. case BitstreamEntry::Error:
  1814. return Error(MalformedBlock);
  1815. case BitstreamEntry::EndBlock:
  1816. return error_code::success();
  1817. case BitstreamEntry::Record:
  1818. // The interesting case.
  1819. break;
  1820. }
  1821. // Read a record.
  1822. switch (Stream.readRecord(Entry.ID, Record)) {
  1823. default: break; // Default behavior, ignore unknown content.
  1824. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  1825. std::string S;
  1826. if (ConvertToString(Record, 0, S))
  1827. return Error(InvalidRecord);
  1828. Triple = S;
  1829. break;
  1830. }
  1831. }
  1832. Record.clear();
  1833. }
  1834. }
  1835. error_code BitcodeReader::ParseTriple(std::string &Triple) {
  1836. if (error_code EC = InitStream())
  1837. return EC;
  1838. // Sniff for the signature.
  1839. if (Stream.Read(8) != 'B' ||
  1840. Stream.Read(8) != 'C' ||
  1841. Stream.Read(4) != 0x0 ||
  1842. Stream.Read(4) != 0xC ||
  1843. Stream.Read(4) != 0xE ||
  1844. Stream.Read(4) != 0xD)
  1845. return Error(InvalidBitcodeSignature);
  1846. // We expect a number of well-defined blocks, though we don't necessarily
  1847. // need to understand them all.
  1848. while (1) {
  1849. BitstreamEntry Entry = Stream.advance();
  1850. switch (Entry.Kind) {
  1851. case BitstreamEntry::Error:
  1852. return Error(MalformedBlock);
  1853. case BitstreamEntry::EndBlock:
  1854. return error_code::success();
  1855. case BitstreamEntry::SubBlock:
  1856. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  1857. return ParseModuleTriple(Triple);
  1858. // Ignore other sub-blocks.
  1859. if (Stream.SkipBlock())
  1860. return Error(MalformedBlock);
  1861. continue;
  1862. case BitstreamEntry::Record:
  1863. Stream.skipRecord(Entry.ID);
  1864. continue;
  1865. }
  1866. }
  1867. }
  1868. /// ParseMetadataAttachment - Parse metadata attachments.
  1869. error_code BitcodeReader::ParseMetadataAttachment() {
  1870. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  1871. return Error(InvalidRecord);
  1872. SmallVector<uint64_t, 64> Record;
  1873. while (1) {
  1874. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1875. switch (Entry.Kind) {
  1876. case BitstreamEntry::SubBlock: // Handled for us already.
  1877. case BitstreamEntry::Error:
  1878. return Error(MalformedBlock);
  1879. case BitstreamEntry::EndBlock:
  1880. return error_code::success();
  1881. case BitstreamEntry::Record:
  1882. // The interesting case.
  1883. break;
  1884. }
  1885. // Read a metadata attachment record.
  1886. Record.clear();
  1887. switch (Stream.readRecord(Entry.ID, Record)) {
  1888. default: // Default behavior: ignore.
  1889. break;
  1890. case bitc::METADATA_ATTACHMENT: {
  1891. unsigned RecordLength = Record.size();
  1892. if (Record.empty() || (RecordLength - 1) % 2 == 1)
  1893. return Error(InvalidRecord);
  1894. Instruction *Inst = InstructionList[Record[0]];
  1895. for (unsigned i = 1; i != RecordLength; i = i+2) {
  1896. unsigned Kind = Record[i];
  1897. DenseMap<unsigned, unsigned>::iterator I =
  1898. MDKindMap.find(Kind);
  1899. if (I == MDKindMap.end())
  1900. return Error(InvalidID);
  1901. Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
  1902. Inst->setMetadata(I->second, cast<MDNode>(Node));
  1903. if (I->second == LLVMContext::MD_tbaa)
  1904. InstsWithTBAATag.push_back(Inst);
  1905. }
  1906. break;
  1907. }
  1908. }
  1909. }
  1910. }
  1911. /// ParseFunctionBody - Lazily parse the specified function body block.
  1912. error_code BitcodeReader::ParseFunctionBody(Function *F) {
  1913. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  1914. return Error(InvalidRecord);
  1915. InstructionList.clear();
  1916. unsigned ModuleValueListSize = ValueList.size();
  1917. unsigned ModuleMDValueListSize = MDValueList.size();
  1918. // Add all the function arguments to the value table.
  1919. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  1920. ValueList.push_back(I);
  1921. unsigned NextValueNo = ValueList.size();
  1922. BasicBlock *CurBB = 0;
  1923. unsigned CurBBNo = 0;
  1924. DebugLoc LastLoc;
  1925. // Read all the records.
  1926. SmallVector<uint64_t, 64> Record;
  1927. while (1) {
  1928. BitstreamEntry Entry = Stream.advance();
  1929. switch (Entry.Kind) {
  1930. case BitstreamEntry::Error:
  1931. return Error(MalformedBlock);
  1932. case BitstreamEntry::EndBlock:
  1933. goto OutOfRecordLoop;
  1934. case BitstreamEntry::SubBlock:
  1935. switch (Entry.ID) {
  1936. default: // Skip unknown content.
  1937. if (Stream.SkipBlock())
  1938. return Error(InvalidRecord);
  1939. break;
  1940. case bitc::CONSTANTS_BLOCK_ID:
  1941. if (error_code EC = ParseConstants())
  1942. return EC;
  1943. NextValueNo = ValueList.size();
  1944. break;
  1945. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1946. if (error_code EC = ParseValueSymbolTable())
  1947. return EC;
  1948. break;
  1949. case bitc::METADATA_ATTACHMENT_ID:
  1950. if (error_code EC = ParseMetadataAttachment())
  1951. return EC;
  1952. break;
  1953. case bitc::METADATA_BLOCK_ID:
  1954. if (error_code EC = ParseMetadata())
  1955. return EC;
  1956. break;
  1957. }
  1958. continue;
  1959. case BitstreamEntry::Record:
  1960. // The interesting case.
  1961. break;
  1962. }
  1963. // Read a record.
  1964. Record.clear();
  1965. Instruction *I = 0;
  1966. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  1967. switch (BitCode) {
  1968. default: // Default behavior: reject
  1969. return Error(InvalidValue);
  1970. case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
  1971. if (Record.size() < 1 || Record[0] == 0)
  1972. return Error(InvalidRecord);
  1973. // Create all the basic blocks for the function.
  1974. FunctionBBs.resize(Record[0]);
  1975. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  1976. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  1977. CurBB = FunctionBBs[0];
  1978. continue;
  1979. case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
  1980. // This record indicates that the last instruction is at the same
  1981. // location as the previous instruction with a location.
  1982. I = 0;
  1983. // Get the last instruction emitted.
  1984. if (CurBB && !CurBB->empty())
  1985. I = &CurBB->back();
  1986. else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
  1987. !FunctionBBs[CurBBNo-1]->empty())
  1988. I = &FunctionBBs[CurBBNo-1]->back();
  1989. if (I == 0)
  1990. return Error(InvalidRecord);
  1991. I->setDebugLoc(LastLoc);
  1992. I = 0;
  1993. continue;
  1994. case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
  1995. I = 0; // Get the last instruction emitted.
  1996. if (CurBB && !CurBB->empty())
  1997. I = &CurBB->back();
  1998. else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
  1999. !FunctionBBs[CurBBNo-1]->empty())
  2000. I = &FunctionBBs[CurBBNo-1]->back();
  2001. if (I == 0 || Record.size() < 4)
  2002. return Error(InvalidRecord);
  2003. unsigned Line = Record[0], Col = Record[1];
  2004. unsigned ScopeID = Record[2], IAID = Record[3];
  2005. MDNode *Scope = 0, *IA = 0;
  2006. if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
  2007. if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
  2008. LastLoc = DebugLoc::get(Line, Col, Scope, IA);
  2009. I->setDebugLoc(LastLoc);
  2010. I = 0;
  2011. continue;
  2012. }
  2013. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  2014. unsigned OpNum = 0;
  2015. Value *LHS, *RHS;
  2016. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  2017. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  2018. OpNum+1 > Record.size())
  2019. return Error(InvalidRecord);
  2020. int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  2021. if (Opc == -1)
  2022. return Error(InvalidRecord);
  2023. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  2024. InstructionList.push_back(I);
  2025. if (OpNum < Record.size()) {
  2026. if (Opc == Instruction::Add ||
  2027. Opc == Instruction::Sub ||
  2028. Opc == Instruction::Mul ||
  2029. Opc == Instruction::Shl) {
  2030. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  2031. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  2032. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  2033. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  2034. } else if (Opc == Instruction::SDiv ||
  2035. Opc == Instruction::UDiv ||
  2036. Opc == Instruction::LShr ||
  2037. Opc == Instruction::AShr) {
  2038. if (Record[OpNum] & (1 << bitc::PEO_EXACT))
  2039. cast<BinaryOperator>(I)->setIsExact(true);
  2040. } else if (isa<FPMathOperator>(I)) {
  2041. FastMathFlags FMF;
  2042. if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
  2043. FMF.setUnsafeAlgebra();
  2044. if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
  2045. FMF.setNoNaNs();
  2046. if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
  2047. FMF.setNoInfs();
  2048. if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
  2049. FMF.setNoSignedZeros();
  2050. if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
  2051. FMF.setAllowReciprocal();
  2052. if (FMF.any())
  2053. I->setFastMathFlags(FMF);
  2054. }
  2055. }
  2056. break;
  2057. }
  2058. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  2059. unsigned OpNum = 0;
  2060. Value *Op;
  2061. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  2062. OpNum+2 != Record.size())
  2063. return Error(InvalidRecord);
  2064. Type *ResTy = getTypeByID(Record[OpNum]);
  2065. int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
  2066. if (Opc == -1 || ResTy == 0)
  2067. return Error(InvalidRecord);
  2068. Instruction *Temp = 0;
  2069. if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
  2070. if (Temp) {
  2071. InstructionList.push_back(Temp);
  2072. CurBB->getInstList().push_back(Temp);
  2073. }
  2074. } else {
  2075. I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
  2076. }
  2077. InstructionList.push_back(I);
  2078. break;
  2079. }
  2080. case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
  2081. case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
  2082. unsigned OpNum = 0;
  2083. Value *BasePtr;
  2084. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  2085. return Error(InvalidRecord);
  2086. SmallVector<Value*, 16> GEPIdx;
  2087. while (OpNum != Record.size()) {
  2088. Value *Op;
  2089. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2090. return Error(InvalidRecord);
  2091. GEPIdx.push_back(Op);
  2092. }
  2093. I = GetElementPtrInst::Create(BasePtr, GEPIdx);
  2094. InstructionList.push_back(I);
  2095. if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
  2096. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  2097. break;
  2098. }
  2099. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  2100. // EXTRACTVAL: [opty, opval, n x indices]
  2101. unsigned OpNum = 0;
  2102. Value *Agg;
  2103. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  2104. return Error(InvalidRecord);
  2105. SmallVector<unsigned, 4> EXTRACTVALIdx;
  2106. for (unsigned RecSize = Record.size();
  2107. OpNum != RecSize; ++OpNum) {
  2108. uint64_t Index = Record[OpNum];
  2109. if ((unsigned)Index != Index)
  2110. return Error(InvalidValue);
  2111. EXTRACTVALIdx.push_back((unsigned)Index);
  2112. }
  2113. I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
  2114. InstructionList.push_back(I);
  2115. break;
  2116. }
  2117. case bitc::FUNC_CODE_INST_INSERTVAL: {
  2118. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  2119. unsigned OpNum = 0;
  2120. Value *Agg;
  2121. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  2122. return Error(InvalidRecord);
  2123. Value *Val;
  2124. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  2125. return Error(InvalidRecord);
  2126. SmallVector<unsigned, 4> INSERTVALIdx;
  2127. for (unsigned RecSize = Record.size();
  2128. OpNum != RecSize; ++OpNum) {
  2129. uint64_t Index = Record[OpNum];
  2130. if ((unsigned)Index != Index)
  2131. return Error(InvalidValue);
  2132. INSERTVALIdx.push_back((unsigned)Index);
  2133. }
  2134. I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
  2135. InstructionList.push_back(I);
  2136. break;
  2137. }
  2138. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  2139. // obsolete form of select
  2140. // handles select i1 ... in old bitcode
  2141. unsigned OpNum = 0;
  2142. Value *TrueVal, *FalseVal, *Cond;
  2143. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  2144. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  2145. popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
  2146. return Error(InvalidRecord);
  2147. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  2148. InstructionList.push_back(I);
  2149. break;
  2150. }
  2151. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  2152. // new form of select
  2153. // handles select i1 or select [N x i1]
  2154. unsigned OpNum = 0;
  2155. Value *TrueVal, *FalseVal, *Cond;
  2156. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  2157. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  2158. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  2159. return Error(InvalidRecord);
  2160. // select condition can be either i1 or [N x i1]
  2161. if (VectorType* vector_type =
  2162. dyn_cast<VectorType>(Cond->getType())) {
  2163. // expect <n x i1>
  2164. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  2165. return Error(InvalidTypeForValue);
  2166. } else {
  2167. // expect i1
  2168. if (Cond->getType() != Type::getInt1Ty(Context))
  2169. return Error(InvalidTypeForValue);
  2170. }
  2171. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  2172. InstructionList.push_back(I);
  2173. break;
  2174. }
  2175. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  2176. unsigned OpNum = 0;
  2177. Value *Vec, *Idx;
  2178. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  2179. popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
  2180. return Error(InvalidRecord);
  2181. I = ExtractElementInst::Create(Vec, Idx);
  2182. InstructionList.push_back(I);
  2183. break;
  2184. }
  2185. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  2186. unsigned OpNum = 0;
  2187. Value *Vec, *Elt, *Idx;
  2188. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  2189. popValue(Record, OpNum, NextValueNo,
  2190. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  2191. popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
  2192. return Error(InvalidRecord);
  2193. I = InsertElementInst::Create(Vec, Elt, Idx);
  2194. InstructionList.push_back(I);
  2195. break;
  2196. }
  2197. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  2198. unsigned OpNum = 0;
  2199. Value *Vec1, *Vec2, *Mask;
  2200. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  2201. popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
  2202. return Error(InvalidRecord);
  2203. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  2204. return Error(InvalidRecord);
  2205. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  2206. InstructionList.push_back(I);
  2207. break;
  2208. }
  2209. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  2210. // Old form of ICmp/FCmp returning bool
  2211. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  2212. // both legal on vectors but had different behaviour.
  2213. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  2214. // FCmp/ICmp returning bool or vector of bool
  2215. unsigned OpNum = 0;
  2216. Value *LHS, *RHS;
  2217. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  2218. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  2219. OpNum+1 != Record.size())
  2220. return Error(InvalidRecord);
  2221. if (LHS->getType()->isFPOrFPVectorTy())
  2222. I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
  2223. else
  2224. I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
  2225. InstructionList.push_back(I);
  2226. break;
  2227. }
  2228. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  2229. {
  2230. unsigned Size = Record.size();
  2231. if (Size == 0) {
  2232. I = ReturnInst::Create(Context);
  2233. InstructionList.push_back(I);
  2234. break;
  2235. }
  2236. unsigned OpNum = 0;
  2237. Value *Op = NULL;
  2238. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2239. return Error(InvalidRecord);
  2240. if (OpNum != Record.size())
  2241. return Error(InvalidRecord);
  2242. I = ReturnInst::Create(Context, Op);
  2243. InstructionList.push_back(I);
  2244. break;
  2245. }
  2246. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  2247. if (Record.size() != 1 && Record.size() != 3)
  2248. return Error(InvalidRecord);
  2249. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  2250. if (TrueDest == 0)
  2251. return Error(InvalidRecord);
  2252. if (Record.size() == 1) {
  2253. I = BranchInst::Create(TrueDest);
  2254. InstructionList.push_back(I);
  2255. }
  2256. else {
  2257. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  2258. Value *Cond = getValue(Record, 2, NextValueNo,
  2259. Type::getInt1Ty(Context));
  2260. if (FalseDest == 0 || Cond == 0)
  2261. return Error(InvalidRecord);
  2262. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  2263. InstructionList.push_back(I);
  2264. }
  2265. break;
  2266. }
  2267. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  2268. // Check magic
  2269. if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
  2270. // "New" SwitchInst format with case ranges. The changes to write this
  2271. // format were reverted but we still recognize bitcode that uses it.
  2272. // Hopefully someday we will have support for case ranges and can use
  2273. // this format again.
  2274. Type *OpTy = getTypeByID(Record[1]);
  2275. unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
  2276. Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
  2277. BasicBlock *Default = getBasicBlock(Record[3]);
  2278. if (OpTy == 0 || Cond == 0 || Default == 0)
  2279. return Error(InvalidRecord);
  2280. unsigned NumCases = Record[4];
  2281. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  2282. InstructionList.push_back(SI);
  2283. unsigned CurIdx = 5;
  2284. for (unsigned i = 0; i != NumCases; ++i) {
  2285. SmallVector<ConstantInt*, 1> CaseVals;
  2286. unsigned NumItems = Record[CurIdx++];
  2287. for (unsigned ci = 0; ci != NumItems; ++ci) {
  2288. bool isSingleNumber = Record[CurIdx++];
  2289. APInt Low;
  2290. unsigned ActiveWords = 1;
  2291. if (ValueBitWidth > 64)
  2292. ActiveWords = Record[CurIdx++];
  2293. Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  2294. ValueBitWidth);
  2295. CurIdx += ActiveWords;
  2296. if (!isSingleNumber) {
  2297. ActiveWords = 1;
  2298. if (ValueBitWidth > 64)
  2299. ActiveWords = Record[CurIdx++];
  2300. APInt High =
  2301. ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  2302. ValueBitWidth);
  2303. CurIdx += ActiveWords;
  2304. // FIXME: It is not clear whether values in the range should be
  2305. // compared as signed or unsigned values. The partially
  2306. // implemented changes that used this format in the past used
  2307. // unsigned comparisons.
  2308. for ( ; Low.ule(High); ++Low)
  2309. CaseVals.push_back(ConstantInt::get(Context, Low));
  2310. } else
  2311. CaseVals.push_back(ConstantInt::get(Context, Low));
  2312. }
  2313. BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
  2314. for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
  2315. cve = CaseVals.end(); cvi != cve; ++cvi)
  2316. SI->addCase(*cvi, DestBB);
  2317. }
  2318. I = SI;
  2319. break;
  2320. }
  2321. // Old SwitchInst format without case ranges.
  2322. if (Record.size() < 3 || (Record.size() & 1) == 0)
  2323. return Error(InvalidRecord);
  2324. Type *OpTy = getTypeByID(Record[0]);
  2325. Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
  2326. BasicBlock *Default = getBasicBlock(Record[2]);
  2327. if (OpTy == 0 || Cond == 0 || Default == 0)
  2328. return Error(InvalidRecord);
  2329. unsigned NumCases = (Record.size()-3)/2;
  2330. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  2331. InstructionList.push_back(SI);
  2332. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  2333. ConstantInt *CaseVal =
  2334. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  2335. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  2336. if (CaseVal == 0 || DestBB == 0) {
  2337. delete SI;
  2338. return Error(InvalidRecord);
  2339. }
  2340. SI->addCase(CaseVal, DestBB);
  2341. }
  2342. I = SI;
  2343. break;
  2344. }
  2345. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  2346. if (Record.size() < 2)
  2347. return Error(InvalidRecord);
  2348. Type *OpTy = getTypeByID(Record[0]);
  2349. Value *Address = getValue(Record, 1, NextValueNo, OpTy);
  2350. if (OpTy == 0 || Address == 0)
  2351. return Error(InvalidRecord);
  2352. unsigned NumDests = Record.size()-2;
  2353. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  2354. InstructionList.push_back(IBI);
  2355. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  2356. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  2357. IBI->addDestination(DestBB);
  2358. } else {
  2359. delete IBI;
  2360. return Error(InvalidRecord);
  2361. }
  2362. }
  2363. I = IBI;
  2364. break;
  2365. }
  2366. case bitc::FUNC_CODE_INST_INVOKE: {
  2367. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  2368. if (Record.size() < 4)
  2369. return Error(InvalidRecord);
  2370. AttributeSet PAL = getAttributes(Record[0]);
  2371. unsigned CCInfo = Record[1];
  2372. BasicBlock *NormalBB = getBasicBlock(Record[2]);
  2373. BasicBlock *UnwindBB = getBasicBlock(Record[3]);
  2374. unsigned OpNum = 4;
  2375. Value *Callee;
  2376. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  2377. return Error(InvalidRecord);
  2378. PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  2379. FunctionType *FTy = !CalleeTy ? 0 :
  2380. dyn_cast<FunctionType>(CalleeTy->getElementType());
  2381. // Check that the right number of fixed parameters are here.
  2382. if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
  2383. Record.size() < OpNum+FTy->getNumParams())
  2384. return Error(InvalidRecord);
  2385. SmallVector<Value*, 16> Ops;
  2386. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  2387. Ops.push_back(getValue(Record, OpNum, NextValueNo,
  2388. FTy->getParamType(i)));
  2389. if (Ops.back() == 0)
  2390. return Error(InvalidRecord);
  2391. }
  2392. if (!FTy->isVarArg()) {
  2393. if (Record.size() != OpNum)
  2394. return Error(InvalidRecord);
  2395. } else {
  2396. // Read type/value pairs for varargs params.
  2397. while (OpNum != Record.size()) {
  2398. Value *Op;
  2399. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2400. return Error(InvalidRecord);
  2401. Ops.push_back(Op);
  2402. }
  2403. }
  2404. I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
  2405. InstructionList.push_back(I);
  2406. cast<InvokeInst>(I)->setCallingConv(
  2407. static_cast<CallingConv::ID>(CCInfo));
  2408. cast<InvokeInst>(I)->setAttributes(PAL);
  2409. break;
  2410. }
  2411. case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
  2412. unsigned Idx = 0;
  2413. Value *Val = 0;
  2414. if (getValueTypePair(Record, Idx, NextValueNo, Val))
  2415. return Error(InvalidRecord);
  2416. I = ResumeInst::Create(Val);
  2417. InstructionList.push_back(I);
  2418. break;
  2419. }
  2420. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  2421. I = new UnreachableInst(Context);
  2422. InstructionList.push_back(I);
  2423. break;
  2424. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  2425. if (Record.size() < 1 || ((Record.size()-1)&1))
  2426. return Error(InvalidRecord);
  2427. Type *Ty = getTypeByID(Record[0]);
  2428. if (!Ty)
  2429. return Error(InvalidRecord);
  2430. PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
  2431. InstructionList.push_back(PN);
  2432. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  2433. Value *V;
  2434. // With the new function encoding, it is possible that operands have
  2435. // negative IDs (for forward references). Use a signed VBR
  2436. // representation to keep the encoding small.
  2437. if (UseRelativeIDs)
  2438. V = getValueSigned(Record, 1+i, NextValueNo, Ty);
  2439. else
  2440. V = getValue(Record, 1+i, NextValueNo, Ty);
  2441. BasicBlock *BB = getBasicBlock(Record[2+i]);
  2442. if (!V || !BB)
  2443. return Error(InvalidRecord);
  2444. PN->addIncoming(V, BB);
  2445. }
  2446. I = PN;
  2447. break;
  2448. }
  2449. case bitc::FUNC_CODE_INST_LANDINGPAD: {
  2450. // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
  2451. unsigned Idx = 0;
  2452. if (Record.size() < 4)
  2453. return Error(InvalidRecord);
  2454. Type *Ty = getTypeByID(Record[Idx++]);
  2455. if (!Ty)
  2456. return Error(InvalidRecord);
  2457. Value *PersFn = 0;
  2458. if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
  2459. return Error(InvalidRecord);
  2460. bool IsCleanup = !!Record[Idx++];
  2461. unsigned NumClauses = Record[Idx++];
  2462. LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
  2463. LP->setCleanup(IsCleanup);
  2464. for (unsigned J = 0; J != NumClauses; ++J) {
  2465. LandingPadInst::ClauseType CT =
  2466. LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
  2467. Value *Val;
  2468. if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
  2469. delete LP;
  2470. return Error(InvalidRecord);
  2471. }
  2472. assert((CT != LandingPadInst::Catch ||
  2473. !isa<ArrayType>(Val->getType())) &&
  2474. "Catch clause has a invalid type!");
  2475. assert((CT != LandingPadInst::Filter ||
  2476. isa<ArrayType>(Val->getType())) &&
  2477. "Filter clause has invalid type!");
  2478. LP->addClause(Val);
  2479. }
  2480. I = LP;
  2481. InstructionList.push_back(I);
  2482. break;
  2483. }
  2484. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
  2485. if (Record.size() != 4)
  2486. return Error(InvalidRecord);
  2487. PointerType *Ty =
  2488. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  2489. Type *OpTy = getTypeByID(Record[1]);
  2490. Value *Size = getFnValueByID(Record[2], OpTy);
  2491. unsigned Align = Record[3];
  2492. if (!Ty || !Size)
  2493. return Error(InvalidRecord);
  2494. I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  2495. InstructionList.push_back(I);
  2496. break;
  2497. }
  2498. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  2499. unsigned OpNum = 0;
  2500. Value *Op;
  2501. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  2502. OpNum+2 != Record.size())
  2503. return Error(InvalidRecord);
  2504. I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  2505. InstructionList.push_back(I);
  2506. break;
  2507. }
  2508. case bitc::FUNC_CODE_INST_LOADATOMIC: {
  2509. // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
  2510. unsigned OpNum = 0;
  2511. Value *Op;
  2512. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  2513. OpNum+4 != Record.size())
  2514. return Error(InvalidRecord);
  2515. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
  2516. if (Ordering == NotAtomic || Ordering == Release ||
  2517. Ordering == AcquireRelease)
  2518. return Error(InvalidRecord);
  2519. if (Ordering != NotAtomic && Record[OpNum] == 0)
  2520. return Error(InvalidRecord);
  2521. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
  2522. I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
  2523. Ordering, SynchScope);
  2524. InstructionList.push_back(I);
  2525. break;
  2526. }
  2527. case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
  2528. unsigned OpNum = 0;
  2529. Value *Val, *Ptr;
  2530. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  2531. popValue(Record, OpNum, NextValueNo,
  2532. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  2533. OpNum+2 != Record.size())
  2534. return Error(InvalidRecord);
  2535. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  2536. InstructionList.push_back(I);
  2537. break;
  2538. }
  2539. case bitc::FUNC_CODE_INST_STOREATOMIC: {
  2540. // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
  2541. unsigned OpNum = 0;
  2542. Value *Val, *Ptr;
  2543. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  2544. popValue(Record, OpNum, NextValueNo,
  2545. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  2546. OpNum+4 != Record.size())
  2547. return Error(InvalidRecord);
  2548. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
  2549. if (Ordering == NotAtomic || Ordering == Acquire ||
  2550. Ordering == AcquireRelease)
  2551. return Error(InvalidRecord);
  2552. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
  2553. if (Ordering != NotAtomic && Record[OpNum] == 0)
  2554. return Error(InvalidRecord);
  2555. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
  2556. Ordering, SynchScope);
  2557. InstructionList.push_back(I);
  2558. break;
  2559. }
  2560. case bitc::FUNC_CODE_INST_CMPXCHG: {
  2561. // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
  2562. unsigned OpNum = 0;
  2563. Value *Ptr, *Cmp, *New;
  2564. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  2565. popValue(Record, OpNum, NextValueNo,
  2566. cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
  2567. popValue(Record, OpNum, NextValueNo,
  2568. cast<PointerType>(Ptr->getType())->getElementType(), New) ||
  2569. OpNum+3 != Record.size())
  2570. return Error(InvalidRecord);
  2571. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
  2572. if (Ordering == NotAtomic || Ordering == Unordered)
  2573. return Error(InvalidRecord);
  2574. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
  2575. I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
  2576. cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
  2577. InstructionList.push_back(I);
  2578. break;
  2579. }
  2580. case bitc::FUNC_CODE_INST_ATOMICRMW: {
  2581. // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
  2582. unsigned OpNum = 0;
  2583. Value *Ptr, *Val;
  2584. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  2585. popValue(Record, OpNum, NextValueNo,
  2586. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  2587. OpNum+4 != Record.size())
  2588. return Error(InvalidRecord);
  2589. AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
  2590. if (Operation < AtomicRMWInst::FIRST_BINOP ||
  2591. Operation > AtomicRMWInst::LAST_BINOP)
  2592. return Error(InvalidRecord);
  2593. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
  2594. if (Ordering == NotAtomic || Ordering == Unordered)
  2595. return Error(InvalidRecord);
  2596. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
  2597. I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
  2598. cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
  2599. InstructionList.push_back(I);
  2600. break;
  2601. }
  2602. case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
  2603. if (2 != Record.size())
  2604. return Error(InvalidRecord);
  2605. AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
  2606. if (Ordering == NotAtomic || Ordering == Unordered ||
  2607. Ordering == Monotonic)
  2608. return Error(InvalidRecord);
  2609. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
  2610. I = new FenceInst(Context, Ordering, SynchScope);
  2611. InstructionList.push_back(I);
  2612. break;
  2613. }
  2614. case bitc::FUNC_CODE_INST_CALL: {
  2615. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  2616. if (Record.size() < 3)
  2617. return Error(InvalidRecord);
  2618. AttributeSet PAL = getAttributes(Record[0]);
  2619. unsigned CCInfo = Record[1];
  2620. unsigned OpNum = 2;
  2621. Value *Callee;
  2622. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  2623. return Error(InvalidRecord);
  2624. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  2625. FunctionType *FTy = 0;
  2626. if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  2627. if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
  2628. return Error(InvalidRecord);
  2629. SmallVector<Value*, 16> Args;
  2630. // Read the fixed params.
  2631. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  2632. if (FTy->getParamType(i)->isLabelTy())
  2633. Args.push_back(getBasicBlock(Record[OpNum]));
  2634. else
  2635. Args.push_back(getValue(Record, OpNum, NextValueNo,
  2636. FTy->getParamType(i)));
  2637. if (Args.back() == 0)
  2638. return Error(InvalidRecord);
  2639. }
  2640. // Read type/value pairs for varargs params.
  2641. if (!FTy->isVarArg()) {
  2642. if (OpNum != Record.size())
  2643. return Error(InvalidRecord);
  2644. } else {
  2645. while (OpNum != Record.size()) {
  2646. Value *Op;
  2647. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2648. return Error(InvalidRecord);
  2649. Args.push_back(Op);
  2650. }
  2651. }
  2652. I = CallInst::Create(Callee, Args);
  2653. InstructionList.push_back(I);
  2654. cast<CallInst>(I)->setCallingConv(
  2655. static_cast<CallingConv::ID>(CCInfo>>1));
  2656. cast<CallInst>(I)->setTailCall(CCInfo & 1);
  2657. cast<CallInst>(I)->setAttributes(PAL);
  2658. break;
  2659. }
  2660. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  2661. if (Record.size() < 3)
  2662. return Error(InvalidRecord);
  2663. Type *OpTy = getTypeByID(Record[0]);
  2664. Value *Op = getValue(Record, 1, NextValueNo, OpTy);
  2665. Type *ResTy = getTypeByID(Record[2]);
  2666. if (!OpTy || !Op || !ResTy)
  2667. return Error(InvalidRecord);
  2668. I = new VAArgInst(Op, ResTy);
  2669. InstructionList.push_back(I);
  2670. break;
  2671. }
  2672. }
  2673. // Add instruction to end of current BB. If there is no current BB, reject
  2674. // this file.
  2675. if (CurBB == 0) {
  2676. delete I;
  2677. return Error(InvalidInstructionWithNoBB);
  2678. }
  2679. CurBB->getInstList().push_back(I);
  2680. // If this was a terminator instruction, move to the next block.
  2681. if (isa<TerminatorInst>(I)) {
  2682. ++CurBBNo;
  2683. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
  2684. }
  2685. // Non-void values get registered in the value table for future use.
  2686. if (I && !I->getType()->isVoidTy())
  2687. ValueList.AssignValue(I, NextValueNo++);
  2688. }
  2689. OutOfRecordLoop:
  2690. // Check the function list for unresolved values.
  2691. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  2692. if (A->getParent() == 0) {
  2693. // We found at least one unresolved value. Nuke them all to avoid leaks.
  2694. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  2695. if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
  2696. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  2697. delete A;
  2698. }
  2699. }
  2700. return Error(NeverResolvedValueFoundInFunction);
  2701. }
  2702. }
  2703. // FIXME: Check for unresolved forward-declared metadata references
  2704. // and clean up leaks.
  2705. // See if anything took the address of blocks in this function. If so,
  2706. // resolve them now.
  2707. DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
  2708. BlockAddrFwdRefs.find(F);
  2709. if (BAFRI != BlockAddrFwdRefs.end()) {
  2710. std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
  2711. for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
  2712. unsigned BlockIdx = RefList[i].first;
  2713. if (BlockIdx >= FunctionBBs.size())
  2714. return Error(InvalidID);
  2715. GlobalVariable *FwdRef = RefList[i].second;
  2716. FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
  2717. FwdRef->eraseFromParent();
  2718. }
  2719. BlockAddrFwdRefs.erase(BAFRI);
  2720. }
  2721. // Trim the value list down to the size it was before we parsed this function.
  2722. ValueList.shrinkTo(ModuleValueListSize);
  2723. MDValueList.shrinkTo(ModuleMDValueListSize);
  2724. std::vector<BasicBlock*>().swap(FunctionBBs);
  2725. return error_code::success();
  2726. }
  2727. /// Find the function body in the bitcode stream
  2728. error_code BitcodeReader::FindFunctionInStream(Function *F,
  2729. DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
  2730. while (DeferredFunctionInfoIterator->second == 0) {
  2731. if (Stream.AtEndOfStream())
  2732. return Error(CouldNotFindFunctionInStream);
  2733. // ParseModule will parse the next body in the stream and set its
  2734. // position in the DeferredFunctionInfo map.
  2735. if (error_code EC = ParseModule(true))
  2736. return EC;
  2737. }
  2738. return error_code::success();
  2739. }
  2740. //===----------------------------------------------------------------------===//
  2741. // GVMaterializer implementation
  2742. //===----------------------------------------------------------------------===//
  2743. bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
  2744. if (const Function *F = dyn_cast<Function>(GV)) {
  2745. return F->isDeclaration() &&
  2746. DeferredFunctionInfo.count(const_cast<Function*>(F));
  2747. }
  2748. return false;
  2749. }
  2750. error_code BitcodeReader::Materialize(GlobalValue *GV) {
  2751. Function *F = dyn_cast<Function>(GV);
  2752. // If it's not a function or is already material, ignore the request.
  2753. if (!F || !F->isMaterializable())
  2754. return error_code::success();
  2755. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  2756. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  2757. // If its position is recorded as 0, its body is somewhere in the stream
  2758. // but we haven't seen it yet.
  2759. if (DFII->second == 0 && LazyStreamer)
  2760. if (error_code EC = FindFunctionInStream(F, DFII))
  2761. return EC;
  2762. // Move the bit stream to the saved position of the deferred function body.
  2763. Stream.JumpToBit(DFII->second);
  2764. if (error_code EC = ParseFunctionBody(F))
  2765. return EC;
  2766. // Upgrade any old intrinsic calls in the function.
  2767. for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
  2768. E = UpgradedIntrinsics.end(); I != E; ++I) {
  2769. if (I->first != I->second) {
  2770. for (Value::use_iterator UI = I->first->use_begin(),
  2771. UE = I->first->use_end(); UI != UE; ) {
  2772. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2773. UpgradeIntrinsicCall(CI, I->second);
  2774. }
  2775. }
  2776. }
  2777. return error_code::success();
  2778. }
  2779. bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
  2780. const Function *F = dyn_cast<Function>(GV);
  2781. if (!F || F->isDeclaration())
  2782. return false;
  2783. return DeferredFunctionInfo.count(const_cast<Function*>(F));
  2784. }
  2785. void BitcodeReader::Dematerialize(GlobalValue *GV) {
  2786. Function *F = dyn_cast<Function>(GV);
  2787. // If this function isn't dematerializable, this is a noop.
  2788. if (!F || !isDematerializable(F))
  2789. return;
  2790. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  2791. // Just forget the function body, we can remat it later.
  2792. F->deleteBody();
  2793. }
  2794. error_code BitcodeReader::MaterializeModule(Module *M) {
  2795. assert(M == TheModule &&
  2796. "Can only Materialize the Module this BitcodeReader is attached to.");
  2797. // Iterate over the module, deserializing any functions that are still on
  2798. // disk.
  2799. for (Module::iterator F = TheModule->begin(), E = TheModule->end();
  2800. F != E; ++F) {
  2801. if (F->isMaterializable()) {
  2802. if (error_code EC = Materialize(F))
  2803. return EC;
  2804. }
  2805. }
  2806. // At this point, if there are any function bodies, the current bit is
  2807. // pointing to the END_BLOCK record after them. Now make sure the rest
  2808. // of the bits in the module have been read.
  2809. if (NextUnreadBit)
  2810. ParseModule(true);
  2811. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  2812. // delete the old functions to clean up. We can't do this unless the entire
  2813. // module is materialized because there could always be another function body
  2814. // with calls to the old function.
  2815. for (std::vector<std::pair<Function*, Function*> >::iterator I =
  2816. UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
  2817. if (I->first != I->second) {
  2818. for (Value::use_iterator UI = I->first->use_begin(),
  2819. UE = I->first->use_end(); UI != UE; ) {
  2820. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2821. UpgradeIntrinsicCall(CI, I->second);
  2822. }
  2823. if (!I->first->use_empty())
  2824. I->first->replaceAllUsesWith(I->second);
  2825. I->first->eraseFromParent();
  2826. }
  2827. }
  2828. std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
  2829. for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
  2830. UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
  2831. UpgradeDebugInfo(*M);
  2832. return error_code::success();
  2833. }
  2834. error_code BitcodeReader::InitStream() {
  2835. if (LazyStreamer)
  2836. return InitLazyStream();
  2837. return InitStreamFromBuffer();
  2838. }
  2839. error_code BitcodeReader::InitStreamFromBuffer() {
  2840. const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
  2841. const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  2842. if (Buffer->getBufferSize() & 3) {
  2843. if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
  2844. return Error(InvalidBitcodeSignature);
  2845. else
  2846. return Error(BitcodeStreamInvalidSize);
  2847. }
  2848. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  2849. // The magic number is 0x0B17C0DE stored in little endian.
  2850. if (isBitcodeWrapper(BufPtr, BufEnd))
  2851. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
  2852. return Error(InvalidBitcodeWrapperHeader);
  2853. StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
  2854. Stream.init(*StreamFile);
  2855. return error_code::success();
  2856. }
  2857. error_code BitcodeReader::InitLazyStream() {
  2858. // Check and strip off the bitcode wrapper; BitstreamReader expects never to
  2859. // see it.
  2860. StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
  2861. StreamFile.reset(new BitstreamReader(Bytes));
  2862. Stream.init(*StreamFile);
  2863. unsigned char buf[16];
  2864. if (Bytes->readBytes(0, 16, buf) == -1)
  2865. return Error(BitcodeStreamInvalidSize);
  2866. if (!isBitcode(buf, buf + 16))
  2867. return Error(InvalidBitcodeSignature);
  2868. if (isBitcodeWrapper(buf, buf + 4)) {
  2869. const unsigned char *bitcodeStart = buf;
  2870. const unsigned char *bitcodeEnd = buf + 16;
  2871. SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
  2872. Bytes->dropLeadingBytes(bitcodeStart - buf);
  2873. Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
  2874. }
  2875. return error_code::success();
  2876. }
  2877. namespace {
  2878. class BitcodeErrorCategoryType : public _do_message {
  2879. const char *name() const LLVM_OVERRIDE {
  2880. return "llvm.bitcode";
  2881. }
  2882. std::string message(int IE) const LLVM_OVERRIDE {
  2883. BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
  2884. switch (E) {
  2885. case BitcodeReader::BitcodeStreamInvalidSize:
  2886. return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
  2887. case BitcodeReader::ConflictingMETADATA_KINDRecords:
  2888. return "Conflicting METADATA_KIND records";
  2889. case BitcodeReader::CouldNotFindFunctionInStream:
  2890. return "Could not find function in stream";
  2891. case BitcodeReader::ExpectedConstant:
  2892. return "Expected a constant";
  2893. case BitcodeReader::InsufficientFunctionProtos:
  2894. return "Insufficient function protos";
  2895. case BitcodeReader::InvalidBitcodeSignature:
  2896. return "Invalid bitcode signature";
  2897. case BitcodeReader::InvalidBitcodeWrapperHeader:
  2898. return "Invalid bitcode wrapper header";
  2899. case BitcodeReader::InvalidConstantReference:
  2900. return "Invalid ronstant reference";
  2901. case BitcodeReader::InvalidID:
  2902. return "Invalid ID";
  2903. case BitcodeReader::InvalidInstructionWithNoBB:
  2904. return "Invalid instruction with no BB";
  2905. case BitcodeReader::InvalidRecord:
  2906. return "Invalid record";
  2907. case BitcodeReader::InvalidTypeForValue:
  2908. return "Invalid type for value";
  2909. case BitcodeReader::InvalidTYPETable:
  2910. return "Invalid TYPE table";
  2911. case BitcodeReader::InvalidType:
  2912. return "Invalid type";
  2913. case BitcodeReader::MalformedBlock:
  2914. return "Malformed block";
  2915. case BitcodeReader::MalformedGlobalInitializerSet:
  2916. return "Malformed global initializer set";
  2917. case BitcodeReader::InvalidMultipleBlocks:
  2918. return "Invalid multiple blocks";
  2919. case BitcodeReader::NeverResolvedValueFoundInFunction:
  2920. return "Never resolved value found in function";
  2921. case BitcodeReader::InvalidValue:
  2922. return "Invalid value";
  2923. }
  2924. llvm_unreachable("Unknown error type!");
  2925. }
  2926. };
  2927. }
  2928. const error_category &BitcodeReader::BitcodeErrorCategory() {
  2929. static BitcodeErrorCategoryType O;
  2930. return O;
  2931. }
  2932. //===----------------------------------------------------------------------===//
  2933. // External interface
  2934. //===----------------------------------------------------------------------===//
  2935. /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
  2936. ///
  2937. Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
  2938. LLVMContext& Context,
  2939. std::string *ErrMsg) {
  2940. Module *M = new Module(Buffer->getBufferIdentifier(), Context);
  2941. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  2942. M->setMaterializer(R);
  2943. if (error_code EC = R->ParseBitcodeInto(M)) {
  2944. if (ErrMsg)
  2945. *ErrMsg = EC.message();
  2946. delete M; // Also deletes R.
  2947. return 0;
  2948. }
  2949. // Have the BitcodeReader dtor delete 'Buffer'.
  2950. R->setBufferOwned(true);
  2951. R->materializeForwardReferencedFunctions();
  2952. return M;
  2953. }
  2954. Module *llvm::getStreamedBitcodeModule(const std::string &name,
  2955. DataStreamer *streamer,
  2956. LLVMContext &Context,
  2957. std::string *ErrMsg) {
  2958. Module *M = new Module(name, Context);
  2959. BitcodeReader *R = new BitcodeReader(streamer, Context);
  2960. M->setMaterializer(R);
  2961. if (error_code EC = R->ParseBitcodeInto(M)) {
  2962. if (ErrMsg)
  2963. *ErrMsg = EC.message();
  2964. delete M; // Also deletes R.
  2965. return 0;
  2966. }
  2967. R->setBufferOwned(false); // no buffer to delete
  2968. return M;
  2969. }
  2970. /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
  2971. /// If an error occurs, return null and fill in *ErrMsg if non-null.
  2972. Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
  2973. std::string *ErrMsg){
  2974. Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
  2975. if (!M) return 0;
  2976. // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
  2977. // there was an error.
  2978. static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
  2979. // Read in the entire module, and destroy the BitcodeReader.
  2980. if (M->MaterializeAllPermanently(ErrMsg)) {
  2981. delete M;
  2982. return 0;
  2983. }
  2984. // TODO: Restore the use-lists to the in-memory state when the bitcode was
  2985. // written. We must defer until the Module has been fully materialized.
  2986. return M;
  2987. }
  2988. std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
  2989. LLVMContext& Context,
  2990. std::string *ErrMsg) {
  2991. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  2992. // Don't let the BitcodeReader dtor delete 'Buffer'.
  2993. R->setBufferOwned(false);
  2994. std::string Triple("");
  2995. if (error_code EC = R->ParseTriple(Triple))
  2996. if (ErrMsg)
  2997. *ErrMsg = EC.message();
  2998. delete R;
  2999. return Triple;
  3000. }