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 if (Record.size() > 6)
1992 NewGA->setUnnamedAddr(Record[6]);
1993 ValueList.push_back(NewGA);
1994 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1997 /// MODULE_CODE_PURGEVALS: [numvals]
1998 case bitc::MODULE_CODE_PURGEVALS:
1999 // Trim down the value list to the specified size.
2000 if (Record.size() < 1 || Record[0] > ValueList.size())
2001 return Error(InvalidRecord);
2002 ValueList.shrinkTo(Record[0]);
2009 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2010 TheModule = nullptr;
2012 if (error_code EC = InitStream())
2015 // Sniff for the signature.
2016 if (Stream.Read(8) != 'B' ||
2017 Stream.Read(8) != 'C' ||
2018 Stream.Read(4) != 0x0 ||
2019 Stream.Read(4) != 0xC ||
2020 Stream.Read(4) != 0xE ||
2021 Stream.Read(4) != 0xD)
2022 return Error(InvalidBitcodeSignature);
2024 // We expect a number of well-defined blocks, though we don't necessarily
2025 // need to understand them all.
2027 if (Stream.AtEndOfStream())
2028 return error_code();
2030 BitstreamEntry Entry =
2031 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2033 switch (Entry.Kind) {
2034 case BitstreamEntry::Error:
2035 return Error(MalformedBlock);
2036 case BitstreamEntry::EndBlock:
2037 return error_code();
2039 case BitstreamEntry::SubBlock:
2041 case bitc::BLOCKINFO_BLOCK_ID:
2042 if (Stream.ReadBlockInfoBlock())
2043 return Error(MalformedBlock);
2045 case bitc::MODULE_BLOCK_ID:
2046 // Reject multiple MODULE_BLOCK's in a single bitstream.
2048 return Error(InvalidMultipleBlocks);
2050 if (error_code EC = ParseModule(false))
2053 return error_code();
2056 if (Stream.SkipBlock())
2057 return Error(InvalidRecord);
2061 case BitstreamEntry::Record:
2062 // There should be no records in the top-level of blocks.
2064 // The ranlib in Xcode 4 will align archive members by appending newlines
2065 // to the end of them. If this file size is a multiple of 4 but not 8, we
2066 // have to read and ignore these final 4 bytes :-(
2067 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2068 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2069 Stream.AtEndOfStream())
2070 return error_code();
2072 return Error(InvalidRecord);
2077 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2078 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2079 return Error(InvalidRecord);
2081 SmallVector<uint64_t, 64> Record;
2083 // Read all the records for this module.
2085 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2087 switch (Entry.Kind) {
2088 case BitstreamEntry::SubBlock: // Handled for us already.
2089 case BitstreamEntry::Error:
2090 return Error(MalformedBlock);
2091 case BitstreamEntry::EndBlock:
2092 return error_code();
2093 case BitstreamEntry::Record:
2094 // The interesting case.
2099 switch (Stream.readRecord(Entry.ID, Record)) {
2100 default: break; // Default behavior, ignore unknown content.
2101 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2103 if (ConvertToString(Record, 0, S))
2104 return Error(InvalidRecord);
2113 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2114 if (error_code EC = InitStream())
2117 // Sniff for the signature.
2118 if (Stream.Read(8) != 'B' ||
2119 Stream.Read(8) != 'C' ||
2120 Stream.Read(4) != 0x0 ||
2121 Stream.Read(4) != 0xC ||
2122 Stream.Read(4) != 0xE ||
2123 Stream.Read(4) != 0xD)
2124 return Error(InvalidBitcodeSignature);
2126 // We expect a number of well-defined blocks, though we don't necessarily
2127 // need to understand them all.
2129 BitstreamEntry Entry = Stream.advance();
2131 switch (Entry.Kind) {
2132 case BitstreamEntry::Error:
2133 return Error(MalformedBlock);
2134 case BitstreamEntry::EndBlock:
2135 return error_code();
2137 case BitstreamEntry::SubBlock:
2138 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2139 return ParseModuleTriple(Triple);
2141 // Ignore other sub-blocks.
2142 if (Stream.SkipBlock())
2143 return Error(MalformedBlock);
2146 case BitstreamEntry::Record:
2147 Stream.skipRecord(Entry.ID);
2153 /// ParseMetadataAttachment - Parse metadata attachments.
2154 error_code BitcodeReader::ParseMetadataAttachment() {
2155 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2156 return Error(InvalidRecord);
2158 SmallVector<uint64_t, 64> Record;
2160 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2162 switch (Entry.Kind) {
2163 case BitstreamEntry::SubBlock: // Handled for us already.
2164 case BitstreamEntry::Error:
2165 return Error(MalformedBlock);
2166 case BitstreamEntry::EndBlock:
2167 return error_code();
2168 case BitstreamEntry::Record:
2169 // The interesting case.
2173 // Read a metadata attachment record.
2175 switch (Stream.readRecord(Entry.ID, Record)) {
2176 default: // Default behavior: ignore.
2178 case bitc::METADATA_ATTACHMENT: {
2179 unsigned RecordLength = Record.size();
2180 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2181 return Error(InvalidRecord);
2182 Instruction *Inst = InstructionList[Record[0]];
2183 for (unsigned i = 1; i != RecordLength; i = i+2) {
2184 unsigned Kind = Record[i];
2185 DenseMap<unsigned, unsigned>::iterator I =
2186 MDKindMap.find(Kind);
2187 if (I == MDKindMap.end())
2188 return Error(InvalidID);
2189 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2190 Inst->setMetadata(I->second, cast<MDNode>(Node));
2191 if (I->second == LLVMContext::MD_tbaa)
2192 InstsWithTBAATag.push_back(Inst);
2200 /// ParseFunctionBody - Lazily parse the specified function body block.
2201 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2202 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2203 return Error(InvalidRecord);
2205 InstructionList.clear();
2206 unsigned ModuleValueListSize = ValueList.size();
2207 unsigned ModuleMDValueListSize = MDValueList.size();
2209 // Add all the function arguments to the value table.
2210 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2211 ValueList.push_back(I);
2213 unsigned NextValueNo = ValueList.size();
2214 BasicBlock *CurBB = nullptr;
2215 unsigned CurBBNo = 0;
2219 // Read all the records.
2220 SmallVector<uint64_t, 64> Record;
2222 BitstreamEntry Entry = Stream.advance();
2224 switch (Entry.Kind) {
2225 case BitstreamEntry::Error:
2226 return Error(MalformedBlock);
2227 case BitstreamEntry::EndBlock:
2228 goto OutOfRecordLoop;
2230 case BitstreamEntry::SubBlock:
2232 default: // Skip unknown content.
2233 if (Stream.SkipBlock())
2234 return Error(InvalidRecord);
2236 case bitc::CONSTANTS_BLOCK_ID:
2237 if (error_code EC = ParseConstants())
2239 NextValueNo = ValueList.size();
2241 case bitc::VALUE_SYMTAB_BLOCK_ID:
2242 if (error_code EC = ParseValueSymbolTable())
2245 case bitc::METADATA_ATTACHMENT_ID:
2246 if (error_code EC = ParseMetadataAttachment())
2249 case bitc::METADATA_BLOCK_ID:
2250 if (error_code EC = ParseMetadata())
2256 case BitstreamEntry::Record:
2257 // The interesting case.
2263 Instruction *I = nullptr;
2264 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2266 default: // Default behavior: reject
2267 return Error(InvalidValue);
2268 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2269 if (Record.size() < 1 || Record[0] == 0)
2270 return Error(InvalidRecord);
2271 // Create all the basic blocks for the function.
2272 FunctionBBs.resize(Record[0]);
2273 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2274 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2275 CurBB = FunctionBBs[0];
2278 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2279 // This record indicates that the last instruction is at the same
2280 // location as the previous instruction with a location.
2283 // Get the last instruction emitted.
2284 if (CurBB && !CurBB->empty())
2286 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2287 !FunctionBBs[CurBBNo-1]->empty())
2288 I = &FunctionBBs[CurBBNo-1]->back();
2291 return Error(InvalidRecord);
2292 I->setDebugLoc(LastLoc);
2296 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2297 I = nullptr; // Get the last instruction emitted.
2298 if (CurBB && !CurBB->empty())
2300 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2301 !FunctionBBs[CurBBNo-1]->empty())
2302 I = &FunctionBBs[CurBBNo-1]->back();
2303 if (!I || Record.size() < 4)
2304 return Error(InvalidRecord);
2306 unsigned Line = Record[0], Col = Record[1];
2307 unsigned ScopeID = Record[2], IAID = Record[3];
2309 MDNode *Scope = nullptr, *IA = nullptr;
2310 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2311 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2312 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2313 I->setDebugLoc(LastLoc);
2318 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2321 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2322 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2323 OpNum+1 > Record.size())
2324 return Error(InvalidRecord);
2326 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2328 return Error(InvalidRecord);
2329 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2330 InstructionList.push_back(I);
2331 if (OpNum < Record.size()) {
2332 if (Opc == Instruction::Add ||
2333 Opc == Instruction::Sub ||
2334 Opc == Instruction::Mul ||
2335 Opc == Instruction::Shl) {
2336 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2337 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2338 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2339 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2340 } else if (Opc == Instruction::SDiv ||
2341 Opc == Instruction::UDiv ||
2342 Opc == Instruction::LShr ||
2343 Opc == Instruction::AShr) {
2344 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2345 cast<BinaryOperator>(I)->setIsExact(true);
2346 } else if (isa<FPMathOperator>(I)) {
2348 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2349 FMF.setUnsafeAlgebra();
2350 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2352 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2354 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2355 FMF.setNoSignedZeros();
2356 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2357 FMF.setAllowReciprocal();
2359 I->setFastMathFlags(FMF);
2365 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2368 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2369 OpNum+2 != Record.size())
2370 return Error(InvalidRecord);
2372 Type *ResTy = getTypeByID(Record[OpNum]);
2373 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2374 if (Opc == -1 || !ResTy)
2375 return Error(InvalidRecord);
2376 Instruction *Temp = nullptr;
2377 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2379 InstructionList.push_back(Temp);
2380 CurBB->getInstList().push_back(Temp);
2383 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2385 InstructionList.push_back(I);
2388 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2389 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2392 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2393 return Error(InvalidRecord);
2395 SmallVector<Value*, 16> GEPIdx;
2396 while (OpNum != Record.size()) {
2398 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2399 return Error(InvalidRecord);
2400 GEPIdx.push_back(Op);
2403 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2404 InstructionList.push_back(I);
2405 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2406 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2410 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2411 // EXTRACTVAL: [opty, opval, n x indices]
2414 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2415 return Error(InvalidRecord);
2417 SmallVector<unsigned, 4> EXTRACTVALIdx;
2418 for (unsigned RecSize = Record.size();
2419 OpNum != RecSize; ++OpNum) {
2420 uint64_t Index = Record[OpNum];
2421 if ((unsigned)Index != Index)
2422 return Error(InvalidValue);
2423 EXTRACTVALIdx.push_back((unsigned)Index);
2426 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2427 InstructionList.push_back(I);
2431 case bitc::FUNC_CODE_INST_INSERTVAL: {
2432 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2435 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2436 return Error(InvalidRecord);
2438 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2439 return Error(InvalidRecord);
2441 SmallVector<unsigned, 4> INSERTVALIdx;
2442 for (unsigned RecSize = Record.size();
2443 OpNum != RecSize; ++OpNum) {
2444 uint64_t Index = Record[OpNum];
2445 if ((unsigned)Index != Index)
2446 return Error(InvalidValue);
2447 INSERTVALIdx.push_back((unsigned)Index);
2450 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2451 InstructionList.push_back(I);
2455 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2456 // obsolete form of select
2457 // handles select i1 ... in old bitcode
2459 Value *TrueVal, *FalseVal, *Cond;
2460 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2461 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2462 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2463 return Error(InvalidRecord);
2465 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2466 InstructionList.push_back(I);
2470 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2471 // new form of select
2472 // handles select i1 or select [N x i1]
2474 Value *TrueVal, *FalseVal, *Cond;
2475 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2476 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2477 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2478 return Error(InvalidRecord);
2480 // select condition can be either i1 or [N x i1]
2481 if (VectorType* vector_type =
2482 dyn_cast<VectorType>(Cond->getType())) {
2484 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2485 return Error(InvalidTypeForValue);
2488 if (Cond->getType() != Type::getInt1Ty(Context))
2489 return Error(InvalidTypeForValue);
2492 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2493 InstructionList.push_back(I);
2497 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2500 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2501 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2502 return Error(InvalidRecord);
2503 I = ExtractElementInst::Create(Vec, Idx);
2504 InstructionList.push_back(I);
2508 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2510 Value *Vec, *Elt, *Idx;
2511 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2512 popValue(Record, OpNum, NextValueNo,
2513 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2514 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2515 return Error(InvalidRecord);
2516 I = InsertElementInst::Create(Vec, Elt, Idx);
2517 InstructionList.push_back(I);
2521 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2523 Value *Vec1, *Vec2, *Mask;
2524 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2525 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2526 return Error(InvalidRecord);
2528 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2529 return Error(InvalidRecord);
2530 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2531 InstructionList.push_back(I);
2535 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2536 // Old form of ICmp/FCmp returning bool
2537 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2538 // both legal on vectors but had different behaviour.
2539 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2540 // FCmp/ICmp returning bool or vector of bool
2544 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2545 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2546 OpNum+1 != Record.size())
2547 return Error(InvalidRecord);
2549 if (LHS->getType()->isFPOrFPVectorTy())
2550 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2552 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2553 InstructionList.push_back(I);
2557 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2559 unsigned Size = Record.size();
2561 I = ReturnInst::Create(Context);
2562 InstructionList.push_back(I);
2567 Value *Op = nullptr;
2568 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2569 return Error(InvalidRecord);
2570 if (OpNum != Record.size())
2571 return Error(InvalidRecord);
2573 I = ReturnInst::Create(Context, Op);
2574 InstructionList.push_back(I);
2577 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2578 if (Record.size() != 1 && Record.size() != 3)
2579 return Error(InvalidRecord);
2580 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2582 return Error(InvalidRecord);
2584 if (Record.size() == 1) {
2585 I = BranchInst::Create(TrueDest);
2586 InstructionList.push_back(I);
2589 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2590 Value *Cond = getValue(Record, 2, NextValueNo,
2591 Type::getInt1Ty(Context));
2592 if (!FalseDest || !Cond)
2593 return Error(InvalidRecord);
2594 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2595 InstructionList.push_back(I);
2599 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2601 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2602 // "New" SwitchInst format with case ranges. The changes to write this
2603 // format were reverted but we still recognize bitcode that uses it.
2604 // Hopefully someday we will have support for case ranges and can use
2605 // this format again.
2607 Type *OpTy = getTypeByID(Record[1]);
2608 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2610 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2611 BasicBlock *Default = getBasicBlock(Record[3]);
2612 if (!OpTy || !Cond || !Default)
2613 return Error(InvalidRecord);
2615 unsigned NumCases = Record[4];
2617 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2618 InstructionList.push_back(SI);
2620 unsigned CurIdx = 5;
2621 for (unsigned i = 0; i != NumCases; ++i) {
2622 SmallVector<ConstantInt*, 1> CaseVals;
2623 unsigned NumItems = Record[CurIdx++];
2624 for (unsigned ci = 0; ci != NumItems; ++ci) {
2625 bool isSingleNumber = Record[CurIdx++];
2628 unsigned ActiveWords = 1;
2629 if (ValueBitWidth > 64)
2630 ActiveWords = Record[CurIdx++];
2631 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2633 CurIdx += ActiveWords;
2635 if (!isSingleNumber) {
2637 if (ValueBitWidth > 64)
2638 ActiveWords = Record[CurIdx++];
2640 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2642 CurIdx += ActiveWords;
2644 // FIXME: It is not clear whether values in the range should be
2645 // compared as signed or unsigned values. The partially
2646 // implemented changes that used this format in the past used
2647 // unsigned comparisons.
2648 for ( ; Low.ule(High); ++Low)
2649 CaseVals.push_back(ConstantInt::get(Context, Low));
2651 CaseVals.push_back(ConstantInt::get(Context, Low));
2653 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2654 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2655 cve = CaseVals.end(); cvi != cve; ++cvi)
2656 SI->addCase(*cvi, DestBB);
2662 // Old SwitchInst format without case ranges.
2664 if (Record.size() < 3 || (Record.size() & 1) == 0)
2665 return Error(InvalidRecord);
2666 Type *OpTy = getTypeByID(Record[0]);
2667 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2668 BasicBlock *Default = getBasicBlock(Record[2]);
2669 if (!OpTy || !Cond || !Default)
2670 return Error(InvalidRecord);
2671 unsigned NumCases = (Record.size()-3)/2;
2672 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2673 InstructionList.push_back(SI);
2674 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2675 ConstantInt *CaseVal =
2676 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2677 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2678 if (!CaseVal || !DestBB) {
2680 return Error(InvalidRecord);
2682 SI->addCase(CaseVal, DestBB);
2687 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2688 if (Record.size() < 2)
2689 return Error(InvalidRecord);
2690 Type *OpTy = getTypeByID(Record[0]);
2691 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2692 if (!OpTy || !Address)
2693 return Error(InvalidRecord);
2694 unsigned NumDests = Record.size()-2;
2695 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2696 InstructionList.push_back(IBI);
2697 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2698 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2699 IBI->addDestination(DestBB);
2702 return Error(InvalidRecord);
2709 case bitc::FUNC_CODE_INST_INVOKE: {
2710 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2711 if (Record.size() < 4)
2712 return Error(InvalidRecord);
2713 AttributeSet PAL = getAttributes(Record[0]);
2714 unsigned CCInfo = Record[1];
2715 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2716 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2720 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2721 return Error(InvalidRecord);
2723 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2724 FunctionType *FTy = !CalleeTy ? nullptr :
2725 dyn_cast<FunctionType>(CalleeTy->getElementType());
2727 // Check that the right number of fixed parameters are here.
2728 if (!FTy || !NormalBB || !UnwindBB ||
2729 Record.size() < OpNum+FTy->getNumParams())
2730 return Error(InvalidRecord);
2732 SmallVector<Value*, 16> Ops;
2733 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2734 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2735 FTy->getParamType(i)));
2737 return Error(InvalidRecord);
2740 if (!FTy->isVarArg()) {
2741 if (Record.size() != OpNum)
2742 return Error(InvalidRecord);
2744 // Read type/value pairs for varargs params.
2745 while (OpNum != Record.size()) {
2747 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2748 return Error(InvalidRecord);
2753 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2754 InstructionList.push_back(I);
2755 cast<InvokeInst>(I)->setCallingConv(
2756 static_cast<CallingConv::ID>(CCInfo));
2757 cast<InvokeInst>(I)->setAttributes(PAL);
2760 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2762 Value *Val = nullptr;
2763 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2764 return Error(InvalidRecord);
2765 I = ResumeInst::Create(Val);
2766 InstructionList.push_back(I);
2769 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2770 I = new UnreachableInst(Context);
2771 InstructionList.push_back(I);
2773 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2774 if (Record.size() < 1 || ((Record.size()-1)&1))
2775 return Error(InvalidRecord);
2776 Type *Ty = getTypeByID(Record[0]);
2778 return Error(InvalidRecord);
2780 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2781 InstructionList.push_back(PN);
2783 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2785 // With the new function encoding, it is possible that operands have
2786 // negative IDs (for forward references). Use a signed VBR
2787 // representation to keep the encoding small.
2789 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2791 V = getValue(Record, 1+i, NextValueNo, Ty);
2792 BasicBlock *BB = getBasicBlock(Record[2+i]);
2794 return Error(InvalidRecord);
2795 PN->addIncoming(V, BB);
2801 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2802 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2804 if (Record.size() < 4)
2805 return Error(InvalidRecord);
2806 Type *Ty = getTypeByID(Record[Idx++]);
2808 return Error(InvalidRecord);
2809 Value *PersFn = nullptr;
2810 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2811 return Error(InvalidRecord);
2813 bool IsCleanup = !!Record[Idx++];
2814 unsigned NumClauses = Record[Idx++];
2815 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2816 LP->setCleanup(IsCleanup);
2817 for (unsigned J = 0; J != NumClauses; ++J) {
2818 LandingPadInst::ClauseType CT =
2819 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2822 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2824 return Error(InvalidRecord);
2827 assert((CT != LandingPadInst::Catch ||
2828 !isa<ArrayType>(Val->getType())) &&
2829 "Catch clause has a invalid type!");
2830 assert((CT != LandingPadInst::Filter ||
2831 isa<ArrayType>(Val->getType())) &&
2832 "Filter clause has invalid type!");
2833 LP->addClause(cast<Constant>(Val));
2837 InstructionList.push_back(I);
2841 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2842 if (Record.size() != 4)
2843 return Error(InvalidRecord);
2845 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2846 Type *OpTy = getTypeByID(Record[1]);
2847 Value *Size = getFnValueByID(Record[2], OpTy);
2848 unsigned Align = Record[3];
2850 return Error(InvalidRecord);
2851 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2852 InstructionList.push_back(I);
2855 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2858 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2859 OpNum+2 != Record.size())
2860 return Error(InvalidRecord);
2862 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2863 InstructionList.push_back(I);
2866 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2867 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2870 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2871 OpNum+4 != Record.size())
2872 return Error(InvalidRecord);
2875 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2876 if (Ordering == NotAtomic || Ordering == Release ||
2877 Ordering == AcquireRelease)
2878 return Error(InvalidRecord);
2879 if (Ordering != NotAtomic && Record[OpNum] == 0)
2880 return Error(InvalidRecord);
2881 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2883 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2884 Ordering, SynchScope);
2885 InstructionList.push_back(I);
2888 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2891 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2892 popValue(Record, OpNum, NextValueNo,
2893 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2894 OpNum+2 != Record.size())
2895 return Error(InvalidRecord);
2897 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2898 InstructionList.push_back(I);
2901 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2902 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2905 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2906 popValue(Record, OpNum, NextValueNo,
2907 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2908 OpNum+4 != Record.size())
2909 return Error(InvalidRecord);
2911 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2912 if (Ordering == NotAtomic || Ordering == Acquire ||
2913 Ordering == AcquireRelease)
2914 return Error(InvalidRecord);
2915 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2916 if (Ordering != NotAtomic && Record[OpNum] == 0)
2917 return Error(InvalidRecord);
2919 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2920 Ordering, SynchScope);
2921 InstructionList.push_back(I);
2924 case bitc::FUNC_CODE_INST_CMPXCHG: {
2925 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2928 Value *Ptr, *Cmp, *New;
2929 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2930 popValue(Record, OpNum, NextValueNo,
2931 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2932 popValue(Record, OpNum, NextValueNo,
2933 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2934 (OpNum + 3 != Record.size() && OpNum + 4 != Record.size()))
2935 return Error(InvalidRecord);
2936 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2937 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2938 return Error(InvalidRecord);
2939 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2941 AtomicOrdering FailureOrdering;
2942 if (Record.size() < 7)
2944 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2946 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
2948 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
2950 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2951 InstructionList.push_back(I);
2954 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2955 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2958 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2959 popValue(Record, OpNum, NextValueNo,
2960 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2961 OpNum+4 != Record.size())
2962 return Error(InvalidRecord);
2963 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2964 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2965 Operation > AtomicRMWInst::LAST_BINOP)
2966 return Error(InvalidRecord);
2967 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2968 if (Ordering == NotAtomic || Ordering == Unordered)
2969 return Error(InvalidRecord);
2970 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2971 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2972 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2973 InstructionList.push_back(I);
2976 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2977 if (2 != Record.size())
2978 return Error(InvalidRecord);
2979 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2980 if (Ordering == NotAtomic || Ordering == Unordered ||
2981 Ordering == Monotonic)
2982 return Error(InvalidRecord);
2983 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2984 I = new FenceInst(Context, Ordering, SynchScope);
2985 InstructionList.push_back(I);
2988 case bitc::FUNC_CODE_INST_CALL: {
2989 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2990 if (Record.size() < 3)
2991 return Error(InvalidRecord);
2993 AttributeSet PAL = getAttributes(Record[0]);
2994 unsigned CCInfo = Record[1];
2998 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2999 return Error(InvalidRecord);
3001 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3002 FunctionType *FTy = nullptr;
3003 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3004 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3005 return Error(InvalidRecord);
3007 SmallVector<Value*, 16> Args;
3008 // Read the fixed params.
3009 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3010 if (FTy->getParamType(i)->isLabelTy())
3011 Args.push_back(getBasicBlock(Record[OpNum]));
3013 Args.push_back(getValue(Record, OpNum, NextValueNo,
3014 FTy->getParamType(i)));
3016 return Error(InvalidRecord);
3019 // Read type/value pairs for varargs params.
3020 if (!FTy->isVarArg()) {
3021 if (OpNum != Record.size())
3022 return Error(InvalidRecord);
3024 while (OpNum != Record.size()) {
3026 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3027 return Error(InvalidRecord);
3032 I = CallInst::Create(Callee, Args);
3033 InstructionList.push_back(I);
3034 cast<CallInst>(I)->setCallingConv(
3035 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3036 CallInst::TailCallKind TCK = CallInst::TCK_None;
3038 TCK = CallInst::TCK_Tail;
3039 if (CCInfo & (1 << 14))
3040 TCK = CallInst::TCK_MustTail;
3041 cast<CallInst>(I)->setTailCallKind(TCK);
3042 cast<CallInst>(I)->setAttributes(PAL);
3045 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3046 if (Record.size() < 3)
3047 return Error(InvalidRecord);
3048 Type *OpTy = getTypeByID(Record[0]);
3049 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3050 Type *ResTy = getTypeByID(Record[2]);
3051 if (!OpTy || !Op || !ResTy)
3052 return Error(InvalidRecord);
3053 I = new VAArgInst(Op, ResTy);
3054 InstructionList.push_back(I);
3059 // Add instruction to end of current BB. If there is no current BB, reject
3063 return Error(InvalidInstructionWithNoBB);
3065 CurBB->getInstList().push_back(I);
3067 // If this was a terminator instruction, move to the next block.
3068 if (isa<TerminatorInst>(I)) {
3070 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3073 // Non-void values get registered in the value table for future use.
3074 if (I && !I->getType()->isVoidTy())
3075 ValueList.AssignValue(I, NextValueNo++);
3080 // Check the function list for unresolved values.
3081 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3082 if (!A->getParent()) {
3083 // We found at least one unresolved value. Nuke them all to avoid leaks.
3084 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3085 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3086 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3090 return Error(NeverResolvedValueFoundInFunction);
3094 // FIXME: Check for unresolved forward-declared metadata references
3095 // and clean up leaks.
3097 // See if anything took the address of blocks in this function. If so,
3098 // resolve them now.
3099 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3100 BlockAddrFwdRefs.find(F);
3101 if (BAFRI != BlockAddrFwdRefs.end()) {
3102 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3103 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3104 unsigned BlockIdx = RefList[i].first;
3105 if (BlockIdx >= FunctionBBs.size())
3106 return Error(InvalidID);
3108 GlobalVariable *FwdRef = RefList[i].second;
3109 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3110 FwdRef->eraseFromParent();
3113 BlockAddrFwdRefs.erase(BAFRI);
3116 // Trim the value list down to the size it was before we parsed this function.
3117 ValueList.shrinkTo(ModuleValueListSize);
3118 MDValueList.shrinkTo(ModuleMDValueListSize);
3119 std::vector<BasicBlock*>().swap(FunctionBBs);
3120 return error_code();
3123 /// Find the function body in the bitcode stream
3124 error_code BitcodeReader::FindFunctionInStream(Function *F,
3125 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3126 while (DeferredFunctionInfoIterator->second == 0) {
3127 if (Stream.AtEndOfStream())
3128 return Error(CouldNotFindFunctionInStream);
3129 // ParseModule will parse the next body in the stream and set its
3130 // position in the DeferredFunctionInfo map.
3131 if (error_code EC = ParseModule(true))
3134 return error_code();
3137 //===----------------------------------------------------------------------===//
3138 // GVMaterializer implementation
3139 //===----------------------------------------------------------------------===//
3142 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3143 if (const Function *F = dyn_cast<Function>(GV)) {
3144 return F->isDeclaration() &&
3145 DeferredFunctionInfo.count(const_cast<Function*>(F));
3150 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3151 Function *F = dyn_cast<Function>(GV);
3152 // If it's not a function or is already material, ignore the request.
3153 if (!F || !F->isMaterializable())
3154 return error_code();
3156 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3157 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3158 // If its position is recorded as 0, its body is somewhere in the stream
3159 // but we haven't seen it yet.
3160 if (DFII->second == 0 && LazyStreamer)
3161 if (error_code EC = FindFunctionInStream(F, DFII))
3164 // Move the bit stream to the saved position of the deferred function body.
3165 Stream.JumpToBit(DFII->second);
3167 if (error_code EC = ParseFunctionBody(F))
3170 // Upgrade any old intrinsic calls in the function.
3171 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3172 E = UpgradedIntrinsics.end(); I != E; ++I) {
3173 if (I->first != I->second) {
3174 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3176 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3177 UpgradeIntrinsicCall(CI, I->second);
3182 return error_code();
3185 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3186 const Function *F = dyn_cast<Function>(GV);
3187 if (!F || F->isDeclaration())
3189 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3192 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3193 Function *F = dyn_cast<Function>(GV);
3194 // If this function isn't dematerializable, this is a noop.
3195 if (!F || !isDematerializable(F))
3198 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3200 // Just forget the function body, we can remat it later.
3205 error_code BitcodeReader::MaterializeModule(Module *M) {
3206 assert(M == TheModule &&
3207 "Can only Materialize the Module this BitcodeReader is attached to.");
3208 // Iterate over the module, deserializing any functions that are still on
3210 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3212 if (F->isMaterializable()) {
3213 if (error_code EC = Materialize(F))
3217 // At this point, if there are any function bodies, the current bit is
3218 // pointing to the END_BLOCK record after them. Now make sure the rest
3219 // of the bits in the module have been read.
3223 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3224 // delete the old functions to clean up. We can't do this unless the entire
3225 // module is materialized because there could always be another function body
3226 // with calls to the old function.
3227 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3228 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3229 if (I->first != I->second) {
3230 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3232 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3233 UpgradeIntrinsicCall(CI, I->second);
3235 if (!I->first->use_empty())
3236 I->first->replaceAllUsesWith(I->second);
3237 I->first->eraseFromParent();
3240 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3242 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3243 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3245 UpgradeDebugInfo(*M);
3246 return error_code();
3249 error_code BitcodeReader::InitStream() {
3251 return InitLazyStream();
3252 return InitStreamFromBuffer();
3255 error_code BitcodeReader::InitStreamFromBuffer() {
3256 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3257 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3259 if (Buffer->getBufferSize() & 3) {
3260 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3261 return Error(InvalidBitcodeSignature);
3263 return Error(BitcodeStreamInvalidSize);
3266 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3267 // The magic number is 0x0B17C0DE stored in little endian.
3268 if (isBitcodeWrapper(BufPtr, BufEnd))
3269 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3270 return Error(InvalidBitcodeWrapperHeader);
3272 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3273 Stream.init(*StreamFile);
3275 return error_code();
3278 error_code BitcodeReader::InitLazyStream() {
3279 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3281 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3282 StreamFile.reset(new BitstreamReader(Bytes));
3283 Stream.init(*StreamFile);
3285 unsigned char buf[16];
3286 if (Bytes->readBytes(0, 16, buf) == -1)
3287 return Error(BitcodeStreamInvalidSize);
3289 if (!isBitcode(buf, buf + 16))
3290 return Error(InvalidBitcodeSignature);
3292 if (isBitcodeWrapper(buf, buf + 4)) {
3293 const unsigned char *bitcodeStart = buf;
3294 const unsigned char *bitcodeEnd = buf + 16;
3295 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3296 Bytes->dropLeadingBytes(bitcodeStart - buf);
3297 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3299 return error_code();
3303 class BitcodeErrorCategoryType : public std::error_category {
3304 const char *name() const LLVM_NOEXCEPT override {
3305 return "llvm.bitcode";
3307 std::string message(int IE) const override {
3308 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3310 case BitcodeReader::BitcodeStreamInvalidSize:
3311 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3312 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3313 return "Conflicting METADATA_KIND records";
3314 case BitcodeReader::CouldNotFindFunctionInStream:
3315 return "Could not find function in stream";
3316 case BitcodeReader::ExpectedConstant:
3317 return "Expected a constant";
3318 case BitcodeReader::InsufficientFunctionProtos:
3319 return "Insufficient function protos";
3320 case BitcodeReader::InvalidBitcodeSignature:
3321 return "Invalid bitcode signature";
3322 case BitcodeReader::InvalidBitcodeWrapperHeader:
3323 return "Invalid bitcode wrapper header";
3324 case BitcodeReader::InvalidConstantReference:
3325 return "Invalid ronstant reference";
3326 case BitcodeReader::InvalidID:
3327 return "Invalid ID";
3328 case BitcodeReader::InvalidInstructionWithNoBB:
3329 return "Invalid instruction with no BB";
3330 case BitcodeReader::InvalidRecord:
3331 return "Invalid record";
3332 case BitcodeReader::InvalidTypeForValue:
3333 return "Invalid type for value";
3334 case BitcodeReader::InvalidTYPETable:
3335 return "Invalid TYPE table";
3336 case BitcodeReader::InvalidType:
3337 return "Invalid type";
3338 case BitcodeReader::MalformedBlock:
3339 return "Malformed block";
3340 case BitcodeReader::MalformedGlobalInitializerSet:
3341 return "Malformed global initializer set";
3342 case BitcodeReader::InvalidMultipleBlocks:
3343 return "Invalid multiple blocks";
3344 case BitcodeReader::NeverResolvedValueFoundInFunction:
3345 return "Never resolved value found in function";
3346 case BitcodeReader::InvalidValue:
3347 return "Invalid value";
3349 llvm_unreachable("Unknown error type!");
3354 const std::error_category &BitcodeReader::BitcodeErrorCategory() {
3355 static BitcodeErrorCategoryType O;
3359 //===----------------------------------------------------------------------===//
3360 // External interface
3361 //===----------------------------------------------------------------------===//
3363 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3365 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3366 LLVMContext &Context) {
3367 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3368 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3369 M->setMaterializer(R);
3370 if (error_code EC = R->ParseBitcodeInto(M)) {
3371 delete M; // Also deletes R.
3374 // Have the BitcodeReader dtor delete 'Buffer'.
3375 R->setBufferOwned(true);
3377 R->materializeForwardReferencedFunctions();
3383 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3384 DataStreamer *streamer,
3385 LLVMContext &Context,
3386 std::string *ErrMsg) {
3387 Module *M = new Module(name, Context);
3388 BitcodeReader *R = new BitcodeReader(streamer, Context);
3389 M->setMaterializer(R);
3390 if (error_code EC = R->ParseBitcodeInto(M)) {
3392 *ErrMsg = EC.message();
3393 delete M; // Also deletes R.
3396 R->setBufferOwned(false); // no buffer to delete
3400 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3401 LLVMContext &Context) {
3402 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3405 Module *M = ModuleOrErr.get();
3407 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3408 // there was an error.
3409 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3411 // Read in the entire module, and destroy the BitcodeReader.
3412 if (error_code EC = M->materializeAllPermanently()) {
3417 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3418 // written. We must defer until the Module has been fully materialized.
3423 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3424 LLVMContext& Context,
3425 std::string *ErrMsg) {
3426 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3427 // Don't let the BitcodeReader dtor delete 'Buffer'.
3428 R->setBufferOwned(false);
3430 std::string Triple("");
3431 if (error_code EC = R->ParseTriple(Triple))
3433 *ErrMsg = EC.message();