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:
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_JUMP_TABLE:
553 return Attribute::JumpTable;
554 case bitc::ATTR_KIND_MIN_SIZE:
555 return Attribute::MinSize;
556 case bitc::ATTR_KIND_NAKED:
557 return Attribute::Naked;
558 case bitc::ATTR_KIND_NEST:
559 return Attribute::Nest;
560 case bitc::ATTR_KIND_NO_ALIAS:
561 return Attribute::NoAlias;
562 case bitc::ATTR_KIND_NO_BUILTIN:
563 return Attribute::NoBuiltin;
564 case bitc::ATTR_KIND_NO_CAPTURE:
565 return Attribute::NoCapture;
566 case bitc::ATTR_KIND_NO_DUPLICATE:
567 return Attribute::NoDuplicate;
568 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
569 return Attribute::NoImplicitFloat;
570 case bitc::ATTR_KIND_NO_INLINE:
571 return Attribute::NoInline;
572 case bitc::ATTR_KIND_NON_LAZY_BIND:
573 return Attribute::NonLazyBind;
574 case bitc::ATTR_KIND_NON_NULL:
575 return Attribute::NonNull;
576 case bitc::ATTR_KIND_NO_RED_ZONE:
577 return Attribute::NoRedZone;
578 case bitc::ATTR_KIND_NO_RETURN:
579 return Attribute::NoReturn;
580 case bitc::ATTR_KIND_NO_UNWIND:
581 return Attribute::NoUnwind;
582 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
583 return Attribute::OptimizeForSize;
584 case bitc::ATTR_KIND_OPTIMIZE_NONE:
585 return Attribute::OptimizeNone;
586 case bitc::ATTR_KIND_READ_NONE:
587 return Attribute::ReadNone;
588 case bitc::ATTR_KIND_READ_ONLY:
589 return Attribute::ReadOnly;
590 case bitc::ATTR_KIND_RETURNED:
591 return Attribute::Returned;
592 case bitc::ATTR_KIND_RETURNS_TWICE:
593 return Attribute::ReturnsTwice;
594 case bitc::ATTR_KIND_S_EXT:
595 return Attribute::SExt;
596 case bitc::ATTR_KIND_STACK_ALIGNMENT:
597 return Attribute::StackAlignment;
598 case bitc::ATTR_KIND_STACK_PROTECT:
599 return Attribute::StackProtect;
600 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
601 return Attribute::StackProtectReq;
602 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
603 return Attribute::StackProtectStrong;
604 case bitc::ATTR_KIND_STRUCT_RET:
605 return Attribute::StructRet;
606 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
607 return Attribute::SanitizeAddress;
608 case bitc::ATTR_KIND_SANITIZE_THREAD:
609 return Attribute::SanitizeThread;
610 case bitc::ATTR_KIND_SANITIZE_MEMORY:
611 return Attribute::SanitizeMemory;
612 case bitc::ATTR_KIND_UW_TABLE:
613 return Attribute::UWTable;
614 case bitc::ATTR_KIND_Z_EXT:
615 return Attribute::ZExt;
619 error_code BitcodeReader::ParseAttrKind(uint64_t Code,
620 Attribute::AttrKind *Kind) {
621 *Kind = GetAttrFromCode(Code);
622 if (*Kind == Attribute::None)
623 return Error(InvalidValue);
627 error_code BitcodeReader::ParseAttributeGroupBlock() {
628 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
629 return Error(InvalidRecord);
631 if (!MAttributeGroups.empty())
632 return Error(InvalidMultipleBlocks);
634 SmallVector<uint64_t, 64> Record;
636 // Read all the records.
638 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
640 switch (Entry.Kind) {
641 case BitstreamEntry::SubBlock: // Handled for us already.
642 case BitstreamEntry::Error:
643 return Error(MalformedBlock);
644 case BitstreamEntry::EndBlock:
646 case BitstreamEntry::Record:
647 // The interesting case.
653 switch (Stream.readRecord(Entry.ID, Record)) {
654 default: // Default behavior: ignore.
656 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
657 if (Record.size() < 3)
658 return Error(InvalidRecord);
660 uint64_t GrpID = Record[0];
661 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
664 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
665 if (Record[i] == 0) { // Enum attribute
666 Attribute::AttrKind Kind;
667 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
670 B.addAttribute(Kind);
671 } else if (Record[i] == 1) { // Align attribute
672 Attribute::AttrKind Kind;
673 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
675 if (Kind == Attribute::Alignment)
676 B.addAlignmentAttr(Record[++i]);
678 B.addStackAlignmentAttr(Record[++i]);
679 } else { // String attribute
680 assert((Record[i] == 3 || Record[i] == 4) &&
681 "Invalid attribute group entry");
682 bool HasValue = (Record[i++] == 4);
683 SmallString<64> KindStr;
684 SmallString<64> ValStr;
686 while (Record[i] != 0 && i != e)
687 KindStr += Record[i++];
688 assert(Record[i] == 0 && "Kind string not null terminated");
691 // Has a value associated with it.
692 ++i; // Skip the '0' that terminates the "kind" string.
693 while (Record[i] != 0 && i != e)
694 ValStr += Record[i++];
695 assert(Record[i] == 0 && "Value string not null terminated");
698 B.addAttribute(KindStr.str(), ValStr.str());
702 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
709 error_code BitcodeReader::ParseTypeTable() {
710 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
711 return Error(InvalidRecord);
713 return ParseTypeTableBody();
716 error_code BitcodeReader::ParseTypeTableBody() {
717 if (!TypeList.empty())
718 return Error(InvalidMultipleBlocks);
720 SmallVector<uint64_t, 64> Record;
721 unsigned NumRecords = 0;
723 SmallString<64> TypeName;
725 // Read all the records for this type table.
727 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
729 switch (Entry.Kind) {
730 case BitstreamEntry::SubBlock: // Handled for us already.
731 case BitstreamEntry::Error:
732 return Error(MalformedBlock);
733 case BitstreamEntry::EndBlock:
734 if (NumRecords != TypeList.size())
735 return Error(MalformedBlock);
737 case BitstreamEntry::Record:
738 // The interesting case.
744 Type *ResultTy = nullptr;
745 switch (Stream.readRecord(Entry.ID, Record)) {
747 return Error(InvalidValue);
748 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
749 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
750 // type list. This allows us to reserve space.
751 if (Record.size() < 1)
752 return Error(InvalidRecord);
753 TypeList.resize(Record[0]);
755 case bitc::TYPE_CODE_VOID: // VOID
756 ResultTy = Type::getVoidTy(Context);
758 case bitc::TYPE_CODE_HALF: // HALF
759 ResultTy = Type::getHalfTy(Context);
761 case bitc::TYPE_CODE_FLOAT: // FLOAT
762 ResultTy = Type::getFloatTy(Context);
764 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
765 ResultTy = Type::getDoubleTy(Context);
767 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
768 ResultTy = Type::getX86_FP80Ty(Context);
770 case bitc::TYPE_CODE_FP128: // FP128
771 ResultTy = Type::getFP128Ty(Context);
773 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
774 ResultTy = Type::getPPC_FP128Ty(Context);
776 case bitc::TYPE_CODE_LABEL: // LABEL
777 ResultTy = Type::getLabelTy(Context);
779 case bitc::TYPE_CODE_METADATA: // METADATA
780 ResultTy = Type::getMetadataTy(Context);
782 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
783 ResultTy = Type::getX86_MMXTy(Context);
785 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
786 if (Record.size() < 1)
787 return Error(InvalidRecord);
789 ResultTy = IntegerType::get(Context, Record[0]);
791 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
792 // [pointee type, address space]
793 if (Record.size() < 1)
794 return Error(InvalidRecord);
795 unsigned AddressSpace = 0;
796 if (Record.size() == 2)
797 AddressSpace = Record[1];
798 ResultTy = getTypeByID(Record[0]);
800 return Error(InvalidType);
801 ResultTy = PointerType::get(ResultTy, AddressSpace);
804 case bitc::TYPE_CODE_FUNCTION_OLD: {
805 // FIXME: attrid is dead, remove it in LLVM 4.0
806 // FUNCTION: [vararg, attrid, retty, paramty x N]
807 if (Record.size() < 3)
808 return Error(InvalidRecord);
809 SmallVector<Type*, 8> ArgTys;
810 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
811 if (Type *T = getTypeByID(Record[i]))
817 ResultTy = getTypeByID(Record[2]);
818 if (!ResultTy || ArgTys.size() < Record.size()-3)
819 return Error(InvalidType);
821 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
824 case bitc::TYPE_CODE_FUNCTION: {
825 // FUNCTION: [vararg, retty, paramty x N]
826 if (Record.size() < 2)
827 return Error(InvalidRecord);
828 SmallVector<Type*, 8> ArgTys;
829 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
830 if (Type *T = getTypeByID(Record[i]))
836 ResultTy = getTypeByID(Record[1]);
837 if (!ResultTy || ArgTys.size() < Record.size()-2)
838 return Error(InvalidType);
840 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
843 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
844 if (Record.size() < 1)
845 return Error(InvalidRecord);
846 SmallVector<Type*, 8> EltTys;
847 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
848 if (Type *T = getTypeByID(Record[i]))
853 if (EltTys.size() != Record.size()-1)
854 return Error(InvalidType);
855 ResultTy = StructType::get(Context, EltTys, Record[0]);
858 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
859 if (ConvertToString(Record, 0, TypeName))
860 return Error(InvalidRecord);
863 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
864 if (Record.size() < 1)
865 return Error(InvalidRecord);
867 if (NumRecords >= TypeList.size())
868 return Error(InvalidTYPETable);
870 // Check to see if this was forward referenced, if so fill in the temp.
871 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
873 Res->setName(TypeName);
874 TypeList[NumRecords] = nullptr;
875 } else // Otherwise, create a new struct.
876 Res = StructType::create(Context, TypeName);
879 SmallVector<Type*, 8> EltTys;
880 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
881 if (Type *T = getTypeByID(Record[i]))
886 if (EltTys.size() != Record.size()-1)
887 return Error(InvalidRecord);
888 Res->setBody(EltTys, Record[0]);
892 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
893 if (Record.size() != 1)
894 return Error(InvalidRecord);
896 if (NumRecords >= TypeList.size())
897 return Error(InvalidTYPETable);
899 // Check to see if this was forward referenced, if so fill in the temp.
900 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
902 Res->setName(TypeName);
903 TypeList[NumRecords] = nullptr;
904 } else // Otherwise, create a new struct with no body.
905 Res = StructType::create(Context, TypeName);
910 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
911 if (Record.size() < 2)
912 return Error(InvalidRecord);
913 if ((ResultTy = getTypeByID(Record[1])))
914 ResultTy = ArrayType::get(ResultTy, Record[0]);
916 return Error(InvalidType);
918 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
919 if (Record.size() < 2)
920 return Error(InvalidRecord);
921 if ((ResultTy = getTypeByID(Record[1])))
922 ResultTy = VectorType::get(ResultTy, Record[0]);
924 return Error(InvalidType);
928 if (NumRecords >= TypeList.size())
929 return Error(InvalidTYPETable);
930 assert(ResultTy && "Didn't read a type?");
931 assert(!TypeList[NumRecords] && "Already read type?");
932 TypeList[NumRecords++] = ResultTy;
936 error_code BitcodeReader::ParseValueSymbolTable() {
937 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
938 return Error(InvalidRecord);
940 SmallVector<uint64_t, 64> Record;
942 // Read all the records for this value table.
943 SmallString<128> ValueName;
945 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
947 switch (Entry.Kind) {
948 case BitstreamEntry::SubBlock: // Handled for us already.
949 case BitstreamEntry::Error:
950 return Error(MalformedBlock);
951 case BitstreamEntry::EndBlock:
953 case BitstreamEntry::Record:
954 // The interesting case.
960 switch (Stream.readRecord(Entry.ID, Record)) {
961 default: // Default behavior: unknown type.
963 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
964 if (ConvertToString(Record, 1, ValueName))
965 return Error(InvalidRecord);
966 unsigned ValueID = Record[0];
967 if (ValueID >= ValueList.size() || !ValueList[ValueID])
968 return Error(InvalidRecord);
969 Value *V = ValueList[ValueID];
971 V->setName(StringRef(ValueName.data(), ValueName.size()));
975 case bitc::VST_CODE_BBENTRY: {
976 if (ConvertToString(Record, 1, ValueName))
977 return Error(InvalidRecord);
978 BasicBlock *BB = getBasicBlock(Record[0]);
980 return Error(InvalidRecord);
982 BB->setName(StringRef(ValueName.data(), ValueName.size()));
990 error_code BitcodeReader::ParseMetadata() {
991 unsigned NextMDValueNo = MDValueList.size();
993 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
994 return Error(InvalidRecord);
996 SmallVector<uint64_t, 64> Record;
998 // Read all the records.
1000 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1002 switch (Entry.Kind) {
1003 case BitstreamEntry::SubBlock: // Handled for us already.
1004 case BitstreamEntry::Error:
1005 return Error(MalformedBlock);
1006 case BitstreamEntry::EndBlock:
1007 return error_code();
1008 case BitstreamEntry::Record:
1009 // The interesting case.
1013 bool IsFunctionLocal = false;
1016 unsigned Code = Stream.readRecord(Entry.ID, Record);
1018 default: // Default behavior: ignore.
1020 case bitc::METADATA_NAME: {
1021 // Read name of the named metadata.
1022 SmallString<8> Name(Record.begin(), Record.end());
1024 Code = Stream.ReadCode();
1026 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1027 unsigned NextBitCode = Stream.readRecord(Code, Record);
1028 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1030 // Read named metadata elements.
1031 unsigned Size = Record.size();
1032 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1033 for (unsigned i = 0; i != Size; ++i) {
1034 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1036 return Error(InvalidRecord);
1037 NMD->addOperand(MD);
1041 case bitc::METADATA_FN_NODE:
1042 IsFunctionLocal = true;
1044 case bitc::METADATA_NODE: {
1045 if (Record.size() % 2 == 1)
1046 return Error(InvalidRecord);
1048 unsigned Size = Record.size();
1049 SmallVector<Value*, 8> Elts;
1050 for (unsigned i = 0; i != Size; i += 2) {
1051 Type *Ty = getTypeByID(Record[i]);
1053 return Error(InvalidRecord);
1054 if (Ty->isMetadataTy())
1055 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1056 else if (!Ty->isVoidTy())
1057 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1059 Elts.push_back(nullptr);
1061 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1062 IsFunctionLocal = false;
1063 MDValueList.AssignValue(V, NextMDValueNo++);
1066 case bitc::METADATA_STRING: {
1067 SmallString<8> String(Record.begin(), Record.end());
1068 Value *V = MDString::get(Context, String);
1069 MDValueList.AssignValue(V, NextMDValueNo++);
1072 case bitc::METADATA_KIND: {
1073 if (Record.size() < 2)
1074 return Error(InvalidRecord);
1076 unsigned Kind = Record[0];
1077 SmallString<8> Name(Record.begin()+1, Record.end());
1079 unsigned NewKind = TheModule->getMDKindID(Name.str());
1080 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1081 return Error(ConflictingMETADATA_KINDRecords);
1088 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1089 /// the LSB for dense VBR encoding.
1090 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1095 // There is no such thing as -0 with integers. "-0" really means MININT.
1099 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1100 /// values and aliases that we can.
1101 error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1102 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1103 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1104 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1106 GlobalInitWorklist.swap(GlobalInits);
1107 AliasInitWorklist.swap(AliasInits);
1108 FunctionPrefixWorklist.swap(FunctionPrefixes);
1110 while (!GlobalInitWorklist.empty()) {
1111 unsigned ValID = GlobalInitWorklist.back().second;
1112 if (ValID >= ValueList.size()) {
1113 // Not ready to resolve this yet, it requires something later in the file.
1114 GlobalInits.push_back(GlobalInitWorklist.back());
1116 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1117 GlobalInitWorklist.back().first->setInitializer(C);
1119 return Error(ExpectedConstant);
1121 GlobalInitWorklist.pop_back();
1124 while (!AliasInitWorklist.empty()) {
1125 unsigned ValID = AliasInitWorklist.back().second;
1126 if (ValID >= ValueList.size()) {
1127 AliasInits.push_back(AliasInitWorklist.back());
1129 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1130 AliasInitWorklist.back().first->setAliasee(C);
1132 return Error(ExpectedConstant);
1134 AliasInitWorklist.pop_back();
1137 while (!FunctionPrefixWorklist.empty()) {
1138 unsigned ValID = FunctionPrefixWorklist.back().second;
1139 if (ValID >= ValueList.size()) {
1140 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1142 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1143 FunctionPrefixWorklist.back().first->setPrefixData(C);
1145 return Error(ExpectedConstant);
1147 FunctionPrefixWorklist.pop_back();
1150 return error_code();
1153 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1154 SmallVector<uint64_t, 8> Words(Vals.size());
1155 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1156 BitcodeReader::decodeSignRotatedValue);
1158 return APInt(TypeBits, Words);
1161 error_code BitcodeReader::ParseConstants() {
1162 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1163 return Error(InvalidRecord);
1165 SmallVector<uint64_t, 64> Record;
1167 // Read all the records for this value table.
1168 Type *CurTy = Type::getInt32Ty(Context);
1169 unsigned NextCstNo = ValueList.size();
1171 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1173 switch (Entry.Kind) {
1174 case BitstreamEntry::SubBlock: // Handled for us already.
1175 case BitstreamEntry::Error:
1176 return Error(MalformedBlock);
1177 case BitstreamEntry::EndBlock:
1178 if (NextCstNo != ValueList.size())
1179 return Error(InvalidConstantReference);
1181 // Once all the constants have been read, go through and resolve forward
1183 ValueList.ResolveConstantForwardRefs();
1184 return error_code();
1185 case BitstreamEntry::Record:
1186 // The interesting case.
1193 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1195 default: // Default behavior: unknown constant
1196 case bitc::CST_CODE_UNDEF: // UNDEF
1197 V = UndefValue::get(CurTy);
1199 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1201 return Error(InvalidRecord);
1202 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1203 return Error(InvalidRecord);
1204 CurTy = TypeList[Record[0]];
1205 continue; // Skip the ValueList manipulation.
1206 case bitc::CST_CODE_NULL: // NULL
1207 V = Constant::getNullValue(CurTy);
1209 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1210 if (!CurTy->isIntegerTy() || Record.empty())
1211 return Error(InvalidRecord);
1212 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1214 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1215 if (!CurTy->isIntegerTy() || Record.empty())
1216 return Error(InvalidRecord);
1218 APInt VInt = ReadWideAPInt(Record,
1219 cast<IntegerType>(CurTy)->getBitWidth());
1220 V = ConstantInt::get(Context, VInt);
1224 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1226 return Error(InvalidRecord);
1227 if (CurTy->isHalfTy())
1228 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1229 APInt(16, (uint16_t)Record[0])));
1230 else if (CurTy->isFloatTy())
1231 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1232 APInt(32, (uint32_t)Record[0])));
1233 else if (CurTy->isDoubleTy())
1234 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1235 APInt(64, Record[0])));
1236 else if (CurTy->isX86_FP80Ty()) {
1237 // Bits are not stored the same way as a normal i80 APInt, compensate.
1238 uint64_t Rearrange[2];
1239 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1240 Rearrange[1] = Record[0] >> 48;
1241 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1242 APInt(80, Rearrange)));
1243 } else if (CurTy->isFP128Ty())
1244 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1245 APInt(128, Record)));
1246 else if (CurTy->isPPC_FP128Ty())
1247 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1248 APInt(128, Record)));
1250 V = UndefValue::get(CurTy);
1254 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1256 return Error(InvalidRecord);
1258 unsigned Size = Record.size();
1259 SmallVector<Constant*, 16> Elts;
1261 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1262 for (unsigned i = 0; i != Size; ++i)
1263 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1264 STy->getElementType(i)));
1265 V = ConstantStruct::get(STy, Elts);
1266 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1267 Type *EltTy = ATy->getElementType();
1268 for (unsigned i = 0; i != Size; ++i)
1269 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1270 V = ConstantArray::get(ATy, Elts);
1271 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1272 Type *EltTy = VTy->getElementType();
1273 for (unsigned i = 0; i != Size; ++i)
1274 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1275 V = ConstantVector::get(Elts);
1277 V = UndefValue::get(CurTy);
1281 case bitc::CST_CODE_STRING: // STRING: [values]
1282 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1284 return Error(InvalidRecord);
1286 SmallString<16> Elts(Record.begin(), Record.end());
1287 V = ConstantDataArray::getString(Context, Elts,
1288 BitCode == bitc::CST_CODE_CSTRING);
1291 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1293 return Error(InvalidRecord);
1295 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1296 unsigned Size = Record.size();
1298 if (EltTy->isIntegerTy(8)) {
1299 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1300 if (isa<VectorType>(CurTy))
1301 V = ConstantDataVector::get(Context, Elts);
1303 V = ConstantDataArray::get(Context, Elts);
1304 } else if (EltTy->isIntegerTy(16)) {
1305 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1306 if (isa<VectorType>(CurTy))
1307 V = ConstantDataVector::get(Context, Elts);
1309 V = ConstantDataArray::get(Context, Elts);
1310 } else if (EltTy->isIntegerTy(32)) {
1311 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1312 if (isa<VectorType>(CurTy))
1313 V = ConstantDataVector::get(Context, Elts);
1315 V = ConstantDataArray::get(Context, Elts);
1316 } else if (EltTy->isIntegerTy(64)) {
1317 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1318 if (isa<VectorType>(CurTy))
1319 V = ConstantDataVector::get(Context, Elts);
1321 V = ConstantDataArray::get(Context, Elts);
1322 } else if (EltTy->isFloatTy()) {
1323 SmallVector<float, 16> Elts(Size);
1324 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1325 if (isa<VectorType>(CurTy))
1326 V = ConstantDataVector::get(Context, Elts);
1328 V = ConstantDataArray::get(Context, Elts);
1329 } else if (EltTy->isDoubleTy()) {
1330 SmallVector<double, 16> Elts(Size);
1331 std::transform(Record.begin(), Record.end(), Elts.begin(),
1333 if (isa<VectorType>(CurTy))
1334 V = ConstantDataVector::get(Context, Elts);
1336 V = ConstantDataArray::get(Context, Elts);
1338 return Error(InvalidTypeForValue);
1343 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1344 if (Record.size() < 3)
1345 return Error(InvalidRecord);
1346 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1348 V = UndefValue::get(CurTy); // Unknown binop.
1350 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1351 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1353 if (Record.size() >= 4) {
1354 if (Opc == Instruction::Add ||
1355 Opc == Instruction::Sub ||
1356 Opc == Instruction::Mul ||
1357 Opc == Instruction::Shl) {
1358 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1359 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1360 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1361 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1362 } else if (Opc == Instruction::SDiv ||
1363 Opc == Instruction::UDiv ||
1364 Opc == Instruction::LShr ||
1365 Opc == Instruction::AShr) {
1366 if (Record[3] & (1 << bitc::PEO_EXACT))
1367 Flags |= SDivOperator::IsExact;
1370 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1374 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1375 if (Record.size() < 3)
1376 return Error(InvalidRecord);
1377 int Opc = GetDecodedCastOpcode(Record[0]);
1379 V = UndefValue::get(CurTy); // Unknown cast.
1381 Type *OpTy = getTypeByID(Record[1]);
1383 return Error(InvalidRecord);
1384 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1385 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1386 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1390 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1391 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1392 if (Record.size() & 1)
1393 return Error(InvalidRecord);
1394 SmallVector<Constant*, 16> Elts;
1395 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1396 Type *ElTy = getTypeByID(Record[i]);
1398 return Error(InvalidRecord);
1399 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1401 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1402 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1404 bitc::CST_CODE_CE_INBOUNDS_GEP);
1407 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1408 if (Record.size() < 3)
1409 return Error(InvalidRecord);
1411 Type *SelectorTy = Type::getInt1Ty(Context);
1413 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1414 // vector. Otherwise, it must be a single bit.
1415 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1416 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1417 VTy->getNumElements());
1419 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1421 ValueList.getConstantFwdRef(Record[1],CurTy),
1422 ValueList.getConstantFwdRef(Record[2],CurTy));
1425 case bitc::CST_CODE_CE_EXTRACTELT
1426 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1427 if (Record.size() < 3)
1428 return Error(InvalidRecord);
1430 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1432 return Error(InvalidRecord);
1433 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1434 Constant *Op1 = nullptr;
1435 if (Record.size() == 4) {
1436 Type *IdxTy = getTypeByID(Record[2]);
1438 return Error(InvalidRecord);
1439 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1440 } else // TODO: Remove with llvm 4.0
1441 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1443 return Error(InvalidRecord);
1444 V = ConstantExpr::getExtractElement(Op0, Op1);
1447 case bitc::CST_CODE_CE_INSERTELT
1448 : { // CE_INSERTELT: [opval, opval, opty, opval]
1449 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1450 if (Record.size() < 3 || !OpTy)
1451 return Error(InvalidRecord);
1452 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1453 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1454 OpTy->getElementType());
1455 Constant *Op2 = nullptr;
1456 if (Record.size() == 4) {
1457 Type *IdxTy = getTypeByID(Record[2]);
1459 return Error(InvalidRecord);
1460 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1461 } else // TODO: Remove with llvm 4.0
1462 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1464 return Error(InvalidRecord);
1465 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1468 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1469 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1470 if (Record.size() < 3 || !OpTy)
1471 return Error(InvalidRecord);
1472 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1473 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1474 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1475 OpTy->getNumElements());
1476 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1477 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1480 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1481 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1483 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1484 if (Record.size() < 4 || !RTy || !OpTy)
1485 return Error(InvalidRecord);
1486 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1487 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1488 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1489 RTy->getNumElements());
1490 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1491 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1494 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1495 if (Record.size() < 4)
1496 return Error(InvalidRecord);
1497 Type *OpTy = getTypeByID(Record[0]);
1499 return Error(InvalidRecord);
1500 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1501 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1503 if (OpTy->isFPOrFPVectorTy())
1504 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1506 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1509 // This maintains backward compatibility, pre-asm dialect keywords.
1510 // FIXME: Remove with the 4.0 release.
1511 case bitc::CST_CODE_INLINEASM_OLD: {
1512 if (Record.size() < 2)
1513 return Error(InvalidRecord);
1514 std::string AsmStr, ConstrStr;
1515 bool HasSideEffects = Record[0] & 1;
1516 bool IsAlignStack = Record[0] >> 1;
1517 unsigned AsmStrSize = Record[1];
1518 if (2+AsmStrSize >= Record.size())
1519 return Error(InvalidRecord);
1520 unsigned ConstStrSize = Record[2+AsmStrSize];
1521 if (3+AsmStrSize+ConstStrSize > Record.size())
1522 return Error(InvalidRecord);
1524 for (unsigned i = 0; i != AsmStrSize; ++i)
1525 AsmStr += (char)Record[2+i];
1526 for (unsigned i = 0; i != ConstStrSize; ++i)
1527 ConstrStr += (char)Record[3+AsmStrSize+i];
1528 PointerType *PTy = cast<PointerType>(CurTy);
1529 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1530 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1533 // This version adds support for the asm dialect keywords (e.g.,
1535 case bitc::CST_CODE_INLINEASM: {
1536 if (Record.size() < 2)
1537 return Error(InvalidRecord);
1538 std::string AsmStr, ConstrStr;
1539 bool HasSideEffects = Record[0] & 1;
1540 bool IsAlignStack = (Record[0] >> 1) & 1;
1541 unsigned AsmDialect = Record[0] >> 2;
1542 unsigned AsmStrSize = Record[1];
1543 if (2+AsmStrSize >= Record.size())
1544 return Error(InvalidRecord);
1545 unsigned ConstStrSize = Record[2+AsmStrSize];
1546 if (3+AsmStrSize+ConstStrSize > Record.size())
1547 return Error(InvalidRecord);
1549 for (unsigned i = 0; i != AsmStrSize; ++i)
1550 AsmStr += (char)Record[2+i];
1551 for (unsigned i = 0; i != ConstStrSize; ++i)
1552 ConstrStr += (char)Record[3+AsmStrSize+i];
1553 PointerType *PTy = cast<PointerType>(CurTy);
1554 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1555 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1556 InlineAsm::AsmDialect(AsmDialect));
1559 case bitc::CST_CODE_BLOCKADDRESS:{
1560 if (Record.size() < 3)
1561 return Error(InvalidRecord);
1562 Type *FnTy = getTypeByID(Record[0]);
1564 return Error(InvalidRecord);
1566 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1568 return Error(InvalidRecord);
1570 // If the function is already parsed we can insert the block address right
1573 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1574 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1576 return Error(InvalidID);
1579 V = BlockAddress::get(Fn, BBI);
1581 // Otherwise insert a placeholder and remember it so it can be inserted
1582 // when the function is parsed.
1583 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1584 Type::getInt8Ty(Context),
1585 false, GlobalValue::InternalLinkage,
1587 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1594 ValueList.AssignValue(V, NextCstNo);
1599 error_code BitcodeReader::ParseUseLists() {
1600 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1601 return Error(InvalidRecord);
1603 SmallVector<uint64_t, 64> Record;
1605 // Read all the records.
1607 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1609 switch (Entry.Kind) {
1610 case BitstreamEntry::SubBlock: // Handled for us already.
1611 case BitstreamEntry::Error:
1612 return Error(MalformedBlock);
1613 case BitstreamEntry::EndBlock:
1614 return error_code();
1615 case BitstreamEntry::Record:
1616 // The interesting case.
1620 // Read a use list record.
1622 switch (Stream.readRecord(Entry.ID, Record)) {
1623 default: // Default behavior: unknown type.
1625 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1626 unsigned RecordLength = Record.size();
1627 if (RecordLength < 1)
1628 return Error(InvalidRecord);
1629 UseListRecords.push_back(Record);
1636 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1637 /// remember where it is and then skip it. This lets us lazily deserialize the
1639 error_code BitcodeReader::RememberAndSkipFunctionBody() {
1640 // Get the function we are talking about.
1641 if (FunctionsWithBodies.empty())
1642 return Error(InsufficientFunctionProtos);
1644 Function *Fn = FunctionsWithBodies.back();
1645 FunctionsWithBodies.pop_back();
1647 // Save the current stream state.
1648 uint64_t CurBit = Stream.GetCurrentBitNo();
1649 DeferredFunctionInfo[Fn] = CurBit;
1651 // Skip over the function block for now.
1652 if (Stream.SkipBlock())
1653 return Error(InvalidRecord);
1654 return error_code();
1657 error_code BitcodeReader::GlobalCleanup() {
1658 // Patch the initializers for globals and aliases up.
1659 ResolveGlobalAndAliasInits();
1660 if (!GlobalInits.empty() || !AliasInits.empty())
1661 return Error(MalformedGlobalInitializerSet);
1663 // Look for intrinsic functions which need to be upgraded at some point
1664 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1667 if (UpgradeIntrinsicFunction(FI, NewFn))
1668 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1671 // Look for global variables which need to be renamed.
1672 for (Module::global_iterator
1673 GI = TheModule->global_begin(), GE = TheModule->global_end();
1675 GlobalVariable *GV = GI++;
1676 UpgradeGlobalVariable(GV);
1679 // Force deallocation of memory for these vectors to favor the client that
1680 // want lazy deserialization.
1681 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1682 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1683 return error_code();
1686 error_code BitcodeReader::ParseModule(bool Resume) {
1688 Stream.JumpToBit(NextUnreadBit);
1689 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1690 return Error(InvalidRecord);
1692 SmallVector<uint64_t, 64> Record;
1693 std::vector<std::string> SectionTable;
1694 std::vector<std::string> GCTable;
1696 // Read all the records for this module.
1698 BitstreamEntry Entry = Stream.advance();
1700 switch (Entry.Kind) {
1701 case BitstreamEntry::Error:
1702 return Error(MalformedBlock);
1703 case BitstreamEntry::EndBlock:
1704 return GlobalCleanup();
1706 case BitstreamEntry::SubBlock:
1708 default: // Skip unknown content.
1709 if (Stream.SkipBlock())
1710 return Error(InvalidRecord);
1712 case bitc::BLOCKINFO_BLOCK_ID:
1713 if (Stream.ReadBlockInfoBlock())
1714 return Error(MalformedBlock);
1716 case bitc::PARAMATTR_BLOCK_ID:
1717 if (error_code EC = ParseAttributeBlock())
1720 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1721 if (error_code EC = ParseAttributeGroupBlock())
1724 case bitc::TYPE_BLOCK_ID_NEW:
1725 if (error_code EC = ParseTypeTable())
1728 case bitc::VALUE_SYMTAB_BLOCK_ID:
1729 if (error_code EC = ParseValueSymbolTable())
1731 SeenValueSymbolTable = true;
1733 case bitc::CONSTANTS_BLOCK_ID:
1734 if (error_code EC = ParseConstants())
1736 if (error_code EC = ResolveGlobalAndAliasInits())
1739 case bitc::METADATA_BLOCK_ID:
1740 if (error_code EC = ParseMetadata())
1743 case bitc::FUNCTION_BLOCK_ID:
1744 // If this is the first function body we've seen, reverse the
1745 // FunctionsWithBodies list.
1746 if (!SeenFirstFunctionBody) {
1747 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1748 if (error_code EC = GlobalCleanup())
1750 SeenFirstFunctionBody = true;
1753 if (error_code EC = RememberAndSkipFunctionBody())
1755 // For streaming bitcode, suspend parsing when we reach the function
1756 // bodies. Subsequent materialization calls will resume it when
1757 // necessary. For streaming, the function bodies must be at the end of
1758 // the bitcode. If the bitcode file is old, the symbol table will be
1759 // at the end instead and will not have been seen yet. In this case,
1760 // just finish the parse now.
1761 if (LazyStreamer && SeenValueSymbolTable) {
1762 NextUnreadBit = Stream.GetCurrentBitNo();
1763 return error_code();
1766 case bitc::USELIST_BLOCK_ID:
1767 if (error_code EC = ParseUseLists())
1773 case BitstreamEntry::Record:
1774 // The interesting case.
1780 switch (Stream.readRecord(Entry.ID, Record)) {
1781 default: break; // Default behavior, ignore unknown content.
1782 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1783 if (Record.size() < 1)
1784 return Error(InvalidRecord);
1785 // Only version #0 and #1 are supported so far.
1786 unsigned module_version = Record[0];
1787 switch (module_version) {
1789 return Error(InvalidValue);
1791 UseRelativeIDs = false;
1794 UseRelativeIDs = true;
1799 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1801 if (ConvertToString(Record, 0, S))
1802 return Error(InvalidRecord);
1803 TheModule->setTargetTriple(S);
1806 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1808 if (ConvertToString(Record, 0, S))
1809 return Error(InvalidRecord);
1810 TheModule->setDataLayout(S);
1813 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1815 if (ConvertToString(Record, 0, S))
1816 return Error(InvalidRecord);
1817 TheModule->setModuleInlineAsm(S);
1820 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1821 // FIXME: Remove in 4.0.
1823 if (ConvertToString(Record, 0, S))
1824 return Error(InvalidRecord);
1828 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1830 if (ConvertToString(Record, 0, S))
1831 return Error(InvalidRecord);
1832 SectionTable.push_back(S);
1835 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1837 if (ConvertToString(Record, 0, S))
1838 return Error(InvalidRecord);
1839 GCTable.push_back(S);
1842 // GLOBALVAR: [pointer type, isconst, initid,
1843 // linkage, alignment, section, visibility, threadlocal,
1844 // unnamed_addr, dllstorageclass]
1845 case bitc::MODULE_CODE_GLOBALVAR: {
1846 if (Record.size() < 6)
1847 return Error(InvalidRecord);
1848 Type *Ty = getTypeByID(Record[0]);
1850 return Error(InvalidRecord);
1851 if (!Ty->isPointerTy())
1852 return Error(InvalidTypeForValue);
1853 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1854 Ty = cast<PointerType>(Ty)->getElementType();
1856 bool isConstant = Record[1];
1857 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1858 unsigned Alignment = (1 << Record[4]) >> 1;
1859 std::string Section;
1861 if (Record[5]-1 >= SectionTable.size())
1862 return Error(InvalidID);
1863 Section = SectionTable[Record[5]-1];
1865 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1866 // Local linkage must have default visibility.
1867 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1868 // FIXME: Change to an error if non-default in 4.0.
1869 Visibility = GetDecodedVisibility(Record[6]);
1871 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1872 if (Record.size() > 7)
1873 TLM = GetDecodedThreadLocalMode(Record[7]);
1875 bool UnnamedAddr = false;
1876 if (Record.size() > 8)
1877 UnnamedAddr = Record[8];
1879 bool ExternallyInitialized = false;
1880 if (Record.size() > 9)
1881 ExternallyInitialized = Record[9];
1883 GlobalVariable *NewGV =
1884 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1885 TLM, AddressSpace, ExternallyInitialized);
1886 NewGV->setAlignment(Alignment);
1887 if (!Section.empty())
1888 NewGV->setSection(Section);
1889 NewGV->setVisibility(Visibility);
1890 NewGV->setUnnamedAddr(UnnamedAddr);
1892 if (Record.size() > 10)
1893 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1895 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1897 ValueList.push_back(NewGV);
1899 // Remember which value to use for the global initializer.
1900 if (unsigned InitID = Record[2])
1901 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1904 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1905 // alignment, section, visibility, gc, unnamed_addr,
1907 case bitc::MODULE_CODE_FUNCTION: {
1908 if (Record.size() < 8)
1909 return Error(InvalidRecord);
1910 Type *Ty = getTypeByID(Record[0]);
1912 return Error(InvalidRecord);
1913 if (!Ty->isPointerTy())
1914 return Error(InvalidTypeForValue);
1916 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1918 return Error(InvalidTypeForValue);
1920 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1923 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1924 bool isProto = Record[2];
1925 Func->setLinkage(GetDecodedLinkage(Record[3]));
1926 Func->setAttributes(getAttributes(Record[4]));
1928 Func->setAlignment((1 << Record[5]) >> 1);
1930 if (Record[6]-1 >= SectionTable.size())
1931 return Error(InvalidID);
1932 Func->setSection(SectionTable[Record[6]-1]);
1934 // Local linkage must have default visibility.
1935 if (!Func->hasLocalLinkage())
1936 // FIXME: Change to an error if non-default in 4.0.
1937 Func->setVisibility(GetDecodedVisibility(Record[7]));
1938 if (Record.size() > 8 && Record[8]) {
1939 if (Record[8]-1 > GCTable.size())
1940 return Error(InvalidID);
1941 Func->setGC(GCTable[Record[8]-1].c_str());
1943 bool UnnamedAddr = false;
1944 if (Record.size() > 9)
1945 UnnamedAddr = Record[9];
1946 Func->setUnnamedAddr(UnnamedAddr);
1947 if (Record.size() > 10 && Record[10] != 0)
1948 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1950 if (Record.size() > 11)
1951 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1953 UpgradeDLLImportExportLinkage(Func, Record[3]);
1955 ValueList.push_back(Func);
1957 // If this is a function with a body, remember the prototype we are
1958 // creating now, so that we can match up the body with them later.
1960 FunctionsWithBodies.push_back(Func);
1961 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1965 // ALIAS: [alias type, aliasee val#, linkage]
1966 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
1967 case bitc::MODULE_CODE_ALIAS: {
1968 if (Record.size() < 3)
1969 return Error(InvalidRecord);
1970 Type *Ty = getTypeByID(Record[0]);
1972 return Error(InvalidRecord);
1973 auto *PTy = dyn_cast<PointerType>(Ty);
1975 return Error(InvalidTypeForValue);
1978 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1979 GetDecodedLinkage(Record[2]), "", TheModule);
1980 // Old bitcode files didn't have visibility field.
1981 // Local linkage must have default visibility.
1982 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
1983 // FIXME: Change to an error if non-default in 4.0.
1984 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1985 if (Record.size() > 4)
1986 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
1988 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
1989 if (Record.size() > 5)
1990 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
1991 ValueList.push_back(NewGA);
1992 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1995 /// MODULE_CODE_PURGEVALS: [numvals]
1996 case bitc::MODULE_CODE_PURGEVALS:
1997 // Trim down the value list to the specified size.
1998 if (Record.size() < 1 || Record[0] > ValueList.size())
1999 return Error(InvalidRecord);
2000 ValueList.shrinkTo(Record[0]);
2007 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2008 TheModule = nullptr;
2010 if (error_code EC = InitStream())
2013 // Sniff for the signature.
2014 if (Stream.Read(8) != 'B' ||
2015 Stream.Read(8) != 'C' ||
2016 Stream.Read(4) != 0x0 ||
2017 Stream.Read(4) != 0xC ||
2018 Stream.Read(4) != 0xE ||
2019 Stream.Read(4) != 0xD)
2020 return Error(InvalidBitcodeSignature);
2022 // We expect a number of well-defined blocks, though we don't necessarily
2023 // need to understand them all.
2025 if (Stream.AtEndOfStream())
2026 return error_code();
2028 BitstreamEntry Entry =
2029 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2031 switch (Entry.Kind) {
2032 case BitstreamEntry::Error:
2033 return Error(MalformedBlock);
2034 case BitstreamEntry::EndBlock:
2035 return error_code();
2037 case BitstreamEntry::SubBlock:
2039 case bitc::BLOCKINFO_BLOCK_ID:
2040 if (Stream.ReadBlockInfoBlock())
2041 return Error(MalformedBlock);
2043 case bitc::MODULE_BLOCK_ID:
2044 // Reject multiple MODULE_BLOCK's in a single bitstream.
2046 return Error(InvalidMultipleBlocks);
2048 if (error_code EC = ParseModule(false))
2051 return error_code();
2054 if (Stream.SkipBlock())
2055 return Error(InvalidRecord);
2059 case BitstreamEntry::Record:
2060 // There should be no records in the top-level of blocks.
2062 // The ranlib in Xcode 4 will align archive members by appending newlines
2063 // to the end of them. If this file size is a multiple of 4 but not 8, we
2064 // have to read and ignore these final 4 bytes :-(
2065 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2066 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2067 Stream.AtEndOfStream())
2068 return error_code();
2070 return Error(InvalidRecord);
2075 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2076 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2077 return Error(InvalidRecord);
2079 SmallVector<uint64_t, 64> Record;
2081 // Read all the records for this module.
2083 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2085 switch (Entry.Kind) {
2086 case BitstreamEntry::SubBlock: // Handled for us already.
2087 case BitstreamEntry::Error:
2088 return Error(MalformedBlock);
2089 case BitstreamEntry::EndBlock:
2090 return error_code();
2091 case BitstreamEntry::Record:
2092 // The interesting case.
2097 switch (Stream.readRecord(Entry.ID, Record)) {
2098 default: break; // Default behavior, ignore unknown content.
2099 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2101 if (ConvertToString(Record, 0, S))
2102 return Error(InvalidRecord);
2111 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2112 if (error_code EC = InitStream())
2115 // Sniff for the signature.
2116 if (Stream.Read(8) != 'B' ||
2117 Stream.Read(8) != 'C' ||
2118 Stream.Read(4) != 0x0 ||
2119 Stream.Read(4) != 0xC ||
2120 Stream.Read(4) != 0xE ||
2121 Stream.Read(4) != 0xD)
2122 return Error(InvalidBitcodeSignature);
2124 // We expect a number of well-defined blocks, though we don't necessarily
2125 // need to understand them all.
2127 BitstreamEntry Entry = Stream.advance();
2129 switch (Entry.Kind) {
2130 case BitstreamEntry::Error:
2131 return Error(MalformedBlock);
2132 case BitstreamEntry::EndBlock:
2133 return error_code();
2135 case BitstreamEntry::SubBlock:
2136 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2137 return ParseModuleTriple(Triple);
2139 // Ignore other sub-blocks.
2140 if (Stream.SkipBlock())
2141 return Error(MalformedBlock);
2144 case BitstreamEntry::Record:
2145 Stream.skipRecord(Entry.ID);
2151 /// ParseMetadataAttachment - Parse metadata attachments.
2152 error_code BitcodeReader::ParseMetadataAttachment() {
2153 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2154 return Error(InvalidRecord);
2156 SmallVector<uint64_t, 64> Record;
2158 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2160 switch (Entry.Kind) {
2161 case BitstreamEntry::SubBlock: // Handled for us already.
2162 case BitstreamEntry::Error:
2163 return Error(MalformedBlock);
2164 case BitstreamEntry::EndBlock:
2165 return error_code();
2166 case BitstreamEntry::Record:
2167 // The interesting case.
2171 // Read a metadata attachment record.
2173 switch (Stream.readRecord(Entry.ID, Record)) {
2174 default: // Default behavior: ignore.
2176 case bitc::METADATA_ATTACHMENT: {
2177 unsigned RecordLength = Record.size();
2178 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2179 return Error(InvalidRecord);
2180 Instruction *Inst = InstructionList[Record[0]];
2181 for (unsigned i = 1; i != RecordLength; i = i+2) {
2182 unsigned Kind = Record[i];
2183 DenseMap<unsigned, unsigned>::iterator I =
2184 MDKindMap.find(Kind);
2185 if (I == MDKindMap.end())
2186 return Error(InvalidID);
2187 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2188 Inst->setMetadata(I->second, cast<MDNode>(Node));
2189 if (I->second == LLVMContext::MD_tbaa)
2190 InstsWithTBAATag.push_back(Inst);
2198 /// ParseFunctionBody - Lazily parse the specified function body block.
2199 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2200 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2201 return Error(InvalidRecord);
2203 InstructionList.clear();
2204 unsigned ModuleValueListSize = ValueList.size();
2205 unsigned ModuleMDValueListSize = MDValueList.size();
2207 // Add all the function arguments to the value table.
2208 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2209 ValueList.push_back(I);
2211 unsigned NextValueNo = ValueList.size();
2212 BasicBlock *CurBB = nullptr;
2213 unsigned CurBBNo = 0;
2217 // Read all the records.
2218 SmallVector<uint64_t, 64> Record;
2220 BitstreamEntry Entry = Stream.advance();
2222 switch (Entry.Kind) {
2223 case BitstreamEntry::Error:
2224 return Error(MalformedBlock);
2225 case BitstreamEntry::EndBlock:
2226 goto OutOfRecordLoop;
2228 case BitstreamEntry::SubBlock:
2230 default: // Skip unknown content.
2231 if (Stream.SkipBlock())
2232 return Error(InvalidRecord);
2234 case bitc::CONSTANTS_BLOCK_ID:
2235 if (error_code EC = ParseConstants())
2237 NextValueNo = ValueList.size();
2239 case bitc::VALUE_SYMTAB_BLOCK_ID:
2240 if (error_code EC = ParseValueSymbolTable())
2243 case bitc::METADATA_ATTACHMENT_ID:
2244 if (error_code EC = ParseMetadataAttachment())
2247 case bitc::METADATA_BLOCK_ID:
2248 if (error_code EC = ParseMetadata())
2254 case BitstreamEntry::Record:
2255 // The interesting case.
2261 Instruction *I = nullptr;
2262 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2264 default: // Default behavior: reject
2265 return Error(InvalidValue);
2266 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2267 if (Record.size() < 1 || Record[0] == 0)
2268 return Error(InvalidRecord);
2269 // Create all the basic blocks for the function.
2270 FunctionBBs.resize(Record[0]);
2271 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2272 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2273 CurBB = FunctionBBs[0];
2276 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2277 // This record indicates that the last instruction is at the same
2278 // location as the previous instruction with a location.
2281 // Get the last instruction emitted.
2282 if (CurBB && !CurBB->empty())
2284 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2285 !FunctionBBs[CurBBNo-1]->empty())
2286 I = &FunctionBBs[CurBBNo-1]->back();
2289 return Error(InvalidRecord);
2290 I->setDebugLoc(LastLoc);
2294 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2295 I = nullptr; // Get the last instruction emitted.
2296 if (CurBB && !CurBB->empty())
2298 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2299 !FunctionBBs[CurBBNo-1]->empty())
2300 I = &FunctionBBs[CurBBNo-1]->back();
2301 if (!I || Record.size() < 4)
2302 return Error(InvalidRecord);
2304 unsigned Line = Record[0], Col = Record[1];
2305 unsigned ScopeID = Record[2], IAID = Record[3];
2307 MDNode *Scope = nullptr, *IA = nullptr;
2308 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2309 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2310 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2311 I->setDebugLoc(LastLoc);
2316 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2319 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2320 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2321 OpNum+1 > Record.size())
2322 return Error(InvalidRecord);
2324 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2326 return Error(InvalidRecord);
2327 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2328 InstructionList.push_back(I);
2329 if (OpNum < Record.size()) {
2330 if (Opc == Instruction::Add ||
2331 Opc == Instruction::Sub ||
2332 Opc == Instruction::Mul ||
2333 Opc == Instruction::Shl) {
2334 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2335 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2336 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2337 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2338 } else if (Opc == Instruction::SDiv ||
2339 Opc == Instruction::UDiv ||
2340 Opc == Instruction::LShr ||
2341 Opc == Instruction::AShr) {
2342 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2343 cast<BinaryOperator>(I)->setIsExact(true);
2344 } else if (isa<FPMathOperator>(I)) {
2346 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2347 FMF.setUnsafeAlgebra();
2348 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2350 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2352 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2353 FMF.setNoSignedZeros();
2354 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2355 FMF.setAllowReciprocal();
2357 I->setFastMathFlags(FMF);
2363 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2366 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2367 OpNum+2 != Record.size())
2368 return Error(InvalidRecord);
2370 Type *ResTy = getTypeByID(Record[OpNum]);
2371 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2372 if (Opc == -1 || !ResTy)
2373 return Error(InvalidRecord);
2374 Instruction *Temp = nullptr;
2375 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2377 InstructionList.push_back(Temp);
2378 CurBB->getInstList().push_back(Temp);
2381 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2383 InstructionList.push_back(I);
2386 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2387 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2390 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2391 return Error(InvalidRecord);
2393 SmallVector<Value*, 16> GEPIdx;
2394 while (OpNum != Record.size()) {
2396 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2397 return Error(InvalidRecord);
2398 GEPIdx.push_back(Op);
2401 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2402 InstructionList.push_back(I);
2403 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2404 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2408 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2409 // EXTRACTVAL: [opty, opval, n x indices]
2412 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2413 return Error(InvalidRecord);
2415 SmallVector<unsigned, 4> EXTRACTVALIdx;
2416 for (unsigned RecSize = Record.size();
2417 OpNum != RecSize; ++OpNum) {
2418 uint64_t Index = Record[OpNum];
2419 if ((unsigned)Index != Index)
2420 return Error(InvalidValue);
2421 EXTRACTVALIdx.push_back((unsigned)Index);
2424 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2425 InstructionList.push_back(I);
2429 case bitc::FUNC_CODE_INST_INSERTVAL: {
2430 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2433 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2434 return Error(InvalidRecord);
2436 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2437 return Error(InvalidRecord);
2439 SmallVector<unsigned, 4> INSERTVALIdx;
2440 for (unsigned RecSize = Record.size();
2441 OpNum != RecSize; ++OpNum) {
2442 uint64_t Index = Record[OpNum];
2443 if ((unsigned)Index != Index)
2444 return Error(InvalidValue);
2445 INSERTVALIdx.push_back((unsigned)Index);
2448 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2449 InstructionList.push_back(I);
2453 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2454 // obsolete form of select
2455 // handles select i1 ... in old bitcode
2457 Value *TrueVal, *FalseVal, *Cond;
2458 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2459 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2460 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2461 return Error(InvalidRecord);
2463 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2464 InstructionList.push_back(I);
2468 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2469 // new form of select
2470 // handles select i1 or select [N x i1]
2472 Value *TrueVal, *FalseVal, *Cond;
2473 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2474 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2475 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2476 return Error(InvalidRecord);
2478 // select condition can be either i1 or [N x i1]
2479 if (VectorType* vector_type =
2480 dyn_cast<VectorType>(Cond->getType())) {
2482 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2483 return Error(InvalidTypeForValue);
2486 if (Cond->getType() != Type::getInt1Ty(Context))
2487 return Error(InvalidTypeForValue);
2490 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2491 InstructionList.push_back(I);
2495 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2498 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2499 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2500 return Error(InvalidRecord);
2501 I = ExtractElementInst::Create(Vec, Idx);
2502 InstructionList.push_back(I);
2506 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2508 Value *Vec, *Elt, *Idx;
2509 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2510 popValue(Record, OpNum, NextValueNo,
2511 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2512 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2513 return Error(InvalidRecord);
2514 I = InsertElementInst::Create(Vec, Elt, Idx);
2515 InstructionList.push_back(I);
2519 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2521 Value *Vec1, *Vec2, *Mask;
2522 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2523 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2524 return Error(InvalidRecord);
2526 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2527 return Error(InvalidRecord);
2528 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2529 InstructionList.push_back(I);
2533 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2534 // Old form of ICmp/FCmp returning bool
2535 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2536 // both legal on vectors but had different behaviour.
2537 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2538 // FCmp/ICmp returning bool or vector of bool
2542 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2543 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2544 OpNum+1 != Record.size())
2545 return Error(InvalidRecord);
2547 if (LHS->getType()->isFPOrFPVectorTy())
2548 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2550 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2551 InstructionList.push_back(I);
2555 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2557 unsigned Size = Record.size();
2559 I = ReturnInst::Create(Context);
2560 InstructionList.push_back(I);
2565 Value *Op = nullptr;
2566 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2567 return Error(InvalidRecord);
2568 if (OpNum != Record.size())
2569 return Error(InvalidRecord);
2571 I = ReturnInst::Create(Context, Op);
2572 InstructionList.push_back(I);
2575 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2576 if (Record.size() != 1 && Record.size() != 3)
2577 return Error(InvalidRecord);
2578 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2580 return Error(InvalidRecord);
2582 if (Record.size() == 1) {
2583 I = BranchInst::Create(TrueDest);
2584 InstructionList.push_back(I);
2587 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2588 Value *Cond = getValue(Record, 2, NextValueNo,
2589 Type::getInt1Ty(Context));
2590 if (!FalseDest || !Cond)
2591 return Error(InvalidRecord);
2592 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2593 InstructionList.push_back(I);
2597 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2599 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2600 // "New" SwitchInst format with case ranges. The changes to write this
2601 // format were reverted but we still recognize bitcode that uses it.
2602 // Hopefully someday we will have support for case ranges and can use
2603 // this format again.
2605 Type *OpTy = getTypeByID(Record[1]);
2606 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2608 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2609 BasicBlock *Default = getBasicBlock(Record[3]);
2610 if (!OpTy || !Cond || !Default)
2611 return Error(InvalidRecord);
2613 unsigned NumCases = Record[4];
2615 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2616 InstructionList.push_back(SI);
2618 unsigned CurIdx = 5;
2619 for (unsigned i = 0; i != NumCases; ++i) {
2620 SmallVector<ConstantInt*, 1> CaseVals;
2621 unsigned NumItems = Record[CurIdx++];
2622 for (unsigned ci = 0; ci != NumItems; ++ci) {
2623 bool isSingleNumber = Record[CurIdx++];
2626 unsigned ActiveWords = 1;
2627 if (ValueBitWidth > 64)
2628 ActiveWords = Record[CurIdx++];
2629 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2631 CurIdx += ActiveWords;
2633 if (!isSingleNumber) {
2635 if (ValueBitWidth > 64)
2636 ActiveWords = Record[CurIdx++];
2638 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2640 CurIdx += ActiveWords;
2642 // FIXME: It is not clear whether values in the range should be
2643 // compared as signed or unsigned values. The partially
2644 // implemented changes that used this format in the past used
2645 // unsigned comparisons.
2646 for ( ; Low.ule(High); ++Low)
2647 CaseVals.push_back(ConstantInt::get(Context, Low));
2649 CaseVals.push_back(ConstantInt::get(Context, Low));
2651 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2652 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2653 cve = CaseVals.end(); cvi != cve; ++cvi)
2654 SI->addCase(*cvi, DestBB);
2660 // Old SwitchInst format without case ranges.
2662 if (Record.size() < 3 || (Record.size() & 1) == 0)
2663 return Error(InvalidRecord);
2664 Type *OpTy = getTypeByID(Record[0]);
2665 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2666 BasicBlock *Default = getBasicBlock(Record[2]);
2667 if (!OpTy || !Cond || !Default)
2668 return Error(InvalidRecord);
2669 unsigned NumCases = (Record.size()-3)/2;
2670 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2671 InstructionList.push_back(SI);
2672 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2673 ConstantInt *CaseVal =
2674 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2675 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2676 if (!CaseVal || !DestBB) {
2678 return Error(InvalidRecord);
2680 SI->addCase(CaseVal, DestBB);
2685 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2686 if (Record.size() < 2)
2687 return Error(InvalidRecord);
2688 Type *OpTy = getTypeByID(Record[0]);
2689 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2690 if (!OpTy || !Address)
2691 return Error(InvalidRecord);
2692 unsigned NumDests = Record.size()-2;
2693 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2694 InstructionList.push_back(IBI);
2695 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2696 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2697 IBI->addDestination(DestBB);
2700 return Error(InvalidRecord);
2707 case bitc::FUNC_CODE_INST_INVOKE: {
2708 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2709 if (Record.size() < 4)
2710 return Error(InvalidRecord);
2711 AttributeSet PAL = getAttributes(Record[0]);
2712 unsigned CCInfo = Record[1];
2713 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2714 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2718 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2719 return Error(InvalidRecord);
2721 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2722 FunctionType *FTy = !CalleeTy ? nullptr :
2723 dyn_cast<FunctionType>(CalleeTy->getElementType());
2725 // Check that the right number of fixed parameters are here.
2726 if (!FTy || !NormalBB || !UnwindBB ||
2727 Record.size() < OpNum+FTy->getNumParams())
2728 return Error(InvalidRecord);
2730 SmallVector<Value*, 16> Ops;
2731 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2732 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2733 FTy->getParamType(i)));
2735 return Error(InvalidRecord);
2738 if (!FTy->isVarArg()) {
2739 if (Record.size() != OpNum)
2740 return Error(InvalidRecord);
2742 // Read type/value pairs for varargs params.
2743 while (OpNum != Record.size()) {
2745 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2746 return Error(InvalidRecord);
2751 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2752 InstructionList.push_back(I);
2753 cast<InvokeInst>(I)->setCallingConv(
2754 static_cast<CallingConv::ID>(CCInfo));
2755 cast<InvokeInst>(I)->setAttributes(PAL);
2758 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2760 Value *Val = nullptr;
2761 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2762 return Error(InvalidRecord);
2763 I = ResumeInst::Create(Val);
2764 InstructionList.push_back(I);
2767 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2768 I = new UnreachableInst(Context);
2769 InstructionList.push_back(I);
2771 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2772 if (Record.size() < 1 || ((Record.size()-1)&1))
2773 return Error(InvalidRecord);
2774 Type *Ty = getTypeByID(Record[0]);
2776 return Error(InvalidRecord);
2778 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2779 InstructionList.push_back(PN);
2781 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2783 // With the new function encoding, it is possible that operands have
2784 // negative IDs (for forward references). Use a signed VBR
2785 // representation to keep the encoding small.
2787 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2789 V = getValue(Record, 1+i, NextValueNo, Ty);
2790 BasicBlock *BB = getBasicBlock(Record[2+i]);
2792 return Error(InvalidRecord);
2793 PN->addIncoming(V, BB);
2799 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2800 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2802 if (Record.size() < 4)
2803 return Error(InvalidRecord);
2804 Type *Ty = getTypeByID(Record[Idx++]);
2806 return Error(InvalidRecord);
2807 Value *PersFn = nullptr;
2808 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2809 return Error(InvalidRecord);
2811 bool IsCleanup = !!Record[Idx++];
2812 unsigned NumClauses = Record[Idx++];
2813 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2814 LP->setCleanup(IsCleanup);
2815 for (unsigned J = 0; J != NumClauses; ++J) {
2816 LandingPadInst::ClauseType CT =
2817 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2820 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2822 return Error(InvalidRecord);
2825 assert((CT != LandingPadInst::Catch ||
2826 !isa<ArrayType>(Val->getType())) &&
2827 "Catch clause has a invalid type!");
2828 assert((CT != LandingPadInst::Filter ||
2829 isa<ArrayType>(Val->getType())) &&
2830 "Filter clause has invalid type!");
2831 LP->addClause(cast<Constant>(Val));
2835 InstructionList.push_back(I);
2839 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2840 if (Record.size() != 4)
2841 return Error(InvalidRecord);
2843 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2844 Type *OpTy = getTypeByID(Record[1]);
2845 Value *Size = getFnValueByID(Record[2], OpTy);
2846 unsigned Align = Record[3];
2848 return Error(InvalidRecord);
2849 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2850 InstructionList.push_back(I);
2853 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2856 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2857 OpNum+2 != Record.size())
2858 return Error(InvalidRecord);
2860 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2861 InstructionList.push_back(I);
2864 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2865 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2868 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2869 OpNum+4 != Record.size())
2870 return Error(InvalidRecord);
2873 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2874 if (Ordering == NotAtomic || Ordering == Release ||
2875 Ordering == AcquireRelease)
2876 return Error(InvalidRecord);
2877 if (Ordering != NotAtomic && Record[OpNum] == 0)
2878 return Error(InvalidRecord);
2879 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2881 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2882 Ordering, SynchScope);
2883 InstructionList.push_back(I);
2886 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2889 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2890 popValue(Record, OpNum, NextValueNo,
2891 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2892 OpNum+2 != Record.size())
2893 return Error(InvalidRecord);
2895 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2896 InstructionList.push_back(I);
2899 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2900 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2903 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2904 popValue(Record, OpNum, NextValueNo,
2905 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2906 OpNum+4 != Record.size())
2907 return Error(InvalidRecord);
2909 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2910 if (Ordering == NotAtomic || Ordering == Acquire ||
2911 Ordering == AcquireRelease)
2912 return Error(InvalidRecord);
2913 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2914 if (Ordering != NotAtomic && Record[OpNum] == 0)
2915 return Error(InvalidRecord);
2917 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2918 Ordering, SynchScope);
2919 InstructionList.push_back(I);
2922 case bitc::FUNC_CODE_INST_CMPXCHG: {
2923 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2926 Value *Ptr, *Cmp, *New;
2927 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2928 popValue(Record, OpNum, NextValueNo,
2929 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2930 popValue(Record, OpNum, NextValueNo,
2931 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2932 (OpNum + 3 != Record.size() && OpNum + 4 != Record.size()))
2933 return Error(InvalidRecord);
2934 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2935 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2936 return Error(InvalidRecord);
2937 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2939 AtomicOrdering FailureOrdering;
2940 if (Record.size() < 7)
2942 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2944 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
2946 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
2948 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2949 InstructionList.push_back(I);
2952 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2953 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2956 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2957 popValue(Record, OpNum, NextValueNo,
2958 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2959 OpNum+4 != Record.size())
2960 return Error(InvalidRecord);
2961 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2962 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2963 Operation > AtomicRMWInst::LAST_BINOP)
2964 return Error(InvalidRecord);
2965 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2966 if (Ordering == NotAtomic || Ordering == Unordered)
2967 return Error(InvalidRecord);
2968 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2969 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2970 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2971 InstructionList.push_back(I);
2974 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2975 if (2 != Record.size())
2976 return Error(InvalidRecord);
2977 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2978 if (Ordering == NotAtomic || Ordering == Unordered ||
2979 Ordering == Monotonic)
2980 return Error(InvalidRecord);
2981 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2982 I = new FenceInst(Context, Ordering, SynchScope);
2983 InstructionList.push_back(I);
2986 case bitc::FUNC_CODE_INST_CALL: {
2987 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2988 if (Record.size() < 3)
2989 return Error(InvalidRecord);
2991 AttributeSet PAL = getAttributes(Record[0]);
2992 unsigned CCInfo = Record[1];
2996 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2997 return Error(InvalidRecord);
2999 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3000 FunctionType *FTy = nullptr;
3001 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3002 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3003 return Error(InvalidRecord);
3005 SmallVector<Value*, 16> Args;
3006 // Read the fixed params.
3007 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3008 if (FTy->getParamType(i)->isLabelTy())
3009 Args.push_back(getBasicBlock(Record[OpNum]));
3011 Args.push_back(getValue(Record, OpNum, NextValueNo,
3012 FTy->getParamType(i)));
3014 return Error(InvalidRecord);
3017 // Read type/value pairs for varargs params.
3018 if (!FTy->isVarArg()) {
3019 if (OpNum != Record.size())
3020 return Error(InvalidRecord);
3022 while (OpNum != Record.size()) {
3024 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3025 return Error(InvalidRecord);
3030 I = CallInst::Create(Callee, Args);
3031 InstructionList.push_back(I);
3032 cast<CallInst>(I)->setCallingConv(
3033 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3034 CallInst::TailCallKind TCK = CallInst::TCK_None;
3036 TCK = CallInst::TCK_Tail;
3037 if (CCInfo & (1 << 14))
3038 TCK = CallInst::TCK_MustTail;
3039 cast<CallInst>(I)->setTailCallKind(TCK);
3040 cast<CallInst>(I)->setAttributes(PAL);
3043 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3044 if (Record.size() < 3)
3045 return Error(InvalidRecord);
3046 Type *OpTy = getTypeByID(Record[0]);
3047 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3048 Type *ResTy = getTypeByID(Record[2]);
3049 if (!OpTy || !Op || !ResTy)
3050 return Error(InvalidRecord);
3051 I = new VAArgInst(Op, ResTy);
3052 InstructionList.push_back(I);
3057 // Add instruction to end of current BB. If there is no current BB, reject
3061 return Error(InvalidInstructionWithNoBB);
3063 CurBB->getInstList().push_back(I);
3065 // If this was a terminator instruction, move to the next block.
3066 if (isa<TerminatorInst>(I)) {
3068 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3071 // Non-void values get registered in the value table for future use.
3072 if (I && !I->getType()->isVoidTy())
3073 ValueList.AssignValue(I, NextValueNo++);
3078 // Check the function list for unresolved values.
3079 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3080 if (!A->getParent()) {
3081 // We found at least one unresolved value. Nuke them all to avoid leaks.
3082 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3083 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3084 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3088 return Error(NeverResolvedValueFoundInFunction);
3092 // FIXME: Check for unresolved forward-declared metadata references
3093 // and clean up leaks.
3095 // See if anything took the address of blocks in this function. If so,
3096 // resolve them now.
3097 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3098 BlockAddrFwdRefs.find(F);
3099 if (BAFRI != BlockAddrFwdRefs.end()) {
3100 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3101 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3102 unsigned BlockIdx = RefList[i].first;
3103 if (BlockIdx >= FunctionBBs.size())
3104 return Error(InvalidID);
3106 GlobalVariable *FwdRef = RefList[i].second;
3107 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3108 FwdRef->eraseFromParent();
3111 BlockAddrFwdRefs.erase(BAFRI);
3114 // Trim the value list down to the size it was before we parsed this function.
3115 ValueList.shrinkTo(ModuleValueListSize);
3116 MDValueList.shrinkTo(ModuleMDValueListSize);
3117 std::vector<BasicBlock*>().swap(FunctionBBs);
3118 return error_code();
3121 /// Find the function body in the bitcode stream
3122 error_code BitcodeReader::FindFunctionInStream(Function *F,
3123 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3124 while (DeferredFunctionInfoIterator->second == 0) {
3125 if (Stream.AtEndOfStream())
3126 return Error(CouldNotFindFunctionInStream);
3127 // ParseModule will parse the next body in the stream and set its
3128 // position in the DeferredFunctionInfo map.
3129 if (error_code EC = ParseModule(true))
3132 return error_code();
3135 //===----------------------------------------------------------------------===//
3136 // GVMaterializer implementation
3137 //===----------------------------------------------------------------------===//
3140 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3141 if (const Function *F = dyn_cast<Function>(GV)) {
3142 return F->isDeclaration() &&
3143 DeferredFunctionInfo.count(const_cast<Function*>(F));
3148 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3149 Function *F = dyn_cast<Function>(GV);
3150 // If it's not a function or is already material, ignore the request.
3151 if (!F || !F->isMaterializable())
3152 return error_code();
3154 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3155 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3156 // If its position is recorded as 0, its body is somewhere in the stream
3157 // but we haven't seen it yet.
3158 if (DFII->second == 0 && LazyStreamer)
3159 if (error_code EC = FindFunctionInStream(F, DFII))
3162 // Move the bit stream to the saved position of the deferred function body.
3163 Stream.JumpToBit(DFII->second);
3165 if (error_code EC = ParseFunctionBody(F))
3168 // Upgrade any old intrinsic calls in the function.
3169 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3170 E = UpgradedIntrinsics.end(); I != E; ++I) {
3171 if (I->first != I->second) {
3172 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3174 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3175 UpgradeIntrinsicCall(CI, I->second);
3180 return error_code();
3183 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3184 const Function *F = dyn_cast<Function>(GV);
3185 if (!F || F->isDeclaration())
3187 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3190 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3191 Function *F = dyn_cast<Function>(GV);
3192 // If this function isn't dematerializable, this is a noop.
3193 if (!F || !isDematerializable(F))
3196 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3198 // Just forget the function body, we can remat it later.
3203 error_code BitcodeReader::MaterializeModule(Module *M) {
3204 assert(M == TheModule &&
3205 "Can only Materialize the Module this BitcodeReader is attached to.");
3206 // Iterate over the module, deserializing any functions that are still on
3208 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3210 if (F->isMaterializable()) {
3211 if (error_code EC = Materialize(F))
3215 // At this point, if there are any function bodies, the current bit is
3216 // pointing to the END_BLOCK record after them. Now make sure the rest
3217 // of the bits in the module have been read.
3221 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3222 // delete the old functions to clean up. We can't do this unless the entire
3223 // module is materialized because there could always be another function body
3224 // with calls to the old function.
3225 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3226 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3227 if (I->first != I->second) {
3228 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3230 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3231 UpgradeIntrinsicCall(CI, I->second);
3233 if (!I->first->use_empty())
3234 I->first->replaceAllUsesWith(I->second);
3235 I->first->eraseFromParent();
3238 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3240 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3241 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3243 UpgradeDebugInfo(*M);
3244 return error_code();
3247 error_code BitcodeReader::InitStream() {
3249 return InitLazyStream();
3250 return InitStreamFromBuffer();
3253 error_code BitcodeReader::InitStreamFromBuffer() {
3254 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3255 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3257 if (Buffer->getBufferSize() & 3) {
3258 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3259 return Error(InvalidBitcodeSignature);
3261 return Error(BitcodeStreamInvalidSize);
3264 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3265 // The magic number is 0x0B17C0DE stored in little endian.
3266 if (isBitcodeWrapper(BufPtr, BufEnd))
3267 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3268 return Error(InvalidBitcodeWrapperHeader);
3270 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3271 Stream.init(*StreamFile);
3273 return error_code();
3276 error_code BitcodeReader::InitLazyStream() {
3277 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3279 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3280 StreamFile.reset(new BitstreamReader(Bytes));
3281 Stream.init(*StreamFile);
3283 unsigned char buf[16];
3284 if (Bytes->readBytes(0, 16, buf) == -1)
3285 return Error(BitcodeStreamInvalidSize);
3287 if (!isBitcode(buf, buf + 16))
3288 return Error(InvalidBitcodeSignature);
3290 if (isBitcodeWrapper(buf, buf + 4)) {
3291 const unsigned char *bitcodeStart = buf;
3292 const unsigned char *bitcodeEnd = buf + 16;
3293 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3294 Bytes->dropLeadingBytes(bitcodeStart - buf);
3295 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3297 return error_code();
3301 class BitcodeErrorCategoryType : public error_category {
3302 const char *name() const override {
3303 return "llvm.bitcode";
3305 std::string message(int IE) const override {
3306 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3308 case BitcodeReader::BitcodeStreamInvalidSize:
3309 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3310 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3311 return "Conflicting METADATA_KIND records";
3312 case BitcodeReader::CouldNotFindFunctionInStream:
3313 return "Could not find function in stream";
3314 case BitcodeReader::ExpectedConstant:
3315 return "Expected a constant";
3316 case BitcodeReader::InsufficientFunctionProtos:
3317 return "Insufficient function protos";
3318 case BitcodeReader::InvalidBitcodeSignature:
3319 return "Invalid bitcode signature";
3320 case BitcodeReader::InvalidBitcodeWrapperHeader:
3321 return "Invalid bitcode wrapper header";
3322 case BitcodeReader::InvalidConstantReference:
3323 return "Invalid ronstant reference";
3324 case BitcodeReader::InvalidID:
3325 return "Invalid ID";
3326 case BitcodeReader::InvalidInstructionWithNoBB:
3327 return "Invalid instruction with no BB";
3328 case BitcodeReader::InvalidRecord:
3329 return "Invalid record";
3330 case BitcodeReader::InvalidTypeForValue:
3331 return "Invalid type for value";
3332 case BitcodeReader::InvalidTYPETable:
3333 return "Invalid TYPE table";
3334 case BitcodeReader::InvalidType:
3335 return "Invalid type";
3336 case BitcodeReader::MalformedBlock:
3337 return "Malformed block";
3338 case BitcodeReader::MalformedGlobalInitializerSet:
3339 return "Malformed global initializer set";
3340 case BitcodeReader::InvalidMultipleBlocks:
3341 return "Invalid multiple blocks";
3342 case BitcodeReader::NeverResolvedValueFoundInFunction:
3343 return "Never resolved value found in function";
3344 case BitcodeReader::InvalidValue:
3345 return "Invalid value";
3347 llvm_unreachable("Unknown error type!");
3352 const error_category &BitcodeReader::BitcodeErrorCategory() {
3353 static BitcodeErrorCategoryType O;
3357 //===----------------------------------------------------------------------===//
3358 // External interface
3359 //===----------------------------------------------------------------------===//
3361 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3363 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3364 LLVMContext &Context) {
3365 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3366 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3367 M->setMaterializer(R);
3368 if (error_code EC = R->ParseBitcodeInto(M)) {
3369 delete M; // Also deletes R.
3372 // Have the BitcodeReader dtor delete 'Buffer'.
3373 R->setBufferOwned(true);
3375 R->materializeForwardReferencedFunctions();
3381 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3382 DataStreamer *streamer,
3383 LLVMContext &Context,
3384 std::string *ErrMsg) {
3385 Module *M = new Module(name, Context);
3386 BitcodeReader *R = new BitcodeReader(streamer, Context);
3387 M->setMaterializer(R);
3388 if (error_code EC = R->ParseBitcodeInto(M)) {
3390 *ErrMsg = EC.message();
3391 delete M; // Also deletes R.
3394 R->setBufferOwned(false); // no buffer to delete
3398 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3399 LLVMContext &Context) {
3400 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3403 Module *M = ModuleOrErr.get();
3405 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3406 // there was an error.
3407 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3409 // Read in the entire module, and destroy the BitcodeReader.
3410 if (error_code EC = M->materializeAllPermanently()) {
3415 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3416 // written. We must defer until the Module has been fully materialized.
3421 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3422 LLVMContext& Context,
3423 std::string *ErrMsg) {
3424 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3425 // Don't let the BitcodeReader dtor delete 'Buffer'.
3426 R->setBufferOwned(false);
3428 std::string Triple("");
3429 if (error_code EC = R->ParseTriple(Triple))
3431 *ErrMsg = EC.message();