1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/Bitcode/LLVMBitCodes.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 void BitcodeReader::materializeForwardReferencedFunctions() {
35 while (!BlockAddrFwdRefs.empty()) {
36 Function *F = BlockAddrFwdRefs.begin()->first;
41 void BitcodeReader::FreeState() {
45 std::vector<Type*>().swap(TypeList);
49 std::vector<AttributeSet>().swap(MAttributes);
50 std::vector<BasicBlock*>().swap(FunctionBBs);
51 std::vector<Function*>().swap(FunctionsWithBodies);
52 DeferredFunctionInfo.clear();
55 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
58 //===----------------------------------------------------------------------===//
59 // Helper functions to implement forward reference resolution, etc.
60 //===----------------------------------------------------------------------===//
62 /// ConvertToString - Convert a string from a record into an std::string, return
64 template<typename StrTy>
65 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
67 if (Idx > Record.size())
70 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
71 Result += (char)Record[i];
75 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
77 default: // Map unknown/new linkages to external
78 case 0: return GlobalValue::ExternalLinkage;
79 case 1: return GlobalValue::WeakAnyLinkage;
80 case 2: return GlobalValue::AppendingLinkage;
81 case 3: return GlobalValue::InternalLinkage;
82 case 4: return GlobalValue::LinkOnceAnyLinkage;
83 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
84 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
85 case 7: return GlobalValue::ExternalWeakLinkage;
86 case 8: return GlobalValue::CommonLinkage;
87 case 9: return GlobalValue::PrivateLinkage;
88 case 10: return GlobalValue::WeakODRLinkage;
89 case 11: return GlobalValue::LinkOnceODRLinkage;
90 case 12: return GlobalValue::AvailableExternallyLinkage;
92 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
94 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
98 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
100 default: // Map unknown visibilities to default.
101 case 0: return GlobalValue::DefaultVisibility;
102 case 1: return GlobalValue::HiddenVisibility;
103 case 2: return GlobalValue::ProtectedVisibility;
107 static GlobalValue::DLLStorageClassTypes
108 GetDecodedDLLStorageClass(unsigned Val) {
110 default: // Map unknown values to default.
111 case 0: return GlobalValue::DefaultStorageClass;
112 case 1: return GlobalValue::DLLImportStorageClass;
113 case 2: return GlobalValue::DLLExportStorageClass;
117 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
119 case 0: return GlobalVariable::NotThreadLocal;
120 default: // Map unknown non-zero value to general dynamic.
121 case 1: return GlobalVariable::GeneralDynamicTLSModel;
122 case 2: return GlobalVariable::LocalDynamicTLSModel;
123 case 3: return GlobalVariable::InitialExecTLSModel;
124 case 4: return GlobalVariable::LocalExecTLSModel;
128 static int GetDecodedCastOpcode(unsigned Val) {
131 case bitc::CAST_TRUNC : return Instruction::Trunc;
132 case bitc::CAST_ZEXT : return Instruction::ZExt;
133 case bitc::CAST_SEXT : return Instruction::SExt;
134 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
135 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
136 case bitc::CAST_UITOFP : return Instruction::UIToFP;
137 case bitc::CAST_SITOFP : return Instruction::SIToFP;
138 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
139 case bitc::CAST_FPEXT : return Instruction::FPExt;
140 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
141 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
142 case bitc::CAST_BITCAST : return Instruction::BitCast;
143 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
146 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
149 case bitc::BINOP_ADD:
150 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
151 case bitc::BINOP_SUB:
152 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
153 case bitc::BINOP_MUL:
154 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
155 case bitc::BINOP_UDIV: return Instruction::UDiv;
156 case bitc::BINOP_SDIV:
157 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
158 case bitc::BINOP_UREM: return Instruction::URem;
159 case bitc::BINOP_SREM:
160 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
161 case bitc::BINOP_SHL: return Instruction::Shl;
162 case bitc::BINOP_LSHR: return Instruction::LShr;
163 case bitc::BINOP_ASHR: return Instruction::AShr;
164 case bitc::BINOP_AND: return Instruction::And;
165 case bitc::BINOP_OR: return Instruction::Or;
166 case bitc::BINOP_XOR: return Instruction::Xor;
170 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
172 default: return AtomicRMWInst::BAD_BINOP;
173 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
174 case bitc::RMW_ADD: return AtomicRMWInst::Add;
175 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
176 case bitc::RMW_AND: return AtomicRMWInst::And;
177 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
178 case bitc::RMW_OR: return AtomicRMWInst::Or;
179 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
180 case bitc::RMW_MAX: return AtomicRMWInst::Max;
181 case bitc::RMW_MIN: return AtomicRMWInst::Min;
182 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
183 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
187 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
189 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
190 case bitc::ORDERING_UNORDERED: return Unordered;
191 case bitc::ORDERING_MONOTONIC: return Monotonic;
192 case bitc::ORDERING_ACQUIRE: return Acquire;
193 case bitc::ORDERING_RELEASE: return Release;
194 case bitc::ORDERING_ACQREL: return AcquireRelease;
195 default: // Map unknown orderings to sequentially-consistent.
196 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
200 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
202 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
203 default: // Map unknown scopes to cross-thread.
204 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
208 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
210 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
211 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
217 /// @brief A class for maintaining the slot number definition
218 /// as a placeholder for the actual definition for forward constants defs.
219 class ConstantPlaceHolder : public ConstantExpr {
220 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
222 // allocate space for exactly one operand
223 void *operator new(size_t s) {
224 return User::operator new(s, 1);
226 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
227 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
228 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
231 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
232 static bool classof(const Value *V) {
233 return isa<ConstantExpr>(V) &&
234 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
238 /// Provide fast operand accessors
239 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
243 // FIXME: can we inherit this from ConstantExpr?
245 struct OperandTraits<ConstantPlaceHolder> :
246 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
251 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
260 WeakVH &OldV = ValuePtrs[Idx];
266 // Handle constants and non-constants (e.g. instrs) differently for
268 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
269 ResolveConstants.push_back(std::make_pair(PHC, Idx));
272 // If there was a forward reference to this value, replace it.
273 Value *PrevVal = OldV;
274 OldV->replaceAllUsesWith(V);
280 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
285 if (Value *V = ValuePtrs[Idx]) {
286 assert(Ty == V->getType() && "Type mismatch in constant table!");
287 return cast<Constant>(V);
290 // Create and return a placeholder, which will later be RAUW'd.
291 Constant *C = new ConstantPlaceHolder(Ty, Context);
296 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
300 if (Value *V = ValuePtrs[Idx]) {
301 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
305 // No type specified, must be invalid reference.
306 if (!Ty) return nullptr;
308 // Create and return a placeholder, which will later be RAUW'd.
309 Value *V = new Argument(Ty);
314 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
315 /// resolves any forward references. The idea behind this is that we sometimes
316 /// get constants (such as large arrays) which reference *many* forward ref
317 /// constants. Replacing each of these causes a lot of thrashing when
318 /// building/reuniquing the constant. Instead of doing this, we look at all the
319 /// uses and rewrite all the place holders at once for any constant that uses
321 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
322 // Sort the values by-pointer so that they are efficient to look up with a
324 std::sort(ResolveConstants.begin(), ResolveConstants.end());
326 SmallVector<Constant*, 64> NewOps;
328 while (!ResolveConstants.empty()) {
329 Value *RealVal = operator[](ResolveConstants.back().second);
330 Constant *Placeholder = ResolveConstants.back().first;
331 ResolveConstants.pop_back();
333 // Loop over all users of the placeholder, updating them to reference the
334 // new value. If they reference more than one placeholder, update them all
336 while (!Placeholder->use_empty()) {
337 auto UI = Placeholder->user_begin();
340 // If the using object isn't uniqued, just update the operands. This
341 // handles instructions and initializers for global variables.
342 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
343 UI.getUse().set(RealVal);
347 // Otherwise, we have a constant that uses the placeholder. Replace that
348 // constant with a new constant that has *all* placeholder uses updated.
349 Constant *UserC = cast<Constant>(U);
350 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
353 if (!isa<ConstantPlaceHolder>(*I)) {
354 // Not a placeholder reference.
356 } else if (*I == Placeholder) {
357 // Common case is that it just references this one placeholder.
360 // Otherwise, look up the placeholder in ResolveConstants.
361 ResolveConstantsTy::iterator It =
362 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
363 std::pair<Constant*, unsigned>(cast<Constant>(*I),
365 assert(It != ResolveConstants.end() && It->first == *I);
366 NewOp = operator[](It->second);
369 NewOps.push_back(cast<Constant>(NewOp));
372 // Make the new constant.
374 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
375 NewC = ConstantArray::get(UserCA->getType(), NewOps);
376 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
377 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
378 } else if (isa<ConstantVector>(UserC)) {
379 NewC = ConstantVector::get(NewOps);
381 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
382 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
385 UserC->replaceAllUsesWith(NewC);
386 UserC->destroyConstant();
390 // Update all ValueHandles, they should be the only users at this point.
391 Placeholder->replaceAllUsesWith(RealVal);
396 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
405 WeakVH &OldV = MDValuePtrs[Idx];
411 // If there was a forward reference to this value, replace it.
412 MDNode *PrevVal = cast<MDNode>(OldV);
413 OldV->replaceAllUsesWith(V);
414 MDNode::deleteTemporary(PrevVal);
415 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
417 MDValuePtrs[Idx] = V;
420 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
424 if (Value *V = MDValuePtrs[Idx]) {
425 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
429 // Create and return a placeholder, which will later be RAUW'd.
430 Value *V = MDNode::getTemporary(Context, None);
431 MDValuePtrs[Idx] = V;
435 Type *BitcodeReader::getTypeByID(unsigned ID) {
436 // The type table size is always specified correctly.
437 if (ID >= TypeList.size())
440 if (Type *Ty = TypeList[ID])
443 // If we have a forward reference, the only possible case is when it is to a
444 // named struct. Just create a placeholder for now.
445 return TypeList[ID] = StructType::create(Context);
449 //===----------------------------------------------------------------------===//
450 // Functions for parsing blocks from the bitcode file
451 //===----------------------------------------------------------------------===//
454 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
455 /// been decoded from the given integer. This function must stay in sync with
456 /// 'encodeLLVMAttributesForBitcode'.
457 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
458 uint64_t EncodedAttrs) {
459 // FIXME: Remove in 4.0.
461 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
462 // the bits above 31 down by 11 bits.
463 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
464 assert((!Alignment || isPowerOf2_32(Alignment)) &&
465 "Alignment must be a power of two.");
468 B.addAlignmentAttr(Alignment);
469 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
470 (EncodedAttrs & 0xffff));
473 error_code BitcodeReader::ParseAttributeBlock() {
474 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
475 return Error(InvalidRecord);
477 if (!MAttributes.empty())
478 return Error(InvalidMultipleBlocks);
480 SmallVector<uint64_t, 64> Record;
482 SmallVector<AttributeSet, 8> Attrs;
484 // Read all the records.
486 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
488 switch (Entry.Kind) {
489 case BitstreamEntry::SubBlock: // Handled for us already.
490 case BitstreamEntry::Error:
491 return Error(MalformedBlock);
492 case BitstreamEntry::EndBlock:
493 return error_code::success();
494 case BitstreamEntry::Record:
495 // The interesting case.
501 switch (Stream.readRecord(Entry.ID, Record)) {
502 default: // Default behavior: ignore.
504 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
505 // FIXME: Remove in 4.0.
506 if (Record.size() & 1)
507 return Error(InvalidRecord);
509 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
511 decodeLLVMAttributesForBitcode(B, Record[i+1]);
512 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
515 MAttributes.push_back(AttributeSet::get(Context, Attrs));
519 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
520 for (unsigned i = 0, e = Record.size(); i != e; ++i)
521 Attrs.push_back(MAttributeGroups[Record[i]]);
523 MAttributes.push_back(AttributeSet::get(Context, Attrs));
531 // Returns Attribute::None on unrecognized codes.
532 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
535 return Attribute::None;
536 case bitc::ATTR_KIND_ALIGNMENT:
537 return Attribute::Alignment;
538 case bitc::ATTR_KIND_ALWAYS_INLINE:
539 return Attribute::AlwaysInline;
540 case bitc::ATTR_KIND_BUILTIN:
541 return Attribute::Builtin;
542 case bitc::ATTR_KIND_BY_VAL:
543 return Attribute::ByVal;
544 case bitc::ATTR_KIND_IN_ALLOCA:
545 return Attribute::InAlloca;
546 case bitc::ATTR_KIND_COLD:
547 return Attribute::Cold;
548 case bitc::ATTR_KIND_INLINE_HINT:
549 return Attribute::InlineHint;
550 case bitc::ATTR_KIND_IN_REG:
551 return Attribute::InReg;
552 case bitc::ATTR_KIND_MIN_SIZE:
553 return Attribute::MinSize;
554 case bitc::ATTR_KIND_NAKED:
555 return Attribute::Naked;
556 case bitc::ATTR_KIND_NEST:
557 return Attribute::Nest;
558 case bitc::ATTR_KIND_NO_ALIAS:
559 return Attribute::NoAlias;
560 case bitc::ATTR_KIND_NO_BUILTIN:
561 return Attribute::NoBuiltin;
562 case bitc::ATTR_KIND_NO_CAPTURE:
563 return Attribute::NoCapture;
564 case bitc::ATTR_KIND_NO_DUPLICATE:
565 return Attribute::NoDuplicate;
566 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
567 return Attribute::NoImplicitFloat;
568 case bitc::ATTR_KIND_NO_INLINE:
569 return Attribute::NoInline;
570 case bitc::ATTR_KIND_NON_LAZY_BIND:
571 return Attribute::NonLazyBind;
572 case bitc::ATTR_KIND_NO_RED_ZONE:
573 return Attribute::NoRedZone;
574 case bitc::ATTR_KIND_NO_RETURN:
575 return Attribute::NoReturn;
576 case bitc::ATTR_KIND_NO_UNWIND:
577 return Attribute::NoUnwind;
578 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
579 return Attribute::OptimizeForSize;
580 case bitc::ATTR_KIND_OPTIMIZE_NONE:
581 return Attribute::OptimizeNone;
582 case bitc::ATTR_KIND_READ_NONE:
583 return Attribute::ReadNone;
584 case bitc::ATTR_KIND_READ_ONLY:
585 return Attribute::ReadOnly;
586 case bitc::ATTR_KIND_RETURNED:
587 return Attribute::Returned;
588 case bitc::ATTR_KIND_RETURNS_TWICE:
589 return Attribute::ReturnsTwice;
590 case bitc::ATTR_KIND_S_EXT:
591 return Attribute::SExt;
592 case bitc::ATTR_KIND_STACK_ALIGNMENT:
593 return Attribute::StackAlignment;
594 case bitc::ATTR_KIND_STACK_PROTECT:
595 return Attribute::StackProtect;
596 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
597 return Attribute::StackProtectReq;
598 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
599 return Attribute::StackProtectStrong;
600 case bitc::ATTR_KIND_STRUCT_RET:
601 return Attribute::StructRet;
602 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
603 return Attribute::SanitizeAddress;
604 case bitc::ATTR_KIND_SANITIZE_THREAD:
605 return Attribute::SanitizeThread;
606 case bitc::ATTR_KIND_SANITIZE_MEMORY:
607 return Attribute::SanitizeMemory;
608 case bitc::ATTR_KIND_UW_TABLE:
609 return Attribute::UWTable;
610 case bitc::ATTR_KIND_Z_EXT:
611 return Attribute::ZExt;
615 error_code BitcodeReader::ParseAttrKind(uint64_t Code,
616 Attribute::AttrKind *Kind) {
617 *Kind = GetAttrFromCode(Code);
618 if (*Kind == Attribute::None)
619 return Error(InvalidValue);
620 return error_code::success();
623 error_code BitcodeReader::ParseAttributeGroupBlock() {
624 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
625 return Error(InvalidRecord);
627 if (!MAttributeGroups.empty())
628 return Error(InvalidMultipleBlocks);
630 SmallVector<uint64_t, 64> Record;
632 // Read all the records.
634 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
636 switch (Entry.Kind) {
637 case BitstreamEntry::SubBlock: // Handled for us already.
638 case BitstreamEntry::Error:
639 return Error(MalformedBlock);
640 case BitstreamEntry::EndBlock:
641 return error_code::success();
642 case BitstreamEntry::Record:
643 // The interesting case.
649 switch (Stream.readRecord(Entry.ID, Record)) {
650 default: // Default behavior: ignore.
652 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
653 if (Record.size() < 3)
654 return Error(InvalidRecord);
656 uint64_t GrpID = Record[0];
657 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
660 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
661 if (Record[i] == 0) { // Enum attribute
662 Attribute::AttrKind Kind;
663 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
666 B.addAttribute(Kind);
667 } else if (Record[i] == 1) { // Align attribute
668 Attribute::AttrKind Kind;
669 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
671 if (Kind == Attribute::Alignment)
672 B.addAlignmentAttr(Record[++i]);
674 B.addStackAlignmentAttr(Record[++i]);
675 } else { // String attribute
676 assert((Record[i] == 3 || Record[i] == 4) &&
677 "Invalid attribute group entry");
678 bool HasValue = (Record[i++] == 4);
679 SmallString<64> KindStr;
680 SmallString<64> ValStr;
682 while (Record[i] != 0 && i != e)
683 KindStr += Record[i++];
684 assert(Record[i] == 0 && "Kind string not null terminated");
687 // Has a value associated with it.
688 ++i; // Skip the '0' that terminates the "kind" string.
689 while (Record[i] != 0 && i != e)
690 ValStr += Record[i++];
691 assert(Record[i] == 0 && "Value string not null terminated");
694 B.addAttribute(KindStr.str(), ValStr.str());
698 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
705 error_code BitcodeReader::ParseTypeTable() {
706 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
707 return Error(InvalidRecord);
709 return ParseTypeTableBody();
712 error_code BitcodeReader::ParseTypeTableBody() {
713 if (!TypeList.empty())
714 return Error(InvalidMultipleBlocks);
716 SmallVector<uint64_t, 64> Record;
717 unsigned NumRecords = 0;
719 SmallString<64> TypeName;
721 // Read all the records for this type table.
723 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
725 switch (Entry.Kind) {
726 case BitstreamEntry::SubBlock: // Handled for us already.
727 case BitstreamEntry::Error:
728 return Error(MalformedBlock);
729 case BitstreamEntry::EndBlock:
730 if (NumRecords != TypeList.size())
731 return Error(MalformedBlock);
732 return error_code::success();
733 case BitstreamEntry::Record:
734 // The interesting case.
740 Type *ResultTy = nullptr;
741 switch (Stream.readRecord(Entry.ID, Record)) {
743 return Error(InvalidValue);
744 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
745 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
746 // type list. This allows us to reserve space.
747 if (Record.size() < 1)
748 return Error(InvalidRecord);
749 TypeList.resize(Record[0]);
751 case bitc::TYPE_CODE_VOID: // VOID
752 ResultTy = Type::getVoidTy(Context);
754 case bitc::TYPE_CODE_HALF: // HALF
755 ResultTy = Type::getHalfTy(Context);
757 case bitc::TYPE_CODE_FLOAT: // FLOAT
758 ResultTy = Type::getFloatTy(Context);
760 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
761 ResultTy = Type::getDoubleTy(Context);
763 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
764 ResultTy = Type::getX86_FP80Ty(Context);
766 case bitc::TYPE_CODE_FP128: // FP128
767 ResultTy = Type::getFP128Ty(Context);
769 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
770 ResultTy = Type::getPPC_FP128Ty(Context);
772 case bitc::TYPE_CODE_LABEL: // LABEL
773 ResultTy = Type::getLabelTy(Context);
775 case bitc::TYPE_CODE_METADATA: // METADATA
776 ResultTy = Type::getMetadataTy(Context);
778 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
779 ResultTy = Type::getX86_MMXTy(Context);
781 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
782 if (Record.size() < 1)
783 return Error(InvalidRecord);
785 ResultTy = IntegerType::get(Context, Record[0]);
787 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
788 // [pointee type, address space]
789 if (Record.size() < 1)
790 return Error(InvalidRecord);
791 unsigned AddressSpace = 0;
792 if (Record.size() == 2)
793 AddressSpace = Record[1];
794 ResultTy = getTypeByID(Record[0]);
796 return Error(InvalidType);
797 ResultTy = PointerType::get(ResultTy, AddressSpace);
800 case bitc::TYPE_CODE_FUNCTION_OLD: {
801 // FIXME: attrid is dead, remove it in LLVM 4.0
802 // FUNCTION: [vararg, attrid, retty, paramty x N]
803 if (Record.size() < 3)
804 return Error(InvalidRecord);
805 SmallVector<Type*, 8> ArgTys;
806 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
807 if (Type *T = getTypeByID(Record[i]))
813 ResultTy = getTypeByID(Record[2]);
814 if (!ResultTy || ArgTys.size() < Record.size()-3)
815 return Error(InvalidType);
817 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
820 case bitc::TYPE_CODE_FUNCTION: {
821 // FUNCTION: [vararg, retty, paramty x N]
822 if (Record.size() < 2)
823 return Error(InvalidRecord);
824 SmallVector<Type*, 8> ArgTys;
825 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
826 if (Type *T = getTypeByID(Record[i]))
832 ResultTy = getTypeByID(Record[1]);
833 if (!ResultTy || ArgTys.size() < Record.size()-2)
834 return Error(InvalidType);
836 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
839 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
840 if (Record.size() < 1)
841 return Error(InvalidRecord);
842 SmallVector<Type*, 8> EltTys;
843 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
844 if (Type *T = getTypeByID(Record[i]))
849 if (EltTys.size() != Record.size()-1)
850 return Error(InvalidType);
851 ResultTy = StructType::get(Context, EltTys, Record[0]);
854 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
855 if (ConvertToString(Record, 0, TypeName))
856 return Error(InvalidRecord);
859 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
860 if (Record.size() < 1)
861 return Error(InvalidRecord);
863 if (NumRecords >= TypeList.size())
864 return Error(InvalidTYPETable);
866 // Check to see if this was forward referenced, if so fill in the temp.
867 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
869 Res->setName(TypeName);
870 TypeList[NumRecords] = nullptr;
871 } else // Otherwise, create a new struct.
872 Res = StructType::create(Context, TypeName);
875 SmallVector<Type*, 8> EltTys;
876 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
877 if (Type *T = getTypeByID(Record[i]))
882 if (EltTys.size() != Record.size()-1)
883 return Error(InvalidRecord);
884 Res->setBody(EltTys, Record[0]);
888 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
889 if (Record.size() != 1)
890 return Error(InvalidRecord);
892 if (NumRecords >= TypeList.size())
893 return Error(InvalidTYPETable);
895 // Check to see if this was forward referenced, if so fill in the temp.
896 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
898 Res->setName(TypeName);
899 TypeList[NumRecords] = nullptr;
900 } else // Otherwise, create a new struct with no body.
901 Res = StructType::create(Context, TypeName);
906 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
907 if (Record.size() < 2)
908 return Error(InvalidRecord);
909 if ((ResultTy = getTypeByID(Record[1])))
910 ResultTy = ArrayType::get(ResultTy, Record[0]);
912 return Error(InvalidType);
914 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
915 if (Record.size() < 2)
916 return Error(InvalidRecord);
917 if ((ResultTy = getTypeByID(Record[1])))
918 ResultTy = VectorType::get(ResultTy, Record[0]);
920 return Error(InvalidType);
924 if (NumRecords >= TypeList.size())
925 return Error(InvalidTYPETable);
926 assert(ResultTy && "Didn't read a type?");
927 assert(!TypeList[NumRecords] && "Already read type?");
928 TypeList[NumRecords++] = ResultTy;
932 error_code BitcodeReader::ParseValueSymbolTable() {
933 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
934 return Error(InvalidRecord);
936 SmallVector<uint64_t, 64> Record;
938 // Read all the records for this value table.
939 SmallString<128> ValueName;
941 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
943 switch (Entry.Kind) {
944 case BitstreamEntry::SubBlock: // Handled for us already.
945 case BitstreamEntry::Error:
946 return Error(MalformedBlock);
947 case BitstreamEntry::EndBlock:
948 return error_code::success();
949 case BitstreamEntry::Record:
950 // The interesting case.
956 switch (Stream.readRecord(Entry.ID, Record)) {
957 default: // Default behavior: unknown type.
959 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
960 if (ConvertToString(Record, 1, ValueName))
961 return Error(InvalidRecord);
962 unsigned ValueID = Record[0];
963 if (ValueID >= ValueList.size() || !ValueList[ValueID])
964 return Error(InvalidRecord);
965 Value *V = ValueList[ValueID];
967 V->setName(StringRef(ValueName.data(), ValueName.size()));
971 case bitc::VST_CODE_BBENTRY: {
972 if (ConvertToString(Record, 1, ValueName))
973 return Error(InvalidRecord);
974 BasicBlock *BB = getBasicBlock(Record[0]);
976 return Error(InvalidRecord);
978 BB->setName(StringRef(ValueName.data(), ValueName.size()));
986 error_code BitcodeReader::ParseMetadata() {
987 unsigned NextMDValueNo = MDValueList.size();
989 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
990 return Error(InvalidRecord);
992 SmallVector<uint64_t, 64> Record;
994 // Read all the records.
996 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
998 switch (Entry.Kind) {
999 case BitstreamEntry::SubBlock: // Handled for us already.
1000 case BitstreamEntry::Error:
1001 return Error(MalformedBlock);
1002 case BitstreamEntry::EndBlock:
1003 return error_code::success();
1004 case BitstreamEntry::Record:
1005 // The interesting case.
1009 bool IsFunctionLocal = false;
1012 unsigned Code = Stream.readRecord(Entry.ID, Record);
1014 default: // Default behavior: ignore.
1016 case bitc::METADATA_NAME: {
1017 // Read name of the named metadata.
1018 SmallString<8> Name(Record.begin(), Record.end());
1020 Code = Stream.ReadCode();
1022 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1023 unsigned NextBitCode = Stream.readRecord(Code, Record);
1024 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1026 // Read named metadata elements.
1027 unsigned Size = Record.size();
1028 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1029 for (unsigned i = 0; i != Size; ++i) {
1030 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1032 return Error(InvalidRecord);
1033 NMD->addOperand(MD);
1037 case bitc::METADATA_FN_NODE:
1038 IsFunctionLocal = true;
1040 case bitc::METADATA_NODE: {
1041 if (Record.size() % 2 == 1)
1042 return Error(InvalidRecord);
1044 unsigned Size = Record.size();
1045 SmallVector<Value*, 8> Elts;
1046 for (unsigned i = 0; i != Size; i += 2) {
1047 Type *Ty = getTypeByID(Record[i]);
1049 return Error(InvalidRecord);
1050 if (Ty->isMetadataTy())
1051 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1052 else if (!Ty->isVoidTy())
1053 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1055 Elts.push_back(nullptr);
1057 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1058 IsFunctionLocal = false;
1059 MDValueList.AssignValue(V, NextMDValueNo++);
1062 case bitc::METADATA_STRING: {
1063 SmallString<8> String(Record.begin(), Record.end());
1064 Value *V = MDString::get(Context, String);
1065 MDValueList.AssignValue(V, NextMDValueNo++);
1068 case bitc::METADATA_KIND: {
1069 if (Record.size() < 2)
1070 return Error(InvalidRecord);
1072 unsigned Kind = Record[0];
1073 SmallString<8> Name(Record.begin()+1, Record.end());
1075 unsigned NewKind = TheModule->getMDKindID(Name.str());
1076 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1077 return Error(ConflictingMETADATA_KINDRecords);
1084 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1085 /// the LSB for dense VBR encoding.
1086 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1091 // There is no such thing as -0 with integers. "-0" really means MININT.
1095 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1096 /// values and aliases that we can.
1097 error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1098 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1099 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1100 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1102 GlobalInitWorklist.swap(GlobalInits);
1103 AliasInitWorklist.swap(AliasInits);
1104 FunctionPrefixWorklist.swap(FunctionPrefixes);
1106 while (!GlobalInitWorklist.empty()) {
1107 unsigned ValID = GlobalInitWorklist.back().second;
1108 if (ValID >= ValueList.size()) {
1109 // Not ready to resolve this yet, it requires something later in the file.
1110 GlobalInits.push_back(GlobalInitWorklist.back());
1112 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1113 GlobalInitWorklist.back().first->setInitializer(C);
1115 return Error(ExpectedConstant);
1117 GlobalInitWorklist.pop_back();
1120 while (!AliasInitWorklist.empty()) {
1121 unsigned ValID = AliasInitWorklist.back().second;
1122 if (ValID >= ValueList.size()) {
1123 AliasInits.push_back(AliasInitWorklist.back());
1125 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1126 AliasInitWorklist.back().first->setAliasee(C);
1128 return Error(ExpectedConstant);
1130 AliasInitWorklist.pop_back();
1133 while (!FunctionPrefixWorklist.empty()) {
1134 unsigned ValID = FunctionPrefixWorklist.back().second;
1135 if (ValID >= ValueList.size()) {
1136 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1138 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1139 FunctionPrefixWorklist.back().first->setPrefixData(C);
1141 return Error(ExpectedConstant);
1143 FunctionPrefixWorklist.pop_back();
1146 return error_code::success();
1149 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1150 SmallVector<uint64_t, 8> Words(Vals.size());
1151 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1152 BitcodeReader::decodeSignRotatedValue);
1154 return APInt(TypeBits, Words);
1157 error_code BitcodeReader::ParseConstants() {
1158 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1159 return Error(InvalidRecord);
1161 SmallVector<uint64_t, 64> Record;
1163 // Read all the records for this value table.
1164 Type *CurTy = Type::getInt32Ty(Context);
1165 unsigned NextCstNo = ValueList.size();
1167 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1169 switch (Entry.Kind) {
1170 case BitstreamEntry::SubBlock: // Handled for us already.
1171 case BitstreamEntry::Error:
1172 return Error(MalformedBlock);
1173 case BitstreamEntry::EndBlock:
1174 if (NextCstNo != ValueList.size())
1175 return Error(InvalidConstantReference);
1177 // Once all the constants have been read, go through and resolve forward
1179 ValueList.ResolveConstantForwardRefs();
1180 return error_code::success();
1181 case BitstreamEntry::Record:
1182 // The interesting case.
1189 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1191 default: // Default behavior: unknown constant
1192 case bitc::CST_CODE_UNDEF: // UNDEF
1193 V = UndefValue::get(CurTy);
1195 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1197 return Error(InvalidRecord);
1198 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1199 return Error(InvalidRecord);
1200 CurTy = TypeList[Record[0]];
1201 continue; // Skip the ValueList manipulation.
1202 case bitc::CST_CODE_NULL: // NULL
1203 V = Constant::getNullValue(CurTy);
1205 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1206 if (!CurTy->isIntegerTy() || Record.empty())
1207 return Error(InvalidRecord);
1208 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1210 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1211 if (!CurTy->isIntegerTy() || Record.empty())
1212 return Error(InvalidRecord);
1214 APInt VInt = ReadWideAPInt(Record,
1215 cast<IntegerType>(CurTy)->getBitWidth());
1216 V = ConstantInt::get(Context, VInt);
1220 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1222 return Error(InvalidRecord);
1223 if (CurTy->isHalfTy())
1224 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1225 APInt(16, (uint16_t)Record[0])));
1226 else if (CurTy->isFloatTy())
1227 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1228 APInt(32, (uint32_t)Record[0])));
1229 else if (CurTy->isDoubleTy())
1230 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1231 APInt(64, Record[0])));
1232 else if (CurTy->isX86_FP80Ty()) {
1233 // Bits are not stored the same way as a normal i80 APInt, compensate.
1234 uint64_t Rearrange[2];
1235 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1236 Rearrange[1] = Record[0] >> 48;
1237 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1238 APInt(80, Rearrange)));
1239 } else if (CurTy->isFP128Ty())
1240 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1241 APInt(128, Record)));
1242 else if (CurTy->isPPC_FP128Ty())
1243 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1244 APInt(128, Record)));
1246 V = UndefValue::get(CurTy);
1250 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1252 return Error(InvalidRecord);
1254 unsigned Size = Record.size();
1255 SmallVector<Constant*, 16> Elts;
1257 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1258 for (unsigned i = 0; i != Size; ++i)
1259 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1260 STy->getElementType(i)));
1261 V = ConstantStruct::get(STy, Elts);
1262 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1263 Type *EltTy = ATy->getElementType();
1264 for (unsigned i = 0; i != Size; ++i)
1265 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1266 V = ConstantArray::get(ATy, Elts);
1267 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1268 Type *EltTy = VTy->getElementType();
1269 for (unsigned i = 0; i != Size; ++i)
1270 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1271 V = ConstantVector::get(Elts);
1273 V = UndefValue::get(CurTy);
1277 case bitc::CST_CODE_STRING: // STRING: [values]
1278 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1280 return Error(InvalidRecord);
1282 SmallString<16> Elts(Record.begin(), Record.end());
1283 V = ConstantDataArray::getString(Context, Elts,
1284 BitCode == bitc::CST_CODE_CSTRING);
1287 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1289 return Error(InvalidRecord);
1291 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1292 unsigned Size = Record.size();
1294 if (EltTy->isIntegerTy(8)) {
1295 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1296 if (isa<VectorType>(CurTy))
1297 V = ConstantDataVector::get(Context, Elts);
1299 V = ConstantDataArray::get(Context, Elts);
1300 } else if (EltTy->isIntegerTy(16)) {
1301 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1302 if (isa<VectorType>(CurTy))
1303 V = ConstantDataVector::get(Context, Elts);
1305 V = ConstantDataArray::get(Context, Elts);
1306 } else if (EltTy->isIntegerTy(32)) {
1307 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1308 if (isa<VectorType>(CurTy))
1309 V = ConstantDataVector::get(Context, Elts);
1311 V = ConstantDataArray::get(Context, Elts);
1312 } else if (EltTy->isIntegerTy(64)) {
1313 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1314 if (isa<VectorType>(CurTy))
1315 V = ConstantDataVector::get(Context, Elts);
1317 V = ConstantDataArray::get(Context, Elts);
1318 } else if (EltTy->isFloatTy()) {
1319 SmallVector<float, 16> Elts(Size);
1320 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1321 if (isa<VectorType>(CurTy))
1322 V = ConstantDataVector::get(Context, Elts);
1324 V = ConstantDataArray::get(Context, Elts);
1325 } else if (EltTy->isDoubleTy()) {
1326 SmallVector<double, 16> Elts(Size);
1327 std::transform(Record.begin(), Record.end(), Elts.begin(),
1329 if (isa<VectorType>(CurTy))
1330 V = ConstantDataVector::get(Context, Elts);
1332 V = ConstantDataArray::get(Context, Elts);
1334 return Error(InvalidTypeForValue);
1339 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1340 if (Record.size() < 3)
1341 return Error(InvalidRecord);
1342 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1344 V = UndefValue::get(CurTy); // Unknown binop.
1346 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1347 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1349 if (Record.size() >= 4) {
1350 if (Opc == Instruction::Add ||
1351 Opc == Instruction::Sub ||
1352 Opc == Instruction::Mul ||
1353 Opc == Instruction::Shl) {
1354 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1355 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1356 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1357 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1358 } else if (Opc == Instruction::SDiv ||
1359 Opc == Instruction::UDiv ||
1360 Opc == Instruction::LShr ||
1361 Opc == Instruction::AShr) {
1362 if (Record[3] & (1 << bitc::PEO_EXACT))
1363 Flags |= SDivOperator::IsExact;
1366 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1370 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1371 if (Record.size() < 3)
1372 return Error(InvalidRecord);
1373 int Opc = GetDecodedCastOpcode(Record[0]);
1375 V = UndefValue::get(CurTy); // Unknown cast.
1377 Type *OpTy = getTypeByID(Record[1]);
1379 return Error(InvalidRecord);
1380 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1381 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1382 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1386 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1387 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1388 if (Record.size() & 1)
1389 return Error(InvalidRecord);
1390 SmallVector<Constant*, 16> Elts;
1391 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1392 Type *ElTy = getTypeByID(Record[i]);
1394 return Error(InvalidRecord);
1395 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1397 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1398 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1400 bitc::CST_CODE_CE_INBOUNDS_GEP);
1403 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1404 if (Record.size() < 3)
1405 return Error(InvalidRecord);
1407 Type *SelectorTy = Type::getInt1Ty(Context);
1409 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1410 // vector. Otherwise, it must be a single bit.
1411 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1412 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1413 VTy->getNumElements());
1415 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1417 ValueList.getConstantFwdRef(Record[1],CurTy),
1418 ValueList.getConstantFwdRef(Record[2],CurTy));
1421 case bitc::CST_CODE_CE_EXTRACTELT
1422 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1423 if (Record.size() < 3)
1424 return Error(InvalidRecord);
1426 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1428 return Error(InvalidRecord);
1429 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1430 Constant *Op1 = nullptr;
1431 if (Record.size() == 4) {
1432 Type *IdxTy = getTypeByID(Record[2]);
1434 return Error(InvalidRecord);
1435 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1436 } else // TODO: Remove with llvm 4.0
1437 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1439 return Error(InvalidRecord);
1440 V = ConstantExpr::getExtractElement(Op0, Op1);
1443 case bitc::CST_CODE_CE_INSERTELT
1444 : { // CE_INSERTELT: [opval, opval, opty, opval]
1445 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1446 if (Record.size() < 3 || !OpTy)
1447 return Error(InvalidRecord);
1448 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1449 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1450 OpTy->getElementType());
1451 Constant *Op2 = nullptr;
1452 if (Record.size() == 4) {
1453 Type *IdxTy = getTypeByID(Record[2]);
1455 return Error(InvalidRecord);
1456 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1457 } else // TODO: Remove with llvm 4.0
1458 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1460 return Error(InvalidRecord);
1461 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1464 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1465 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1466 if (Record.size() < 3 || !OpTy)
1467 return Error(InvalidRecord);
1468 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1469 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1470 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1471 OpTy->getNumElements());
1472 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1473 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1476 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1477 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1479 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1480 if (Record.size() < 4 || !RTy || !OpTy)
1481 return Error(InvalidRecord);
1482 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1483 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1484 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1485 RTy->getNumElements());
1486 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1487 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1490 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1491 if (Record.size() < 4)
1492 return Error(InvalidRecord);
1493 Type *OpTy = getTypeByID(Record[0]);
1495 return Error(InvalidRecord);
1496 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1497 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1499 if (OpTy->isFPOrFPVectorTy())
1500 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1502 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1505 // This maintains backward compatibility, pre-asm dialect keywords.
1506 // FIXME: Remove with the 4.0 release.
1507 case bitc::CST_CODE_INLINEASM_OLD: {
1508 if (Record.size() < 2)
1509 return Error(InvalidRecord);
1510 std::string AsmStr, ConstrStr;
1511 bool HasSideEffects = Record[0] & 1;
1512 bool IsAlignStack = Record[0] >> 1;
1513 unsigned AsmStrSize = Record[1];
1514 if (2+AsmStrSize >= Record.size())
1515 return Error(InvalidRecord);
1516 unsigned ConstStrSize = Record[2+AsmStrSize];
1517 if (3+AsmStrSize+ConstStrSize > Record.size())
1518 return Error(InvalidRecord);
1520 for (unsigned i = 0; i != AsmStrSize; ++i)
1521 AsmStr += (char)Record[2+i];
1522 for (unsigned i = 0; i != ConstStrSize; ++i)
1523 ConstrStr += (char)Record[3+AsmStrSize+i];
1524 PointerType *PTy = cast<PointerType>(CurTy);
1525 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1526 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1529 // This version adds support for the asm dialect keywords (e.g.,
1531 case bitc::CST_CODE_INLINEASM: {
1532 if (Record.size() < 2)
1533 return Error(InvalidRecord);
1534 std::string AsmStr, ConstrStr;
1535 bool HasSideEffects = Record[0] & 1;
1536 bool IsAlignStack = (Record[0] >> 1) & 1;
1537 unsigned AsmDialect = Record[0] >> 2;
1538 unsigned AsmStrSize = Record[1];
1539 if (2+AsmStrSize >= Record.size())
1540 return Error(InvalidRecord);
1541 unsigned ConstStrSize = Record[2+AsmStrSize];
1542 if (3+AsmStrSize+ConstStrSize > Record.size())
1543 return Error(InvalidRecord);
1545 for (unsigned i = 0; i != AsmStrSize; ++i)
1546 AsmStr += (char)Record[2+i];
1547 for (unsigned i = 0; i != ConstStrSize; ++i)
1548 ConstrStr += (char)Record[3+AsmStrSize+i];
1549 PointerType *PTy = cast<PointerType>(CurTy);
1550 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1551 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1552 InlineAsm::AsmDialect(AsmDialect));
1555 case bitc::CST_CODE_BLOCKADDRESS:{
1556 if (Record.size() < 3)
1557 return Error(InvalidRecord);
1558 Type *FnTy = getTypeByID(Record[0]);
1560 return Error(InvalidRecord);
1562 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1564 return Error(InvalidRecord);
1566 // If the function is already parsed we can insert the block address right
1569 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1570 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1572 return Error(InvalidID);
1575 V = BlockAddress::get(Fn, BBI);
1577 // Otherwise insert a placeholder and remember it so it can be inserted
1578 // when the function is parsed.
1579 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1580 Type::getInt8Ty(Context),
1581 false, GlobalValue::InternalLinkage,
1583 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1590 ValueList.AssignValue(V, NextCstNo);
1595 error_code BitcodeReader::ParseUseLists() {
1596 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1597 return Error(InvalidRecord);
1599 SmallVector<uint64_t, 64> Record;
1601 // Read all the records.
1603 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1605 switch (Entry.Kind) {
1606 case BitstreamEntry::SubBlock: // Handled for us already.
1607 case BitstreamEntry::Error:
1608 return Error(MalformedBlock);
1609 case BitstreamEntry::EndBlock:
1610 return error_code::success();
1611 case BitstreamEntry::Record:
1612 // The interesting case.
1616 // Read a use list record.
1618 switch (Stream.readRecord(Entry.ID, Record)) {
1619 default: // Default behavior: unknown type.
1621 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1622 unsigned RecordLength = Record.size();
1623 if (RecordLength < 1)
1624 return Error(InvalidRecord);
1625 UseListRecords.push_back(Record);
1632 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1633 /// remember where it is and then skip it. This lets us lazily deserialize the
1635 error_code BitcodeReader::RememberAndSkipFunctionBody() {
1636 // Get the function we are talking about.
1637 if (FunctionsWithBodies.empty())
1638 return Error(InsufficientFunctionProtos);
1640 Function *Fn = FunctionsWithBodies.back();
1641 FunctionsWithBodies.pop_back();
1643 // Save the current stream state.
1644 uint64_t CurBit = Stream.GetCurrentBitNo();
1645 DeferredFunctionInfo[Fn] = CurBit;
1647 // Skip over the function block for now.
1648 if (Stream.SkipBlock())
1649 return Error(InvalidRecord);
1650 return error_code::success();
1653 error_code BitcodeReader::GlobalCleanup() {
1654 // Patch the initializers for globals and aliases up.
1655 ResolveGlobalAndAliasInits();
1656 if (!GlobalInits.empty() || !AliasInits.empty())
1657 return Error(MalformedGlobalInitializerSet);
1659 // Look for intrinsic functions which need to be upgraded at some point
1660 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1663 if (UpgradeIntrinsicFunction(FI, NewFn))
1664 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1667 // Look for global variables which need to be renamed.
1668 for (Module::global_iterator
1669 GI = TheModule->global_begin(), GE = TheModule->global_end();
1671 UpgradeGlobalVariable(GI);
1672 // Force deallocation of memory for these vectors to favor the client that
1673 // want lazy deserialization.
1674 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1675 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1676 return error_code::success();
1679 error_code BitcodeReader::ParseModule(bool Resume) {
1681 Stream.JumpToBit(NextUnreadBit);
1682 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1683 return Error(InvalidRecord);
1685 SmallVector<uint64_t, 64> Record;
1686 std::vector<std::string> SectionTable;
1687 std::vector<std::string> GCTable;
1689 // Read all the records for this module.
1691 BitstreamEntry Entry = Stream.advance();
1693 switch (Entry.Kind) {
1694 case BitstreamEntry::Error:
1695 return Error(MalformedBlock);
1696 case BitstreamEntry::EndBlock:
1697 return GlobalCleanup();
1699 case BitstreamEntry::SubBlock:
1701 default: // Skip unknown content.
1702 if (Stream.SkipBlock())
1703 return Error(InvalidRecord);
1705 case bitc::BLOCKINFO_BLOCK_ID:
1706 if (Stream.ReadBlockInfoBlock())
1707 return Error(MalformedBlock);
1709 case bitc::PARAMATTR_BLOCK_ID:
1710 if (error_code EC = ParseAttributeBlock())
1713 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1714 if (error_code EC = ParseAttributeGroupBlock())
1717 case bitc::TYPE_BLOCK_ID_NEW:
1718 if (error_code EC = ParseTypeTable())
1721 case bitc::VALUE_SYMTAB_BLOCK_ID:
1722 if (error_code EC = ParseValueSymbolTable())
1724 SeenValueSymbolTable = true;
1726 case bitc::CONSTANTS_BLOCK_ID:
1727 if (error_code EC = ParseConstants())
1729 if (error_code EC = ResolveGlobalAndAliasInits())
1732 case bitc::METADATA_BLOCK_ID:
1733 if (error_code EC = ParseMetadata())
1736 case bitc::FUNCTION_BLOCK_ID:
1737 // If this is the first function body we've seen, reverse the
1738 // FunctionsWithBodies list.
1739 if (!SeenFirstFunctionBody) {
1740 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1741 if (error_code EC = GlobalCleanup())
1743 SeenFirstFunctionBody = true;
1746 if (error_code EC = RememberAndSkipFunctionBody())
1748 // For streaming bitcode, suspend parsing when we reach the function
1749 // bodies. Subsequent materialization calls will resume it when
1750 // necessary. For streaming, the function bodies must be at the end of
1751 // the bitcode. If the bitcode file is old, the symbol table will be
1752 // at the end instead and will not have been seen yet. In this case,
1753 // just finish the parse now.
1754 if (LazyStreamer && SeenValueSymbolTable) {
1755 NextUnreadBit = Stream.GetCurrentBitNo();
1756 return error_code::success();
1759 case bitc::USELIST_BLOCK_ID:
1760 if (error_code EC = ParseUseLists())
1766 case BitstreamEntry::Record:
1767 // The interesting case.
1773 switch (Stream.readRecord(Entry.ID, Record)) {
1774 default: break; // Default behavior, ignore unknown content.
1775 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1776 if (Record.size() < 1)
1777 return Error(InvalidRecord);
1778 // Only version #0 and #1 are supported so far.
1779 unsigned module_version = Record[0];
1780 switch (module_version) {
1782 return Error(InvalidValue);
1784 UseRelativeIDs = false;
1787 UseRelativeIDs = true;
1792 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1794 if (ConvertToString(Record, 0, S))
1795 return Error(InvalidRecord);
1796 TheModule->setTargetTriple(S);
1799 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1801 if (ConvertToString(Record, 0, S))
1802 return Error(InvalidRecord);
1803 TheModule->setDataLayout(S);
1806 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1808 if (ConvertToString(Record, 0, S))
1809 return Error(InvalidRecord);
1810 TheModule->setModuleInlineAsm(S);
1813 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1814 // FIXME: Remove in 4.0.
1816 if (ConvertToString(Record, 0, S))
1817 return Error(InvalidRecord);
1821 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1823 if (ConvertToString(Record, 0, S))
1824 return Error(InvalidRecord);
1825 SectionTable.push_back(S);
1828 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1830 if (ConvertToString(Record, 0, S))
1831 return Error(InvalidRecord);
1832 GCTable.push_back(S);
1835 // GLOBALVAR: [pointer type, isconst, initid,
1836 // linkage, alignment, section, visibility, threadlocal,
1837 // unnamed_addr, dllstorageclass]
1838 case bitc::MODULE_CODE_GLOBALVAR: {
1839 if (Record.size() < 6)
1840 return Error(InvalidRecord);
1841 Type *Ty = getTypeByID(Record[0]);
1843 return Error(InvalidRecord);
1844 if (!Ty->isPointerTy())
1845 return Error(InvalidTypeForValue);
1846 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1847 Ty = cast<PointerType>(Ty)->getElementType();
1849 bool isConstant = Record[1];
1850 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1851 unsigned Alignment = (1 << Record[4]) >> 1;
1852 std::string Section;
1854 if (Record[5]-1 >= SectionTable.size())
1855 return Error(InvalidID);
1856 Section = SectionTable[Record[5]-1];
1858 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1859 if (Record.size() > 6)
1860 Visibility = GetDecodedVisibility(Record[6]);
1862 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1863 if (Record.size() > 7)
1864 TLM = GetDecodedThreadLocalMode(Record[7]);
1866 bool UnnamedAddr = false;
1867 if (Record.size() > 8)
1868 UnnamedAddr = Record[8];
1870 bool ExternallyInitialized = false;
1871 if (Record.size() > 9)
1872 ExternallyInitialized = Record[9];
1874 GlobalVariable *NewGV =
1875 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1876 TLM, AddressSpace, ExternallyInitialized);
1877 NewGV->setAlignment(Alignment);
1878 if (!Section.empty())
1879 NewGV->setSection(Section);
1880 NewGV->setVisibility(Visibility);
1881 NewGV->setUnnamedAddr(UnnamedAddr);
1883 if (Record.size() > 10)
1884 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1886 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1888 ValueList.push_back(NewGV);
1890 // Remember which value to use for the global initializer.
1891 if (unsigned InitID = Record[2])
1892 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1895 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1896 // alignment, section, visibility, gc, unnamed_addr,
1898 case bitc::MODULE_CODE_FUNCTION: {
1899 if (Record.size() < 8)
1900 return Error(InvalidRecord);
1901 Type *Ty = getTypeByID(Record[0]);
1903 return Error(InvalidRecord);
1904 if (!Ty->isPointerTy())
1905 return Error(InvalidTypeForValue);
1907 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1909 return Error(InvalidTypeForValue);
1911 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1914 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1915 bool isProto = Record[2];
1916 Func->setLinkage(GetDecodedLinkage(Record[3]));
1917 Func->setAttributes(getAttributes(Record[4]));
1919 Func->setAlignment((1 << Record[5]) >> 1);
1921 if (Record[6]-1 >= SectionTable.size())
1922 return Error(InvalidID);
1923 Func->setSection(SectionTable[Record[6]-1]);
1925 Func->setVisibility(GetDecodedVisibility(Record[7]));
1926 if (Record.size() > 8 && Record[8]) {
1927 if (Record[8]-1 > GCTable.size())
1928 return Error(InvalidID);
1929 Func->setGC(GCTable[Record[8]-1].c_str());
1931 bool UnnamedAddr = false;
1932 if (Record.size() > 9)
1933 UnnamedAddr = Record[9];
1934 Func->setUnnamedAddr(UnnamedAddr);
1935 if (Record.size() > 10 && Record[10] != 0)
1936 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1938 if (Record.size() > 11)
1939 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1941 UpgradeDLLImportExportLinkage(Func, Record[3]);
1943 ValueList.push_back(Func);
1945 // If this is a function with a body, remember the prototype we are
1946 // creating now, so that we can match up the body with them later.
1948 FunctionsWithBodies.push_back(Func);
1949 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1953 // ALIAS: [alias type, aliasee val#, linkage]
1954 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
1955 case bitc::MODULE_CODE_ALIAS: {
1956 if (Record.size() < 3)
1957 return Error(InvalidRecord);
1958 Type *Ty = getTypeByID(Record[0]);
1960 return Error(InvalidRecord);
1961 if (!Ty->isPointerTy())
1962 return Error(InvalidTypeForValue);
1964 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1965 "", nullptr, TheModule);
1966 // Old bitcode files didn't have visibility field.
1967 if (Record.size() > 3)
1968 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1969 if (Record.size() > 4)
1970 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
1972 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
1973 ValueList.push_back(NewGA);
1974 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1977 /// MODULE_CODE_PURGEVALS: [numvals]
1978 case bitc::MODULE_CODE_PURGEVALS:
1979 // Trim down the value list to the specified size.
1980 if (Record.size() < 1 || Record[0] > ValueList.size())
1981 return Error(InvalidRecord);
1982 ValueList.shrinkTo(Record[0]);
1989 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
1990 TheModule = nullptr;
1992 if (error_code EC = InitStream())
1995 // Sniff for the signature.
1996 if (Stream.Read(8) != 'B' ||
1997 Stream.Read(8) != 'C' ||
1998 Stream.Read(4) != 0x0 ||
1999 Stream.Read(4) != 0xC ||
2000 Stream.Read(4) != 0xE ||
2001 Stream.Read(4) != 0xD)
2002 return Error(InvalidBitcodeSignature);
2004 // We expect a number of well-defined blocks, though we don't necessarily
2005 // need to understand them all.
2007 if (Stream.AtEndOfStream())
2008 return error_code::success();
2010 BitstreamEntry Entry =
2011 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2013 switch (Entry.Kind) {
2014 case BitstreamEntry::Error:
2015 return Error(MalformedBlock);
2016 case BitstreamEntry::EndBlock:
2017 return error_code::success();
2019 case BitstreamEntry::SubBlock:
2021 case bitc::BLOCKINFO_BLOCK_ID:
2022 if (Stream.ReadBlockInfoBlock())
2023 return Error(MalformedBlock);
2025 case bitc::MODULE_BLOCK_ID:
2026 // Reject multiple MODULE_BLOCK's in a single bitstream.
2028 return Error(InvalidMultipleBlocks);
2030 if (error_code EC = ParseModule(false))
2033 return error_code::success();
2036 if (Stream.SkipBlock())
2037 return Error(InvalidRecord);
2041 case BitstreamEntry::Record:
2042 // There should be no records in the top-level of blocks.
2044 // The ranlib in Xcode 4 will align archive members by appending newlines
2045 // to the end of them. If this file size is a multiple of 4 but not 8, we
2046 // have to read and ignore these final 4 bytes :-(
2047 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2048 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2049 Stream.AtEndOfStream())
2050 return error_code::success();
2052 return Error(InvalidRecord);
2057 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2058 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2059 return Error(InvalidRecord);
2061 SmallVector<uint64_t, 64> Record;
2063 // Read all the records for this module.
2065 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2067 switch (Entry.Kind) {
2068 case BitstreamEntry::SubBlock: // Handled for us already.
2069 case BitstreamEntry::Error:
2070 return Error(MalformedBlock);
2071 case BitstreamEntry::EndBlock:
2072 return error_code::success();
2073 case BitstreamEntry::Record:
2074 // The interesting case.
2079 switch (Stream.readRecord(Entry.ID, Record)) {
2080 default: break; // Default behavior, ignore unknown content.
2081 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2083 if (ConvertToString(Record, 0, S))
2084 return Error(InvalidRecord);
2093 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2094 if (error_code EC = InitStream())
2097 // Sniff for the signature.
2098 if (Stream.Read(8) != 'B' ||
2099 Stream.Read(8) != 'C' ||
2100 Stream.Read(4) != 0x0 ||
2101 Stream.Read(4) != 0xC ||
2102 Stream.Read(4) != 0xE ||
2103 Stream.Read(4) != 0xD)
2104 return Error(InvalidBitcodeSignature);
2106 // We expect a number of well-defined blocks, though we don't necessarily
2107 // need to understand them all.
2109 BitstreamEntry Entry = Stream.advance();
2111 switch (Entry.Kind) {
2112 case BitstreamEntry::Error:
2113 return Error(MalformedBlock);
2114 case BitstreamEntry::EndBlock:
2115 return error_code::success();
2117 case BitstreamEntry::SubBlock:
2118 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2119 return ParseModuleTriple(Triple);
2121 // Ignore other sub-blocks.
2122 if (Stream.SkipBlock())
2123 return Error(MalformedBlock);
2126 case BitstreamEntry::Record:
2127 Stream.skipRecord(Entry.ID);
2133 /// ParseMetadataAttachment - Parse metadata attachments.
2134 error_code BitcodeReader::ParseMetadataAttachment() {
2135 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2136 return Error(InvalidRecord);
2138 SmallVector<uint64_t, 64> Record;
2140 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2142 switch (Entry.Kind) {
2143 case BitstreamEntry::SubBlock: // Handled for us already.
2144 case BitstreamEntry::Error:
2145 return Error(MalformedBlock);
2146 case BitstreamEntry::EndBlock:
2147 return error_code::success();
2148 case BitstreamEntry::Record:
2149 // The interesting case.
2153 // Read a metadata attachment record.
2155 switch (Stream.readRecord(Entry.ID, Record)) {
2156 default: // Default behavior: ignore.
2158 case bitc::METADATA_ATTACHMENT: {
2159 unsigned RecordLength = Record.size();
2160 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2161 return Error(InvalidRecord);
2162 Instruction *Inst = InstructionList[Record[0]];
2163 for (unsigned i = 1; i != RecordLength; i = i+2) {
2164 unsigned Kind = Record[i];
2165 DenseMap<unsigned, unsigned>::iterator I =
2166 MDKindMap.find(Kind);
2167 if (I == MDKindMap.end())
2168 return Error(InvalidID);
2169 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2170 Inst->setMetadata(I->second, cast<MDNode>(Node));
2171 if (I->second == LLVMContext::MD_tbaa)
2172 InstsWithTBAATag.push_back(Inst);
2180 /// ParseFunctionBody - Lazily parse the specified function body block.
2181 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2182 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2183 return Error(InvalidRecord);
2185 InstructionList.clear();
2186 unsigned ModuleValueListSize = ValueList.size();
2187 unsigned ModuleMDValueListSize = MDValueList.size();
2189 // Add all the function arguments to the value table.
2190 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2191 ValueList.push_back(I);
2193 unsigned NextValueNo = ValueList.size();
2194 BasicBlock *CurBB = nullptr;
2195 unsigned CurBBNo = 0;
2199 // Read all the records.
2200 SmallVector<uint64_t, 64> Record;
2202 BitstreamEntry Entry = Stream.advance();
2204 switch (Entry.Kind) {
2205 case BitstreamEntry::Error:
2206 return Error(MalformedBlock);
2207 case BitstreamEntry::EndBlock:
2208 goto OutOfRecordLoop;
2210 case BitstreamEntry::SubBlock:
2212 default: // Skip unknown content.
2213 if (Stream.SkipBlock())
2214 return Error(InvalidRecord);
2216 case bitc::CONSTANTS_BLOCK_ID:
2217 if (error_code EC = ParseConstants())
2219 NextValueNo = ValueList.size();
2221 case bitc::VALUE_SYMTAB_BLOCK_ID:
2222 if (error_code EC = ParseValueSymbolTable())
2225 case bitc::METADATA_ATTACHMENT_ID:
2226 if (error_code EC = ParseMetadataAttachment())
2229 case bitc::METADATA_BLOCK_ID:
2230 if (error_code EC = ParseMetadata())
2236 case BitstreamEntry::Record:
2237 // The interesting case.
2243 Instruction *I = nullptr;
2244 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2246 default: // Default behavior: reject
2247 return Error(InvalidValue);
2248 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2249 if (Record.size() < 1 || Record[0] == 0)
2250 return Error(InvalidRecord);
2251 // Create all the basic blocks for the function.
2252 FunctionBBs.resize(Record[0]);
2253 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2254 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2255 CurBB = FunctionBBs[0];
2258 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2259 // This record indicates that the last instruction is at the same
2260 // location as the previous instruction with a location.
2263 // Get the last instruction emitted.
2264 if (CurBB && !CurBB->empty())
2266 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2267 !FunctionBBs[CurBBNo-1]->empty())
2268 I = &FunctionBBs[CurBBNo-1]->back();
2271 return Error(InvalidRecord);
2272 I->setDebugLoc(LastLoc);
2276 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2277 I = nullptr; // Get the last instruction emitted.
2278 if (CurBB && !CurBB->empty())
2280 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2281 !FunctionBBs[CurBBNo-1]->empty())
2282 I = &FunctionBBs[CurBBNo-1]->back();
2283 if (!I || Record.size() < 4)
2284 return Error(InvalidRecord);
2286 unsigned Line = Record[0], Col = Record[1];
2287 unsigned ScopeID = Record[2], IAID = Record[3];
2289 MDNode *Scope = nullptr, *IA = nullptr;
2290 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2291 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2292 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2293 I->setDebugLoc(LastLoc);
2298 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2301 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2302 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2303 OpNum+1 > Record.size())
2304 return Error(InvalidRecord);
2306 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2308 return Error(InvalidRecord);
2309 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2310 InstructionList.push_back(I);
2311 if (OpNum < Record.size()) {
2312 if (Opc == Instruction::Add ||
2313 Opc == Instruction::Sub ||
2314 Opc == Instruction::Mul ||
2315 Opc == Instruction::Shl) {
2316 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2317 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2318 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2319 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2320 } else if (Opc == Instruction::SDiv ||
2321 Opc == Instruction::UDiv ||
2322 Opc == Instruction::LShr ||
2323 Opc == Instruction::AShr) {
2324 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2325 cast<BinaryOperator>(I)->setIsExact(true);
2326 } else if (isa<FPMathOperator>(I)) {
2328 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2329 FMF.setUnsafeAlgebra();
2330 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2332 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2334 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2335 FMF.setNoSignedZeros();
2336 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2337 FMF.setAllowReciprocal();
2339 I->setFastMathFlags(FMF);
2345 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2348 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2349 OpNum+2 != Record.size())
2350 return Error(InvalidRecord);
2352 Type *ResTy = getTypeByID(Record[OpNum]);
2353 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2354 if (Opc == -1 || !ResTy)
2355 return Error(InvalidRecord);
2356 Instruction *Temp = nullptr;
2357 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2359 InstructionList.push_back(Temp);
2360 CurBB->getInstList().push_back(Temp);
2363 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2365 InstructionList.push_back(I);
2368 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2369 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2372 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2373 return Error(InvalidRecord);
2375 SmallVector<Value*, 16> GEPIdx;
2376 while (OpNum != Record.size()) {
2378 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2379 return Error(InvalidRecord);
2380 GEPIdx.push_back(Op);
2383 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2384 InstructionList.push_back(I);
2385 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2386 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2390 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2391 // EXTRACTVAL: [opty, opval, n x indices]
2394 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2395 return Error(InvalidRecord);
2397 SmallVector<unsigned, 4> EXTRACTVALIdx;
2398 for (unsigned RecSize = Record.size();
2399 OpNum != RecSize; ++OpNum) {
2400 uint64_t Index = Record[OpNum];
2401 if ((unsigned)Index != Index)
2402 return Error(InvalidValue);
2403 EXTRACTVALIdx.push_back((unsigned)Index);
2406 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2407 InstructionList.push_back(I);
2411 case bitc::FUNC_CODE_INST_INSERTVAL: {
2412 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2415 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2416 return Error(InvalidRecord);
2418 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2419 return Error(InvalidRecord);
2421 SmallVector<unsigned, 4> INSERTVALIdx;
2422 for (unsigned RecSize = Record.size();
2423 OpNum != RecSize; ++OpNum) {
2424 uint64_t Index = Record[OpNum];
2425 if ((unsigned)Index != Index)
2426 return Error(InvalidValue);
2427 INSERTVALIdx.push_back((unsigned)Index);
2430 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2431 InstructionList.push_back(I);
2435 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2436 // obsolete form of select
2437 // handles select i1 ... in old bitcode
2439 Value *TrueVal, *FalseVal, *Cond;
2440 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2441 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2442 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2443 return Error(InvalidRecord);
2445 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2446 InstructionList.push_back(I);
2450 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2451 // new form of select
2452 // handles select i1 or select [N x i1]
2454 Value *TrueVal, *FalseVal, *Cond;
2455 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2456 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2457 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2458 return Error(InvalidRecord);
2460 // select condition can be either i1 or [N x i1]
2461 if (VectorType* vector_type =
2462 dyn_cast<VectorType>(Cond->getType())) {
2464 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2465 return Error(InvalidTypeForValue);
2468 if (Cond->getType() != Type::getInt1Ty(Context))
2469 return Error(InvalidTypeForValue);
2472 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2473 InstructionList.push_back(I);
2477 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2480 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2481 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2482 return Error(InvalidRecord);
2483 I = ExtractElementInst::Create(Vec, Idx);
2484 InstructionList.push_back(I);
2488 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2490 Value *Vec, *Elt, *Idx;
2491 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2492 popValue(Record, OpNum, NextValueNo,
2493 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2494 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2495 return Error(InvalidRecord);
2496 I = InsertElementInst::Create(Vec, Elt, Idx);
2497 InstructionList.push_back(I);
2501 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2503 Value *Vec1, *Vec2, *Mask;
2504 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2505 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2506 return Error(InvalidRecord);
2508 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2509 return Error(InvalidRecord);
2510 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2511 InstructionList.push_back(I);
2515 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2516 // Old form of ICmp/FCmp returning bool
2517 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2518 // both legal on vectors but had different behaviour.
2519 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2520 // FCmp/ICmp returning bool or vector of bool
2524 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2525 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2526 OpNum+1 != Record.size())
2527 return Error(InvalidRecord);
2529 if (LHS->getType()->isFPOrFPVectorTy())
2530 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2532 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2533 InstructionList.push_back(I);
2537 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2539 unsigned Size = Record.size();
2541 I = ReturnInst::Create(Context);
2542 InstructionList.push_back(I);
2547 Value *Op = nullptr;
2548 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2549 return Error(InvalidRecord);
2550 if (OpNum != Record.size())
2551 return Error(InvalidRecord);
2553 I = ReturnInst::Create(Context, Op);
2554 InstructionList.push_back(I);
2557 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2558 if (Record.size() != 1 && Record.size() != 3)
2559 return Error(InvalidRecord);
2560 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2562 return Error(InvalidRecord);
2564 if (Record.size() == 1) {
2565 I = BranchInst::Create(TrueDest);
2566 InstructionList.push_back(I);
2569 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2570 Value *Cond = getValue(Record, 2, NextValueNo,
2571 Type::getInt1Ty(Context));
2572 if (!FalseDest || !Cond)
2573 return Error(InvalidRecord);
2574 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2575 InstructionList.push_back(I);
2579 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2581 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2582 // "New" SwitchInst format with case ranges. The changes to write this
2583 // format were reverted but we still recognize bitcode that uses it.
2584 // Hopefully someday we will have support for case ranges and can use
2585 // this format again.
2587 Type *OpTy = getTypeByID(Record[1]);
2588 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2590 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2591 BasicBlock *Default = getBasicBlock(Record[3]);
2592 if (!OpTy || !Cond || !Default)
2593 return Error(InvalidRecord);
2595 unsigned NumCases = Record[4];
2597 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2598 InstructionList.push_back(SI);
2600 unsigned CurIdx = 5;
2601 for (unsigned i = 0; i != NumCases; ++i) {
2602 SmallVector<ConstantInt*, 1> CaseVals;
2603 unsigned NumItems = Record[CurIdx++];
2604 for (unsigned ci = 0; ci != NumItems; ++ci) {
2605 bool isSingleNumber = Record[CurIdx++];
2608 unsigned ActiveWords = 1;
2609 if (ValueBitWidth > 64)
2610 ActiveWords = Record[CurIdx++];
2611 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2613 CurIdx += ActiveWords;
2615 if (!isSingleNumber) {
2617 if (ValueBitWidth > 64)
2618 ActiveWords = Record[CurIdx++];
2620 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2622 CurIdx += ActiveWords;
2624 // FIXME: It is not clear whether values in the range should be
2625 // compared as signed or unsigned values. The partially
2626 // implemented changes that used this format in the past used
2627 // unsigned comparisons.
2628 for ( ; Low.ule(High); ++Low)
2629 CaseVals.push_back(ConstantInt::get(Context, Low));
2631 CaseVals.push_back(ConstantInt::get(Context, Low));
2633 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2634 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2635 cve = CaseVals.end(); cvi != cve; ++cvi)
2636 SI->addCase(*cvi, DestBB);
2642 // Old SwitchInst format without case ranges.
2644 if (Record.size() < 3 || (Record.size() & 1) == 0)
2645 return Error(InvalidRecord);
2646 Type *OpTy = getTypeByID(Record[0]);
2647 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2648 BasicBlock *Default = getBasicBlock(Record[2]);
2649 if (!OpTy || !Cond || !Default)
2650 return Error(InvalidRecord);
2651 unsigned NumCases = (Record.size()-3)/2;
2652 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2653 InstructionList.push_back(SI);
2654 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2655 ConstantInt *CaseVal =
2656 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2657 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2658 if (!CaseVal || !DestBB) {
2660 return Error(InvalidRecord);
2662 SI->addCase(CaseVal, DestBB);
2667 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2668 if (Record.size() < 2)
2669 return Error(InvalidRecord);
2670 Type *OpTy = getTypeByID(Record[0]);
2671 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2672 if (!OpTy || !Address)
2673 return Error(InvalidRecord);
2674 unsigned NumDests = Record.size()-2;
2675 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2676 InstructionList.push_back(IBI);
2677 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2678 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2679 IBI->addDestination(DestBB);
2682 return Error(InvalidRecord);
2689 case bitc::FUNC_CODE_INST_INVOKE: {
2690 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2691 if (Record.size() < 4)
2692 return Error(InvalidRecord);
2693 AttributeSet PAL = getAttributes(Record[0]);
2694 unsigned CCInfo = Record[1];
2695 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2696 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2700 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2701 return Error(InvalidRecord);
2703 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2704 FunctionType *FTy = !CalleeTy ? nullptr :
2705 dyn_cast<FunctionType>(CalleeTy->getElementType());
2707 // Check that the right number of fixed parameters are here.
2708 if (!FTy || !NormalBB || !UnwindBB ||
2709 Record.size() < OpNum+FTy->getNumParams())
2710 return Error(InvalidRecord);
2712 SmallVector<Value*, 16> Ops;
2713 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2714 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2715 FTy->getParamType(i)));
2717 return Error(InvalidRecord);
2720 if (!FTy->isVarArg()) {
2721 if (Record.size() != OpNum)
2722 return Error(InvalidRecord);
2724 // Read type/value pairs for varargs params.
2725 while (OpNum != Record.size()) {
2727 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2728 return Error(InvalidRecord);
2733 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2734 InstructionList.push_back(I);
2735 cast<InvokeInst>(I)->setCallingConv(
2736 static_cast<CallingConv::ID>(CCInfo));
2737 cast<InvokeInst>(I)->setAttributes(PAL);
2740 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2742 Value *Val = nullptr;
2743 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2744 return Error(InvalidRecord);
2745 I = ResumeInst::Create(Val);
2746 InstructionList.push_back(I);
2749 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2750 I = new UnreachableInst(Context);
2751 InstructionList.push_back(I);
2753 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2754 if (Record.size() < 1 || ((Record.size()-1)&1))
2755 return Error(InvalidRecord);
2756 Type *Ty = getTypeByID(Record[0]);
2758 return Error(InvalidRecord);
2760 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2761 InstructionList.push_back(PN);
2763 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2765 // With the new function encoding, it is possible that operands have
2766 // negative IDs (for forward references). Use a signed VBR
2767 // representation to keep the encoding small.
2769 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2771 V = getValue(Record, 1+i, NextValueNo, Ty);
2772 BasicBlock *BB = getBasicBlock(Record[2+i]);
2774 return Error(InvalidRecord);
2775 PN->addIncoming(V, BB);
2781 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2782 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2784 if (Record.size() < 4)
2785 return Error(InvalidRecord);
2786 Type *Ty = getTypeByID(Record[Idx++]);
2788 return Error(InvalidRecord);
2789 Value *PersFn = nullptr;
2790 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2791 return Error(InvalidRecord);
2793 bool IsCleanup = !!Record[Idx++];
2794 unsigned NumClauses = Record[Idx++];
2795 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2796 LP->setCleanup(IsCleanup);
2797 for (unsigned J = 0; J != NumClauses; ++J) {
2798 LandingPadInst::ClauseType CT =
2799 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2802 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2804 return Error(InvalidRecord);
2807 assert((CT != LandingPadInst::Catch ||
2808 !isa<ArrayType>(Val->getType())) &&
2809 "Catch clause has a invalid type!");
2810 assert((CT != LandingPadInst::Filter ||
2811 isa<ArrayType>(Val->getType())) &&
2812 "Filter clause has invalid type!");
2817 InstructionList.push_back(I);
2821 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2822 if (Record.size() != 4)
2823 return Error(InvalidRecord);
2825 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2826 Type *OpTy = getTypeByID(Record[1]);
2827 Value *Size = getFnValueByID(Record[2], OpTy);
2828 unsigned Align = Record[3];
2830 return Error(InvalidRecord);
2831 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2832 InstructionList.push_back(I);
2835 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2838 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2839 OpNum+2 != Record.size())
2840 return Error(InvalidRecord);
2842 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2843 InstructionList.push_back(I);
2846 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2847 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2850 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2851 OpNum+4 != Record.size())
2852 return Error(InvalidRecord);
2855 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2856 if (Ordering == NotAtomic || Ordering == Release ||
2857 Ordering == AcquireRelease)
2858 return Error(InvalidRecord);
2859 if (Ordering != NotAtomic && Record[OpNum] == 0)
2860 return Error(InvalidRecord);
2861 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2863 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2864 Ordering, SynchScope);
2865 InstructionList.push_back(I);
2868 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2871 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2872 popValue(Record, OpNum, NextValueNo,
2873 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2874 OpNum+2 != Record.size())
2875 return Error(InvalidRecord);
2877 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2878 InstructionList.push_back(I);
2881 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2882 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2885 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2886 popValue(Record, OpNum, NextValueNo,
2887 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2888 OpNum+4 != Record.size())
2889 return Error(InvalidRecord);
2891 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2892 if (Ordering == NotAtomic || Ordering == Acquire ||
2893 Ordering == AcquireRelease)
2894 return Error(InvalidRecord);
2895 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2896 if (Ordering != NotAtomic && Record[OpNum] == 0)
2897 return Error(InvalidRecord);
2899 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2900 Ordering, SynchScope);
2901 InstructionList.push_back(I);
2904 case bitc::FUNC_CODE_INST_CMPXCHG: {
2905 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2908 Value *Ptr, *Cmp, *New;
2909 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2910 popValue(Record, OpNum, NextValueNo,
2911 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2912 popValue(Record, OpNum, NextValueNo,
2913 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2914 (OpNum + 3 != Record.size() && OpNum + 4 != Record.size()))
2915 return Error(InvalidRecord);
2916 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2917 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2918 return Error(InvalidRecord);
2919 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2921 AtomicOrdering FailureOrdering;
2922 if (Record.size() < 7)
2924 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2926 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
2928 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
2930 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2931 InstructionList.push_back(I);
2934 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2935 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2938 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2939 popValue(Record, OpNum, NextValueNo,
2940 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2941 OpNum+4 != Record.size())
2942 return Error(InvalidRecord);
2943 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2944 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2945 Operation > AtomicRMWInst::LAST_BINOP)
2946 return Error(InvalidRecord);
2947 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2948 if (Ordering == NotAtomic || Ordering == Unordered)
2949 return Error(InvalidRecord);
2950 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2951 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2952 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2953 InstructionList.push_back(I);
2956 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2957 if (2 != Record.size())
2958 return Error(InvalidRecord);
2959 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2960 if (Ordering == NotAtomic || Ordering == Unordered ||
2961 Ordering == Monotonic)
2962 return Error(InvalidRecord);
2963 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2964 I = new FenceInst(Context, Ordering, SynchScope);
2965 InstructionList.push_back(I);
2968 case bitc::FUNC_CODE_INST_CALL: {
2969 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2970 if (Record.size() < 3)
2971 return Error(InvalidRecord);
2973 AttributeSet PAL = getAttributes(Record[0]);
2974 unsigned CCInfo = Record[1];
2978 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2979 return Error(InvalidRecord);
2981 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2982 FunctionType *FTy = nullptr;
2983 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2984 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2985 return Error(InvalidRecord);
2987 SmallVector<Value*, 16> Args;
2988 // Read the fixed params.
2989 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2990 if (FTy->getParamType(i)->isLabelTy())
2991 Args.push_back(getBasicBlock(Record[OpNum]));
2993 Args.push_back(getValue(Record, OpNum, NextValueNo,
2994 FTy->getParamType(i)));
2996 return Error(InvalidRecord);
2999 // Read type/value pairs for varargs params.
3000 if (!FTy->isVarArg()) {
3001 if (OpNum != Record.size())
3002 return Error(InvalidRecord);
3004 while (OpNum != Record.size()) {
3006 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3007 return Error(InvalidRecord);
3012 I = CallInst::Create(Callee, Args);
3013 InstructionList.push_back(I);
3014 cast<CallInst>(I)->setCallingConv(
3015 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3016 CallInst::TailCallKind TCK = CallInst::TCK_None;
3018 TCK = CallInst::TCK_Tail;
3019 if (CCInfo & (1 << 14))
3020 TCK = CallInst::TCK_MustTail;
3021 cast<CallInst>(I)->setTailCallKind(TCK);
3022 cast<CallInst>(I)->setAttributes(PAL);
3025 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3026 if (Record.size() < 3)
3027 return Error(InvalidRecord);
3028 Type *OpTy = getTypeByID(Record[0]);
3029 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3030 Type *ResTy = getTypeByID(Record[2]);
3031 if (!OpTy || !Op || !ResTy)
3032 return Error(InvalidRecord);
3033 I = new VAArgInst(Op, ResTy);
3034 InstructionList.push_back(I);
3039 // Add instruction to end of current BB. If there is no current BB, reject
3043 return Error(InvalidInstructionWithNoBB);
3045 CurBB->getInstList().push_back(I);
3047 // If this was a terminator instruction, move to the next block.
3048 if (isa<TerminatorInst>(I)) {
3050 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3053 // Non-void values get registered in the value table for future use.
3054 if (I && !I->getType()->isVoidTy())
3055 ValueList.AssignValue(I, NextValueNo++);
3060 // Check the function list for unresolved values.
3061 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3062 if (!A->getParent()) {
3063 // We found at least one unresolved value. Nuke them all to avoid leaks.
3064 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3065 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3066 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3070 return Error(NeverResolvedValueFoundInFunction);
3074 // FIXME: Check for unresolved forward-declared metadata references
3075 // and clean up leaks.
3077 // See if anything took the address of blocks in this function. If so,
3078 // resolve them now.
3079 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3080 BlockAddrFwdRefs.find(F);
3081 if (BAFRI != BlockAddrFwdRefs.end()) {
3082 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3083 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3084 unsigned BlockIdx = RefList[i].first;
3085 if (BlockIdx >= FunctionBBs.size())
3086 return Error(InvalidID);
3088 GlobalVariable *FwdRef = RefList[i].second;
3089 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3090 FwdRef->eraseFromParent();
3093 BlockAddrFwdRefs.erase(BAFRI);
3096 // Trim the value list down to the size it was before we parsed this function.
3097 ValueList.shrinkTo(ModuleValueListSize);
3098 MDValueList.shrinkTo(ModuleMDValueListSize);
3099 std::vector<BasicBlock*>().swap(FunctionBBs);
3100 return error_code::success();
3103 /// Find the function body in the bitcode stream
3104 error_code BitcodeReader::FindFunctionInStream(Function *F,
3105 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3106 while (DeferredFunctionInfoIterator->second == 0) {
3107 if (Stream.AtEndOfStream())
3108 return Error(CouldNotFindFunctionInStream);
3109 // ParseModule will parse the next body in the stream and set its
3110 // position in the DeferredFunctionInfo map.
3111 if (error_code EC = ParseModule(true))
3114 return error_code::success();
3117 //===----------------------------------------------------------------------===//
3118 // GVMaterializer implementation
3119 //===----------------------------------------------------------------------===//
3122 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3123 if (const Function *F = dyn_cast<Function>(GV)) {
3124 return F->isDeclaration() &&
3125 DeferredFunctionInfo.count(const_cast<Function*>(F));
3130 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3131 Function *F = dyn_cast<Function>(GV);
3132 // If it's not a function or is already material, ignore the request.
3133 if (!F || !F->isMaterializable())
3134 return error_code::success();
3136 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3137 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3138 // If its position is recorded as 0, its body is somewhere in the stream
3139 // but we haven't seen it yet.
3140 if (DFII->second == 0 && LazyStreamer)
3141 if (error_code EC = FindFunctionInStream(F, DFII))
3144 // Move the bit stream to the saved position of the deferred function body.
3145 Stream.JumpToBit(DFII->second);
3147 if (error_code EC = ParseFunctionBody(F))
3150 // Upgrade any old intrinsic calls in the function.
3151 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3152 E = UpgradedIntrinsics.end(); I != E; ++I) {
3153 if (I->first != I->second) {
3154 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3156 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3157 UpgradeIntrinsicCall(CI, I->second);
3162 return error_code::success();
3165 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3166 const Function *F = dyn_cast<Function>(GV);
3167 if (!F || F->isDeclaration())
3169 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3172 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3173 Function *F = dyn_cast<Function>(GV);
3174 // If this function isn't dematerializable, this is a noop.
3175 if (!F || !isDematerializable(F))
3178 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3180 // Just forget the function body, we can remat it later.
3185 error_code BitcodeReader::MaterializeModule(Module *M) {
3186 assert(M == TheModule &&
3187 "Can only Materialize the Module this BitcodeReader is attached to.");
3188 // Iterate over the module, deserializing any functions that are still on
3190 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3192 if (F->isMaterializable()) {
3193 if (error_code EC = Materialize(F))
3197 // At this point, if there are any function bodies, the current bit is
3198 // pointing to the END_BLOCK record after them. Now make sure the rest
3199 // of the bits in the module have been read.
3203 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3204 // delete the old functions to clean up. We can't do this unless the entire
3205 // module is materialized because there could always be another function body
3206 // with calls to the old function.
3207 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3208 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3209 if (I->first != I->second) {
3210 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3212 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3213 UpgradeIntrinsicCall(CI, I->second);
3215 if (!I->first->use_empty())
3216 I->first->replaceAllUsesWith(I->second);
3217 I->first->eraseFromParent();
3220 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3222 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3223 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3225 UpgradeDebugInfo(*M);
3226 return error_code::success();
3229 error_code BitcodeReader::InitStream() {
3231 return InitLazyStream();
3232 return InitStreamFromBuffer();
3235 error_code BitcodeReader::InitStreamFromBuffer() {
3236 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3237 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3239 if (Buffer->getBufferSize() & 3) {
3240 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3241 return Error(InvalidBitcodeSignature);
3243 return Error(BitcodeStreamInvalidSize);
3246 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3247 // The magic number is 0x0B17C0DE stored in little endian.
3248 if (isBitcodeWrapper(BufPtr, BufEnd))
3249 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3250 return Error(InvalidBitcodeWrapperHeader);
3252 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3253 Stream.init(*StreamFile);
3255 return error_code::success();
3258 error_code BitcodeReader::InitLazyStream() {
3259 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3261 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3262 StreamFile.reset(new BitstreamReader(Bytes));
3263 Stream.init(*StreamFile);
3265 unsigned char buf[16];
3266 if (Bytes->readBytes(0, 16, buf) == -1)
3267 return Error(BitcodeStreamInvalidSize);
3269 if (!isBitcode(buf, buf + 16))
3270 return Error(InvalidBitcodeSignature);
3272 if (isBitcodeWrapper(buf, buf + 4)) {
3273 const unsigned char *bitcodeStart = buf;
3274 const unsigned char *bitcodeEnd = buf + 16;
3275 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3276 Bytes->dropLeadingBytes(bitcodeStart - buf);
3277 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3279 return error_code::success();
3283 class BitcodeErrorCategoryType : public error_category {
3284 const char *name() const override {
3285 return "llvm.bitcode";
3287 std::string message(int IE) const override {
3288 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3290 case BitcodeReader::BitcodeStreamInvalidSize:
3291 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3292 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3293 return "Conflicting METADATA_KIND records";
3294 case BitcodeReader::CouldNotFindFunctionInStream:
3295 return "Could not find function in stream";
3296 case BitcodeReader::ExpectedConstant:
3297 return "Expected a constant";
3298 case BitcodeReader::InsufficientFunctionProtos:
3299 return "Insufficient function protos";
3300 case BitcodeReader::InvalidBitcodeSignature:
3301 return "Invalid bitcode signature";
3302 case BitcodeReader::InvalidBitcodeWrapperHeader:
3303 return "Invalid bitcode wrapper header";
3304 case BitcodeReader::InvalidConstantReference:
3305 return "Invalid ronstant reference";
3306 case BitcodeReader::InvalidID:
3307 return "Invalid ID";
3308 case BitcodeReader::InvalidInstructionWithNoBB:
3309 return "Invalid instruction with no BB";
3310 case BitcodeReader::InvalidRecord:
3311 return "Invalid record";
3312 case BitcodeReader::InvalidTypeForValue:
3313 return "Invalid type for value";
3314 case BitcodeReader::InvalidTYPETable:
3315 return "Invalid TYPE table";
3316 case BitcodeReader::InvalidType:
3317 return "Invalid type";
3318 case BitcodeReader::MalformedBlock:
3319 return "Malformed block";
3320 case BitcodeReader::MalformedGlobalInitializerSet:
3321 return "Malformed global initializer set";
3322 case BitcodeReader::InvalidMultipleBlocks:
3323 return "Invalid multiple blocks";
3324 case BitcodeReader::NeverResolvedValueFoundInFunction:
3325 return "Never resolved value found in function";
3326 case BitcodeReader::InvalidValue:
3327 return "Invalid value";
3329 llvm_unreachable("Unknown error type!");
3334 const error_category &BitcodeReader::BitcodeErrorCategory() {
3335 static BitcodeErrorCategoryType O;
3339 //===----------------------------------------------------------------------===//
3340 // External interface
3341 //===----------------------------------------------------------------------===//
3343 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3345 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3346 LLVMContext &Context) {
3347 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3348 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3349 M->setMaterializer(R);
3350 if (error_code EC = R->ParseBitcodeInto(M)) {
3351 delete M; // Also deletes R.
3354 // Have the BitcodeReader dtor delete 'Buffer'.
3355 R->setBufferOwned(true);
3357 R->materializeForwardReferencedFunctions();
3363 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3364 DataStreamer *streamer,
3365 LLVMContext &Context,
3366 std::string *ErrMsg) {
3367 Module *M = new Module(name, Context);
3368 BitcodeReader *R = new BitcodeReader(streamer, Context);
3369 M->setMaterializer(R);
3370 if (error_code EC = R->ParseBitcodeInto(M)) {
3372 *ErrMsg = EC.message();
3373 delete M; // Also deletes R.
3376 R->setBufferOwned(false); // no buffer to delete
3380 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3381 LLVMContext &Context) {
3382 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3385 Module *M = ModuleOrErr.get();
3387 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3388 // there was an error.
3389 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3391 // Read in the entire module, and destroy the BitcodeReader.
3392 if (error_code EC = M->materializeAllPermanently()) {
3397 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3398 // written. We must defer until the Module has been fully materialized.
3403 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3404 LLVMContext& Context,
3405 std::string *ErrMsg) {
3406 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3407 // Don't let the BitcodeReader dtor delete 'Buffer'.
3408 R->setBufferOwned(false);
3410 std::string Triple("");
3411 if (error_code EC = R->ParseTriple(Triple))
3413 *ErrMsg = EC.message();