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() {
43 std::vector<Type*>().swap(TypeList);
46 std::vector<Comdat *>().swap(ComdatList);
48 std::vector<AttributeSet>().swap(MAttributes);
49 std::vector<BasicBlock*>().swap(FunctionBBs);
50 std::vector<Function*>().swap(FunctionsWithBodies);
51 DeferredFunctionInfo.clear();
54 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
57 //===----------------------------------------------------------------------===//
58 // Helper functions to implement forward reference resolution, etc.
59 //===----------------------------------------------------------------------===//
61 /// ConvertToString - Convert a string from a record into an std::string, return
63 template<typename StrTy>
64 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
66 if (Idx > Record.size())
69 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
70 Result += (char)Record[i];
74 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
76 default: // Map unknown/new linkages to external
77 case 0: return GlobalValue::ExternalLinkage;
78 case 1: return GlobalValue::WeakAnyLinkage;
79 case 2: return GlobalValue::AppendingLinkage;
80 case 3: return GlobalValue::InternalLinkage;
81 case 4: return GlobalValue::LinkOnceAnyLinkage;
82 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
83 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
84 case 7: return GlobalValue::ExternalWeakLinkage;
85 case 8: return GlobalValue::CommonLinkage;
86 case 9: return GlobalValue::PrivateLinkage;
87 case 10: return GlobalValue::WeakODRLinkage;
88 case 11: return GlobalValue::LinkOnceODRLinkage;
89 case 12: return GlobalValue::AvailableExternallyLinkage;
91 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
93 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
97 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
99 default: // Map unknown visibilities to default.
100 case 0: return GlobalValue::DefaultVisibility;
101 case 1: return GlobalValue::HiddenVisibility;
102 case 2: return GlobalValue::ProtectedVisibility;
106 static GlobalValue::DLLStorageClassTypes
107 GetDecodedDLLStorageClass(unsigned Val) {
109 default: // Map unknown values to default.
110 case 0: return GlobalValue::DefaultStorageClass;
111 case 1: return GlobalValue::DLLImportStorageClass;
112 case 2: return GlobalValue::DLLExportStorageClass;
116 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
118 case 0: return GlobalVariable::NotThreadLocal;
119 default: // Map unknown non-zero value to general dynamic.
120 case 1: return GlobalVariable::GeneralDynamicTLSModel;
121 case 2: return GlobalVariable::LocalDynamicTLSModel;
122 case 3: return GlobalVariable::InitialExecTLSModel;
123 case 4: return GlobalVariable::LocalExecTLSModel;
127 static int GetDecodedCastOpcode(unsigned Val) {
130 case bitc::CAST_TRUNC : return Instruction::Trunc;
131 case bitc::CAST_ZEXT : return Instruction::ZExt;
132 case bitc::CAST_SEXT : return Instruction::SExt;
133 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
134 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
135 case bitc::CAST_UITOFP : return Instruction::UIToFP;
136 case bitc::CAST_SITOFP : return Instruction::SIToFP;
137 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
138 case bitc::CAST_FPEXT : return Instruction::FPExt;
139 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
140 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
141 case bitc::CAST_BITCAST : return Instruction::BitCast;
142 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
145 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
148 case bitc::BINOP_ADD:
149 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
150 case bitc::BINOP_SUB:
151 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
152 case bitc::BINOP_MUL:
153 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
154 case bitc::BINOP_UDIV: return Instruction::UDiv;
155 case bitc::BINOP_SDIV:
156 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
157 case bitc::BINOP_UREM: return Instruction::URem;
158 case bitc::BINOP_SREM:
159 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
160 case bitc::BINOP_SHL: return Instruction::Shl;
161 case bitc::BINOP_LSHR: return Instruction::LShr;
162 case bitc::BINOP_ASHR: return Instruction::AShr;
163 case bitc::BINOP_AND: return Instruction::And;
164 case bitc::BINOP_OR: return Instruction::Or;
165 case bitc::BINOP_XOR: return Instruction::Xor;
169 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
171 default: return AtomicRMWInst::BAD_BINOP;
172 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
173 case bitc::RMW_ADD: return AtomicRMWInst::Add;
174 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
175 case bitc::RMW_AND: return AtomicRMWInst::And;
176 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
177 case bitc::RMW_OR: return AtomicRMWInst::Or;
178 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
179 case bitc::RMW_MAX: return AtomicRMWInst::Max;
180 case bitc::RMW_MIN: return AtomicRMWInst::Min;
181 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
182 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
186 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
188 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
189 case bitc::ORDERING_UNORDERED: return Unordered;
190 case bitc::ORDERING_MONOTONIC: return Monotonic;
191 case bitc::ORDERING_ACQUIRE: return Acquire;
192 case bitc::ORDERING_RELEASE: return Release;
193 case bitc::ORDERING_ACQREL: return AcquireRelease;
194 default: // Map unknown orderings to sequentially-consistent.
195 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
199 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
201 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
202 default: // Map unknown scopes to cross-thread.
203 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
207 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
209 default: // Map unknown selection kinds to any.
210 case bitc::COMDAT_SELECTION_KIND_ANY:
212 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
213 return Comdat::ExactMatch;
214 case bitc::COMDAT_SELECTION_KIND_LARGEST:
215 return Comdat::Largest;
216 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
217 return Comdat::NoDuplicates;
218 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
219 return Comdat::SameSize;
223 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
225 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
226 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
232 /// @brief A class for maintaining the slot number definition
233 /// as a placeholder for the actual definition for forward constants defs.
234 class ConstantPlaceHolder : public ConstantExpr {
235 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
237 // allocate space for exactly one operand
238 void *operator new(size_t s) {
239 return User::operator new(s, 1);
241 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
242 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
243 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
246 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
247 static bool classof(const Value *V) {
248 return isa<ConstantExpr>(V) &&
249 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
253 /// Provide fast operand accessors
254 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
258 // FIXME: can we inherit this from ConstantExpr?
260 struct OperandTraits<ConstantPlaceHolder> :
261 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
266 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
275 WeakVH &OldV = ValuePtrs[Idx];
281 // Handle constants and non-constants (e.g. instrs) differently for
283 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
284 ResolveConstants.push_back(std::make_pair(PHC, Idx));
287 // If there was a forward reference to this value, replace it.
288 Value *PrevVal = OldV;
289 OldV->replaceAllUsesWith(V);
295 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
300 if (Value *V = ValuePtrs[Idx]) {
301 assert(Ty == V->getType() && "Type mismatch in constant table!");
302 return cast<Constant>(V);
305 // Create and return a placeholder, which will later be RAUW'd.
306 Constant *C = new ConstantPlaceHolder(Ty, Context);
311 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
315 if (Value *V = ValuePtrs[Idx]) {
316 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
320 // No type specified, must be invalid reference.
321 if (!Ty) return nullptr;
323 // Create and return a placeholder, which will later be RAUW'd.
324 Value *V = new Argument(Ty);
329 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
330 /// resolves any forward references. The idea behind this is that we sometimes
331 /// get constants (such as large arrays) which reference *many* forward ref
332 /// constants. Replacing each of these causes a lot of thrashing when
333 /// building/reuniquing the constant. Instead of doing this, we look at all the
334 /// uses and rewrite all the place holders at once for any constant that uses
336 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
337 // Sort the values by-pointer so that they are efficient to look up with a
339 std::sort(ResolveConstants.begin(), ResolveConstants.end());
341 SmallVector<Constant*, 64> NewOps;
343 while (!ResolveConstants.empty()) {
344 Value *RealVal = operator[](ResolveConstants.back().second);
345 Constant *Placeholder = ResolveConstants.back().first;
346 ResolveConstants.pop_back();
348 // Loop over all users of the placeholder, updating them to reference the
349 // new value. If they reference more than one placeholder, update them all
351 while (!Placeholder->use_empty()) {
352 auto UI = Placeholder->user_begin();
355 // If the using object isn't uniqued, just update the operands. This
356 // handles instructions and initializers for global variables.
357 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
358 UI.getUse().set(RealVal);
362 // Otherwise, we have a constant that uses the placeholder. Replace that
363 // constant with a new constant that has *all* placeholder uses updated.
364 Constant *UserC = cast<Constant>(U);
365 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
368 if (!isa<ConstantPlaceHolder>(*I)) {
369 // Not a placeholder reference.
371 } else if (*I == Placeholder) {
372 // Common case is that it just references this one placeholder.
375 // Otherwise, look up the placeholder in ResolveConstants.
376 ResolveConstantsTy::iterator It =
377 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
378 std::pair<Constant*, unsigned>(cast<Constant>(*I),
380 assert(It != ResolveConstants.end() && It->first == *I);
381 NewOp = operator[](It->second);
384 NewOps.push_back(cast<Constant>(NewOp));
387 // Make the new constant.
389 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
390 NewC = ConstantArray::get(UserCA->getType(), NewOps);
391 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
392 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
393 } else if (isa<ConstantVector>(UserC)) {
394 NewC = ConstantVector::get(NewOps);
396 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
397 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
400 UserC->replaceAllUsesWith(NewC);
401 UserC->destroyConstant();
405 // Update all ValueHandles, they should be the only users at this point.
406 Placeholder->replaceAllUsesWith(RealVal);
411 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
420 WeakVH &OldV = MDValuePtrs[Idx];
426 // If there was a forward reference to this value, replace it.
427 MDNode *PrevVal = cast<MDNode>(OldV);
428 OldV->replaceAllUsesWith(V);
429 MDNode::deleteTemporary(PrevVal);
430 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
432 MDValuePtrs[Idx] = V;
435 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
439 if (Value *V = MDValuePtrs[Idx]) {
440 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
444 // Create and return a placeholder, which will later be RAUW'd.
445 Value *V = MDNode::getTemporary(Context, None);
446 MDValuePtrs[Idx] = V;
450 Type *BitcodeReader::getTypeByID(unsigned ID) {
451 // The type table size is always specified correctly.
452 if (ID >= TypeList.size())
455 if (Type *Ty = TypeList[ID])
458 // If we have a forward reference, the only possible case is when it is to a
459 // named struct. Just create a placeholder for now.
460 return TypeList[ID] = StructType::create(Context);
464 //===----------------------------------------------------------------------===//
465 // Functions for parsing blocks from the bitcode file
466 //===----------------------------------------------------------------------===//
469 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
470 /// been decoded from the given integer. This function must stay in sync with
471 /// 'encodeLLVMAttributesForBitcode'.
472 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
473 uint64_t EncodedAttrs) {
474 // FIXME: Remove in 4.0.
476 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
477 // the bits above 31 down by 11 bits.
478 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
479 assert((!Alignment || isPowerOf2_32(Alignment)) &&
480 "Alignment must be a power of two.");
483 B.addAlignmentAttr(Alignment);
484 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
485 (EncodedAttrs & 0xffff));
488 std::error_code BitcodeReader::ParseAttributeBlock() {
489 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
490 return Error(InvalidRecord);
492 if (!MAttributes.empty())
493 return Error(InvalidMultipleBlocks);
495 SmallVector<uint64_t, 64> Record;
497 SmallVector<AttributeSet, 8> Attrs;
499 // Read all the records.
501 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
503 switch (Entry.Kind) {
504 case BitstreamEntry::SubBlock: // Handled for us already.
505 case BitstreamEntry::Error:
506 return Error(MalformedBlock);
507 case BitstreamEntry::EndBlock:
508 return std::error_code();
509 case BitstreamEntry::Record:
510 // The interesting case.
516 switch (Stream.readRecord(Entry.ID, Record)) {
517 default: // Default behavior: ignore.
519 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
520 // FIXME: Remove in 4.0.
521 if (Record.size() & 1)
522 return Error(InvalidRecord);
524 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
526 decodeLLVMAttributesForBitcode(B, Record[i+1]);
527 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
530 MAttributes.push_back(AttributeSet::get(Context, Attrs));
534 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
535 for (unsigned i = 0, e = Record.size(); i != e; ++i)
536 Attrs.push_back(MAttributeGroups[Record[i]]);
538 MAttributes.push_back(AttributeSet::get(Context, Attrs));
546 // Returns Attribute::None on unrecognized codes.
547 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
550 return Attribute::None;
551 case bitc::ATTR_KIND_ALIGNMENT:
552 return Attribute::Alignment;
553 case bitc::ATTR_KIND_ALWAYS_INLINE:
554 return Attribute::AlwaysInline;
555 case bitc::ATTR_KIND_BUILTIN:
556 return Attribute::Builtin;
557 case bitc::ATTR_KIND_BY_VAL:
558 return Attribute::ByVal;
559 case bitc::ATTR_KIND_IN_ALLOCA:
560 return Attribute::InAlloca;
561 case bitc::ATTR_KIND_COLD:
562 return Attribute::Cold;
563 case bitc::ATTR_KIND_INLINE_HINT:
564 return Attribute::InlineHint;
565 case bitc::ATTR_KIND_IN_REG:
566 return Attribute::InReg;
567 case bitc::ATTR_KIND_JUMP_TABLE:
568 return Attribute::JumpTable;
569 case bitc::ATTR_KIND_MIN_SIZE:
570 return Attribute::MinSize;
571 case bitc::ATTR_KIND_NAKED:
572 return Attribute::Naked;
573 case bitc::ATTR_KIND_NEST:
574 return Attribute::Nest;
575 case bitc::ATTR_KIND_NO_ALIAS:
576 return Attribute::NoAlias;
577 case bitc::ATTR_KIND_NO_BUILTIN:
578 return Attribute::NoBuiltin;
579 case bitc::ATTR_KIND_NO_CAPTURE:
580 return Attribute::NoCapture;
581 case bitc::ATTR_KIND_NO_DUPLICATE:
582 return Attribute::NoDuplicate;
583 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
584 return Attribute::NoImplicitFloat;
585 case bitc::ATTR_KIND_NO_INLINE:
586 return Attribute::NoInline;
587 case bitc::ATTR_KIND_NON_LAZY_BIND:
588 return Attribute::NonLazyBind;
589 case bitc::ATTR_KIND_NON_NULL:
590 return Attribute::NonNull;
591 case bitc::ATTR_KIND_NO_RED_ZONE:
592 return Attribute::NoRedZone;
593 case bitc::ATTR_KIND_NO_RETURN:
594 return Attribute::NoReturn;
595 case bitc::ATTR_KIND_NO_UNWIND:
596 return Attribute::NoUnwind;
597 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
598 return Attribute::OptimizeForSize;
599 case bitc::ATTR_KIND_OPTIMIZE_NONE:
600 return Attribute::OptimizeNone;
601 case bitc::ATTR_KIND_READ_NONE:
602 return Attribute::ReadNone;
603 case bitc::ATTR_KIND_READ_ONLY:
604 return Attribute::ReadOnly;
605 case bitc::ATTR_KIND_RETURNED:
606 return Attribute::Returned;
607 case bitc::ATTR_KIND_RETURNS_TWICE:
608 return Attribute::ReturnsTwice;
609 case bitc::ATTR_KIND_S_EXT:
610 return Attribute::SExt;
611 case bitc::ATTR_KIND_STACK_ALIGNMENT:
612 return Attribute::StackAlignment;
613 case bitc::ATTR_KIND_STACK_PROTECT:
614 return Attribute::StackProtect;
615 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
616 return Attribute::StackProtectReq;
617 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
618 return Attribute::StackProtectStrong;
619 case bitc::ATTR_KIND_STRUCT_RET:
620 return Attribute::StructRet;
621 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
622 return Attribute::SanitizeAddress;
623 case bitc::ATTR_KIND_SANITIZE_THREAD:
624 return Attribute::SanitizeThread;
625 case bitc::ATTR_KIND_SANITIZE_MEMORY:
626 return Attribute::SanitizeMemory;
627 case bitc::ATTR_KIND_UW_TABLE:
628 return Attribute::UWTable;
629 case bitc::ATTR_KIND_Z_EXT:
630 return Attribute::ZExt;
634 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
635 Attribute::AttrKind *Kind) {
636 *Kind = GetAttrFromCode(Code);
637 if (*Kind == Attribute::None)
638 return Error(InvalidValue);
639 return std::error_code();
642 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
643 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
644 return Error(InvalidRecord);
646 if (!MAttributeGroups.empty())
647 return Error(InvalidMultipleBlocks);
649 SmallVector<uint64_t, 64> Record;
651 // Read all the records.
653 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
655 switch (Entry.Kind) {
656 case BitstreamEntry::SubBlock: // Handled for us already.
657 case BitstreamEntry::Error:
658 return Error(MalformedBlock);
659 case BitstreamEntry::EndBlock:
660 return std::error_code();
661 case BitstreamEntry::Record:
662 // The interesting case.
668 switch (Stream.readRecord(Entry.ID, Record)) {
669 default: // Default behavior: ignore.
671 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
672 if (Record.size() < 3)
673 return Error(InvalidRecord);
675 uint64_t GrpID = Record[0];
676 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
679 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
680 if (Record[i] == 0) { // Enum attribute
681 Attribute::AttrKind Kind;
682 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
685 B.addAttribute(Kind);
686 } else if (Record[i] == 1) { // Integer attribute
687 Attribute::AttrKind Kind;
688 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
690 if (Kind == Attribute::Alignment)
691 B.addAlignmentAttr(Record[++i]);
693 B.addStackAlignmentAttr(Record[++i]);
694 } else { // String attribute
695 assert((Record[i] == 3 || Record[i] == 4) &&
696 "Invalid attribute group entry");
697 bool HasValue = (Record[i++] == 4);
698 SmallString<64> KindStr;
699 SmallString<64> ValStr;
701 while (Record[i] != 0 && i != e)
702 KindStr += Record[i++];
703 assert(Record[i] == 0 && "Kind string not null terminated");
706 // Has a value associated with it.
707 ++i; // Skip the '0' that terminates the "kind" string.
708 while (Record[i] != 0 && i != e)
709 ValStr += Record[i++];
710 assert(Record[i] == 0 && "Value string not null terminated");
713 B.addAttribute(KindStr.str(), ValStr.str());
717 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
724 std::error_code BitcodeReader::ParseTypeTable() {
725 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
726 return Error(InvalidRecord);
728 return ParseTypeTableBody();
731 std::error_code BitcodeReader::ParseTypeTableBody() {
732 if (!TypeList.empty())
733 return Error(InvalidMultipleBlocks);
735 SmallVector<uint64_t, 64> Record;
736 unsigned NumRecords = 0;
738 SmallString<64> TypeName;
740 // Read all the records for this type table.
742 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
744 switch (Entry.Kind) {
745 case BitstreamEntry::SubBlock: // Handled for us already.
746 case BitstreamEntry::Error:
747 return Error(MalformedBlock);
748 case BitstreamEntry::EndBlock:
749 if (NumRecords != TypeList.size())
750 return Error(MalformedBlock);
751 return std::error_code();
752 case BitstreamEntry::Record:
753 // The interesting case.
759 Type *ResultTy = nullptr;
760 switch (Stream.readRecord(Entry.ID, Record)) {
762 return Error(InvalidValue);
763 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
764 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
765 // type list. This allows us to reserve space.
766 if (Record.size() < 1)
767 return Error(InvalidRecord);
768 TypeList.resize(Record[0]);
770 case bitc::TYPE_CODE_VOID: // VOID
771 ResultTy = Type::getVoidTy(Context);
773 case bitc::TYPE_CODE_HALF: // HALF
774 ResultTy = Type::getHalfTy(Context);
776 case bitc::TYPE_CODE_FLOAT: // FLOAT
777 ResultTy = Type::getFloatTy(Context);
779 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
780 ResultTy = Type::getDoubleTy(Context);
782 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
783 ResultTy = Type::getX86_FP80Ty(Context);
785 case bitc::TYPE_CODE_FP128: // FP128
786 ResultTy = Type::getFP128Ty(Context);
788 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
789 ResultTy = Type::getPPC_FP128Ty(Context);
791 case bitc::TYPE_CODE_LABEL: // LABEL
792 ResultTy = Type::getLabelTy(Context);
794 case bitc::TYPE_CODE_METADATA: // METADATA
795 ResultTy = Type::getMetadataTy(Context);
797 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
798 ResultTy = Type::getX86_MMXTy(Context);
800 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
801 if (Record.size() < 1)
802 return Error(InvalidRecord);
804 ResultTy = IntegerType::get(Context, Record[0]);
806 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
807 // [pointee type, address space]
808 if (Record.size() < 1)
809 return Error(InvalidRecord);
810 unsigned AddressSpace = 0;
811 if (Record.size() == 2)
812 AddressSpace = Record[1];
813 ResultTy = getTypeByID(Record[0]);
815 return Error(InvalidType);
816 ResultTy = PointerType::get(ResultTy, AddressSpace);
819 case bitc::TYPE_CODE_FUNCTION_OLD: {
820 // FIXME: attrid is dead, remove it in LLVM 4.0
821 // FUNCTION: [vararg, attrid, retty, paramty x N]
822 if (Record.size() < 3)
823 return Error(InvalidRecord);
824 SmallVector<Type*, 8> ArgTys;
825 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
826 if (Type *T = getTypeByID(Record[i]))
832 ResultTy = getTypeByID(Record[2]);
833 if (!ResultTy || ArgTys.size() < Record.size()-3)
834 return Error(InvalidType);
836 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
839 case bitc::TYPE_CODE_FUNCTION: {
840 // FUNCTION: [vararg, retty, paramty x N]
841 if (Record.size() < 2)
842 return Error(InvalidRecord);
843 SmallVector<Type*, 8> ArgTys;
844 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
845 if (Type *T = getTypeByID(Record[i]))
851 ResultTy = getTypeByID(Record[1]);
852 if (!ResultTy || ArgTys.size() < Record.size()-2)
853 return Error(InvalidType);
855 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
858 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
859 if (Record.size() < 1)
860 return Error(InvalidRecord);
861 SmallVector<Type*, 8> EltTys;
862 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
863 if (Type *T = getTypeByID(Record[i]))
868 if (EltTys.size() != Record.size()-1)
869 return Error(InvalidType);
870 ResultTy = StructType::get(Context, EltTys, Record[0]);
873 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
874 if (ConvertToString(Record, 0, TypeName))
875 return Error(InvalidRecord);
878 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
879 if (Record.size() < 1)
880 return Error(InvalidRecord);
882 if (NumRecords >= TypeList.size())
883 return Error(InvalidTYPETable);
885 // Check to see if this was forward referenced, if so fill in the temp.
886 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
888 Res->setName(TypeName);
889 TypeList[NumRecords] = nullptr;
890 } else // Otherwise, create a new struct.
891 Res = StructType::create(Context, TypeName);
894 SmallVector<Type*, 8> EltTys;
895 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
896 if (Type *T = getTypeByID(Record[i]))
901 if (EltTys.size() != Record.size()-1)
902 return Error(InvalidRecord);
903 Res->setBody(EltTys, Record[0]);
907 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
908 if (Record.size() != 1)
909 return Error(InvalidRecord);
911 if (NumRecords >= TypeList.size())
912 return Error(InvalidTYPETable);
914 // Check to see if this was forward referenced, if so fill in the temp.
915 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
917 Res->setName(TypeName);
918 TypeList[NumRecords] = nullptr;
919 } else // Otherwise, create a new struct with no body.
920 Res = StructType::create(Context, TypeName);
925 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
926 if (Record.size() < 2)
927 return Error(InvalidRecord);
928 if ((ResultTy = getTypeByID(Record[1])))
929 ResultTy = ArrayType::get(ResultTy, Record[0]);
931 return Error(InvalidType);
933 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
934 if (Record.size() < 2)
935 return Error(InvalidRecord);
936 if ((ResultTy = getTypeByID(Record[1])))
937 ResultTy = VectorType::get(ResultTy, Record[0]);
939 return Error(InvalidType);
943 if (NumRecords >= TypeList.size())
944 return Error(InvalidTYPETable);
945 assert(ResultTy && "Didn't read a type?");
946 assert(!TypeList[NumRecords] && "Already read type?");
947 TypeList[NumRecords++] = ResultTy;
951 std::error_code BitcodeReader::ParseValueSymbolTable() {
952 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
953 return Error(InvalidRecord);
955 SmallVector<uint64_t, 64> Record;
957 // Read all the records for this value table.
958 SmallString<128> ValueName;
960 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
962 switch (Entry.Kind) {
963 case BitstreamEntry::SubBlock: // Handled for us already.
964 case BitstreamEntry::Error:
965 return Error(MalformedBlock);
966 case BitstreamEntry::EndBlock:
967 return std::error_code();
968 case BitstreamEntry::Record:
969 // The interesting case.
975 switch (Stream.readRecord(Entry.ID, Record)) {
976 default: // Default behavior: unknown type.
978 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
979 if (ConvertToString(Record, 1, ValueName))
980 return Error(InvalidRecord);
981 unsigned ValueID = Record[0];
982 if (ValueID >= ValueList.size() || !ValueList[ValueID])
983 return Error(InvalidRecord);
984 Value *V = ValueList[ValueID];
986 V->setName(StringRef(ValueName.data(), ValueName.size()));
990 case bitc::VST_CODE_BBENTRY: {
991 if (ConvertToString(Record, 1, ValueName))
992 return Error(InvalidRecord);
993 BasicBlock *BB = getBasicBlock(Record[0]);
995 return Error(InvalidRecord);
997 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1005 std::error_code BitcodeReader::ParseMetadata() {
1006 unsigned NextMDValueNo = MDValueList.size();
1008 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1009 return Error(InvalidRecord);
1011 SmallVector<uint64_t, 64> Record;
1013 // Read all the records.
1015 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1017 switch (Entry.Kind) {
1018 case BitstreamEntry::SubBlock: // Handled for us already.
1019 case BitstreamEntry::Error:
1020 return Error(MalformedBlock);
1021 case BitstreamEntry::EndBlock:
1022 return std::error_code();
1023 case BitstreamEntry::Record:
1024 // The interesting case.
1028 bool IsFunctionLocal = false;
1031 unsigned Code = Stream.readRecord(Entry.ID, Record);
1033 default: // Default behavior: ignore.
1035 case bitc::METADATA_NAME: {
1036 // Read name of the named metadata.
1037 SmallString<8> Name(Record.begin(), Record.end());
1039 Code = Stream.ReadCode();
1041 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1042 unsigned NextBitCode = Stream.readRecord(Code, Record);
1043 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1045 // Read named metadata elements.
1046 unsigned Size = Record.size();
1047 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1048 for (unsigned i = 0; i != Size; ++i) {
1049 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1051 return Error(InvalidRecord);
1052 NMD->addOperand(MD);
1056 case bitc::METADATA_FN_NODE:
1057 IsFunctionLocal = true;
1059 case bitc::METADATA_NODE: {
1060 if (Record.size() % 2 == 1)
1061 return Error(InvalidRecord);
1063 unsigned Size = Record.size();
1064 SmallVector<Value*, 8> Elts;
1065 for (unsigned i = 0; i != Size; i += 2) {
1066 Type *Ty = getTypeByID(Record[i]);
1068 return Error(InvalidRecord);
1069 if (Ty->isMetadataTy())
1070 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1071 else if (!Ty->isVoidTy())
1072 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1074 Elts.push_back(nullptr);
1076 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1077 IsFunctionLocal = false;
1078 MDValueList.AssignValue(V, NextMDValueNo++);
1081 case bitc::METADATA_STRING: {
1082 std::string String(Record.begin(), Record.end());
1083 llvm::UpgradeMDStringConstant(String);
1084 Value *V = MDString::get(Context, String);
1085 MDValueList.AssignValue(V, NextMDValueNo++);
1088 case bitc::METADATA_KIND: {
1089 if (Record.size() < 2)
1090 return Error(InvalidRecord);
1092 unsigned Kind = Record[0];
1093 SmallString<8> Name(Record.begin()+1, Record.end());
1095 unsigned NewKind = TheModule->getMDKindID(Name.str());
1096 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1097 return Error(ConflictingMETADATA_KINDRecords);
1104 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1105 /// the LSB for dense VBR encoding.
1106 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1111 // There is no such thing as -0 with integers. "-0" really means MININT.
1115 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1116 /// values and aliases that we can.
1117 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1118 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1119 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1120 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1122 GlobalInitWorklist.swap(GlobalInits);
1123 AliasInitWorklist.swap(AliasInits);
1124 FunctionPrefixWorklist.swap(FunctionPrefixes);
1126 while (!GlobalInitWorklist.empty()) {
1127 unsigned ValID = GlobalInitWorklist.back().second;
1128 if (ValID >= ValueList.size()) {
1129 // Not ready to resolve this yet, it requires something later in the file.
1130 GlobalInits.push_back(GlobalInitWorklist.back());
1132 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1133 GlobalInitWorklist.back().first->setInitializer(C);
1135 return Error(ExpectedConstant);
1137 GlobalInitWorklist.pop_back();
1140 while (!AliasInitWorklist.empty()) {
1141 unsigned ValID = AliasInitWorklist.back().second;
1142 if (ValID >= ValueList.size()) {
1143 AliasInits.push_back(AliasInitWorklist.back());
1145 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1146 AliasInitWorklist.back().first->setAliasee(C);
1148 return Error(ExpectedConstant);
1150 AliasInitWorklist.pop_back();
1153 while (!FunctionPrefixWorklist.empty()) {
1154 unsigned ValID = FunctionPrefixWorklist.back().second;
1155 if (ValID >= ValueList.size()) {
1156 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1158 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1159 FunctionPrefixWorklist.back().first->setPrefixData(C);
1161 return Error(ExpectedConstant);
1163 FunctionPrefixWorklist.pop_back();
1166 return std::error_code();
1169 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1170 SmallVector<uint64_t, 8> Words(Vals.size());
1171 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1172 BitcodeReader::decodeSignRotatedValue);
1174 return APInt(TypeBits, Words);
1177 std::error_code BitcodeReader::ParseConstants() {
1178 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1179 return Error(InvalidRecord);
1181 SmallVector<uint64_t, 64> Record;
1183 // Read all the records for this value table.
1184 Type *CurTy = Type::getInt32Ty(Context);
1185 unsigned NextCstNo = ValueList.size();
1187 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1189 switch (Entry.Kind) {
1190 case BitstreamEntry::SubBlock: // Handled for us already.
1191 case BitstreamEntry::Error:
1192 return Error(MalformedBlock);
1193 case BitstreamEntry::EndBlock:
1194 if (NextCstNo != ValueList.size())
1195 return Error(InvalidConstantReference);
1197 // Once all the constants have been read, go through and resolve forward
1199 ValueList.ResolveConstantForwardRefs();
1200 return std::error_code();
1201 case BitstreamEntry::Record:
1202 // The interesting case.
1209 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1211 default: // Default behavior: unknown constant
1212 case bitc::CST_CODE_UNDEF: // UNDEF
1213 V = UndefValue::get(CurTy);
1215 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1217 return Error(InvalidRecord);
1218 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1219 return Error(InvalidRecord);
1220 CurTy = TypeList[Record[0]];
1221 continue; // Skip the ValueList manipulation.
1222 case bitc::CST_CODE_NULL: // NULL
1223 V = Constant::getNullValue(CurTy);
1225 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1226 if (!CurTy->isIntegerTy() || Record.empty())
1227 return Error(InvalidRecord);
1228 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1230 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1231 if (!CurTy->isIntegerTy() || Record.empty())
1232 return Error(InvalidRecord);
1234 APInt VInt = ReadWideAPInt(Record,
1235 cast<IntegerType>(CurTy)->getBitWidth());
1236 V = ConstantInt::get(Context, VInt);
1240 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1242 return Error(InvalidRecord);
1243 if (CurTy->isHalfTy())
1244 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1245 APInt(16, (uint16_t)Record[0])));
1246 else if (CurTy->isFloatTy())
1247 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1248 APInt(32, (uint32_t)Record[0])));
1249 else if (CurTy->isDoubleTy())
1250 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1251 APInt(64, Record[0])));
1252 else if (CurTy->isX86_FP80Ty()) {
1253 // Bits are not stored the same way as a normal i80 APInt, compensate.
1254 uint64_t Rearrange[2];
1255 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1256 Rearrange[1] = Record[0] >> 48;
1257 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1258 APInt(80, Rearrange)));
1259 } else if (CurTy->isFP128Ty())
1260 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1261 APInt(128, Record)));
1262 else if (CurTy->isPPC_FP128Ty())
1263 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1264 APInt(128, Record)));
1266 V = UndefValue::get(CurTy);
1270 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1272 return Error(InvalidRecord);
1274 unsigned Size = Record.size();
1275 SmallVector<Constant*, 16> Elts;
1277 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1278 for (unsigned i = 0; i != Size; ++i)
1279 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1280 STy->getElementType(i)));
1281 V = ConstantStruct::get(STy, Elts);
1282 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1283 Type *EltTy = ATy->getElementType();
1284 for (unsigned i = 0; i != Size; ++i)
1285 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1286 V = ConstantArray::get(ATy, Elts);
1287 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1288 Type *EltTy = VTy->getElementType();
1289 for (unsigned i = 0; i != Size; ++i)
1290 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1291 V = ConstantVector::get(Elts);
1293 V = UndefValue::get(CurTy);
1297 case bitc::CST_CODE_STRING: // STRING: [values]
1298 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1300 return Error(InvalidRecord);
1302 SmallString<16> Elts(Record.begin(), Record.end());
1303 V = ConstantDataArray::getString(Context, Elts,
1304 BitCode == bitc::CST_CODE_CSTRING);
1307 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1309 return Error(InvalidRecord);
1311 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1312 unsigned Size = Record.size();
1314 if (EltTy->isIntegerTy(8)) {
1315 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1316 if (isa<VectorType>(CurTy))
1317 V = ConstantDataVector::get(Context, Elts);
1319 V = ConstantDataArray::get(Context, Elts);
1320 } else if (EltTy->isIntegerTy(16)) {
1321 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1322 if (isa<VectorType>(CurTy))
1323 V = ConstantDataVector::get(Context, Elts);
1325 V = ConstantDataArray::get(Context, Elts);
1326 } else if (EltTy->isIntegerTy(32)) {
1327 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1328 if (isa<VectorType>(CurTy))
1329 V = ConstantDataVector::get(Context, Elts);
1331 V = ConstantDataArray::get(Context, Elts);
1332 } else if (EltTy->isIntegerTy(64)) {
1333 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1334 if (isa<VectorType>(CurTy))
1335 V = ConstantDataVector::get(Context, Elts);
1337 V = ConstantDataArray::get(Context, Elts);
1338 } else if (EltTy->isFloatTy()) {
1339 SmallVector<float, 16> Elts(Size);
1340 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1341 if (isa<VectorType>(CurTy))
1342 V = ConstantDataVector::get(Context, Elts);
1344 V = ConstantDataArray::get(Context, Elts);
1345 } else if (EltTy->isDoubleTy()) {
1346 SmallVector<double, 16> Elts(Size);
1347 std::transform(Record.begin(), Record.end(), Elts.begin(),
1349 if (isa<VectorType>(CurTy))
1350 V = ConstantDataVector::get(Context, Elts);
1352 V = ConstantDataArray::get(Context, Elts);
1354 return Error(InvalidTypeForValue);
1359 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1360 if (Record.size() < 3)
1361 return Error(InvalidRecord);
1362 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1364 V = UndefValue::get(CurTy); // Unknown binop.
1366 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1367 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1369 if (Record.size() >= 4) {
1370 if (Opc == Instruction::Add ||
1371 Opc == Instruction::Sub ||
1372 Opc == Instruction::Mul ||
1373 Opc == Instruction::Shl) {
1374 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1375 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1376 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1377 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1378 } else if (Opc == Instruction::SDiv ||
1379 Opc == Instruction::UDiv ||
1380 Opc == Instruction::LShr ||
1381 Opc == Instruction::AShr) {
1382 if (Record[3] & (1 << bitc::PEO_EXACT))
1383 Flags |= SDivOperator::IsExact;
1386 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1390 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1391 if (Record.size() < 3)
1392 return Error(InvalidRecord);
1393 int Opc = GetDecodedCastOpcode(Record[0]);
1395 V = UndefValue::get(CurTy); // Unknown cast.
1397 Type *OpTy = getTypeByID(Record[1]);
1399 return Error(InvalidRecord);
1400 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1401 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1402 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1406 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1407 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1408 if (Record.size() & 1)
1409 return Error(InvalidRecord);
1410 SmallVector<Constant*, 16> Elts;
1411 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1412 Type *ElTy = getTypeByID(Record[i]);
1414 return Error(InvalidRecord);
1415 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1417 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1418 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1420 bitc::CST_CODE_CE_INBOUNDS_GEP);
1423 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1424 if (Record.size() < 3)
1425 return Error(InvalidRecord);
1427 Type *SelectorTy = Type::getInt1Ty(Context);
1429 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1430 // vector. Otherwise, it must be a single bit.
1431 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1432 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1433 VTy->getNumElements());
1435 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1437 ValueList.getConstantFwdRef(Record[1],CurTy),
1438 ValueList.getConstantFwdRef(Record[2],CurTy));
1441 case bitc::CST_CODE_CE_EXTRACTELT
1442 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1443 if (Record.size() < 3)
1444 return Error(InvalidRecord);
1446 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1448 return Error(InvalidRecord);
1449 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1450 Constant *Op1 = nullptr;
1451 if (Record.size() == 4) {
1452 Type *IdxTy = getTypeByID(Record[2]);
1454 return Error(InvalidRecord);
1455 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1456 } else // TODO: Remove with llvm 4.0
1457 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1459 return Error(InvalidRecord);
1460 V = ConstantExpr::getExtractElement(Op0, Op1);
1463 case bitc::CST_CODE_CE_INSERTELT
1464 : { // CE_INSERTELT: [opval, opval, opty, opval]
1465 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1466 if (Record.size() < 3 || !OpTy)
1467 return Error(InvalidRecord);
1468 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1469 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1470 OpTy->getElementType());
1471 Constant *Op2 = nullptr;
1472 if (Record.size() == 4) {
1473 Type *IdxTy = getTypeByID(Record[2]);
1475 return Error(InvalidRecord);
1476 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1477 } else // TODO: Remove with llvm 4.0
1478 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1480 return Error(InvalidRecord);
1481 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1484 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1485 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1486 if (Record.size() < 3 || !OpTy)
1487 return Error(InvalidRecord);
1488 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1489 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1490 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1491 OpTy->getNumElements());
1492 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1493 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1496 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1497 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1499 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1500 if (Record.size() < 4 || !RTy || !OpTy)
1501 return Error(InvalidRecord);
1502 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1503 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1504 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1505 RTy->getNumElements());
1506 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1507 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1510 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1511 if (Record.size() < 4)
1512 return Error(InvalidRecord);
1513 Type *OpTy = getTypeByID(Record[0]);
1515 return Error(InvalidRecord);
1516 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1517 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1519 if (OpTy->isFPOrFPVectorTy())
1520 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1522 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1525 // This maintains backward compatibility, pre-asm dialect keywords.
1526 // FIXME: Remove with the 4.0 release.
1527 case bitc::CST_CODE_INLINEASM_OLD: {
1528 if (Record.size() < 2)
1529 return Error(InvalidRecord);
1530 std::string AsmStr, ConstrStr;
1531 bool HasSideEffects = Record[0] & 1;
1532 bool IsAlignStack = Record[0] >> 1;
1533 unsigned AsmStrSize = Record[1];
1534 if (2+AsmStrSize >= Record.size())
1535 return Error(InvalidRecord);
1536 unsigned ConstStrSize = Record[2+AsmStrSize];
1537 if (3+AsmStrSize+ConstStrSize > Record.size())
1538 return Error(InvalidRecord);
1540 for (unsigned i = 0; i != AsmStrSize; ++i)
1541 AsmStr += (char)Record[2+i];
1542 for (unsigned i = 0; i != ConstStrSize; ++i)
1543 ConstrStr += (char)Record[3+AsmStrSize+i];
1544 PointerType *PTy = cast<PointerType>(CurTy);
1545 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1546 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1549 // This version adds support for the asm dialect keywords (e.g.,
1551 case bitc::CST_CODE_INLINEASM: {
1552 if (Record.size() < 2)
1553 return Error(InvalidRecord);
1554 std::string AsmStr, ConstrStr;
1555 bool HasSideEffects = Record[0] & 1;
1556 bool IsAlignStack = (Record[0] >> 1) & 1;
1557 unsigned AsmDialect = Record[0] >> 2;
1558 unsigned AsmStrSize = Record[1];
1559 if (2+AsmStrSize >= Record.size())
1560 return Error(InvalidRecord);
1561 unsigned ConstStrSize = Record[2+AsmStrSize];
1562 if (3+AsmStrSize+ConstStrSize > Record.size())
1563 return Error(InvalidRecord);
1565 for (unsigned i = 0; i != AsmStrSize; ++i)
1566 AsmStr += (char)Record[2+i];
1567 for (unsigned i = 0; i != ConstStrSize; ++i)
1568 ConstrStr += (char)Record[3+AsmStrSize+i];
1569 PointerType *PTy = cast<PointerType>(CurTy);
1570 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1571 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1572 InlineAsm::AsmDialect(AsmDialect));
1575 case bitc::CST_CODE_BLOCKADDRESS:{
1576 if (Record.size() < 3)
1577 return Error(InvalidRecord);
1578 Type *FnTy = getTypeByID(Record[0]);
1580 return Error(InvalidRecord);
1582 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1584 return Error(InvalidRecord);
1586 // If the function is already parsed we can insert the block address right
1589 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1590 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1592 return Error(InvalidID);
1595 V = BlockAddress::get(Fn, BBI);
1597 // Otherwise insert a placeholder and remember it so it can be inserted
1598 // when the function is parsed.
1599 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1600 Type::getInt8Ty(Context),
1601 false, GlobalValue::InternalLinkage,
1603 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1610 ValueList.AssignValue(V, NextCstNo);
1615 std::error_code BitcodeReader::ParseUseLists() {
1616 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1617 return Error(InvalidRecord);
1619 SmallVector<uint64_t, 64> Record;
1621 // Read all the records.
1623 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1625 switch (Entry.Kind) {
1626 case BitstreamEntry::SubBlock: // Handled for us already.
1627 case BitstreamEntry::Error:
1628 return Error(MalformedBlock);
1629 case BitstreamEntry::EndBlock:
1630 return std::error_code();
1631 case BitstreamEntry::Record:
1632 // The interesting case.
1636 // Read a use list record.
1638 switch (Stream.readRecord(Entry.ID, Record)) {
1639 default: // Default behavior: unknown type.
1641 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1642 unsigned RecordLength = Record.size();
1643 if (RecordLength < 1)
1644 return Error(InvalidRecord);
1645 UseListRecords.push_back(Record);
1652 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1653 /// remember where it is and then skip it. This lets us lazily deserialize the
1655 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1656 // Get the function we are talking about.
1657 if (FunctionsWithBodies.empty())
1658 return Error(InsufficientFunctionProtos);
1660 Function *Fn = FunctionsWithBodies.back();
1661 FunctionsWithBodies.pop_back();
1663 // Save the current stream state.
1664 uint64_t CurBit = Stream.GetCurrentBitNo();
1665 DeferredFunctionInfo[Fn] = CurBit;
1667 // Skip over the function block for now.
1668 if (Stream.SkipBlock())
1669 return Error(InvalidRecord);
1670 return std::error_code();
1673 std::error_code BitcodeReader::GlobalCleanup() {
1674 // Patch the initializers for globals and aliases up.
1675 ResolveGlobalAndAliasInits();
1676 if (!GlobalInits.empty() || !AliasInits.empty())
1677 return Error(MalformedGlobalInitializerSet);
1679 // Look for intrinsic functions which need to be upgraded at some point
1680 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1683 if (UpgradeIntrinsicFunction(FI, NewFn))
1684 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1687 // Look for global variables which need to be renamed.
1688 for (Module::global_iterator
1689 GI = TheModule->global_begin(), GE = TheModule->global_end();
1691 GlobalVariable *GV = GI++;
1692 UpgradeGlobalVariable(GV);
1695 // Force deallocation of memory for these vectors to favor the client that
1696 // want lazy deserialization.
1697 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1698 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1699 return std::error_code();
1702 std::error_code BitcodeReader::ParseModule(bool Resume) {
1704 Stream.JumpToBit(NextUnreadBit);
1705 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1706 return Error(InvalidRecord);
1708 SmallVector<uint64_t, 64> Record;
1709 std::vector<std::string> SectionTable;
1710 std::vector<std::string> GCTable;
1712 // Read all the records for this module.
1714 BitstreamEntry Entry = Stream.advance();
1716 switch (Entry.Kind) {
1717 case BitstreamEntry::Error:
1718 return Error(MalformedBlock);
1719 case BitstreamEntry::EndBlock:
1720 return GlobalCleanup();
1722 case BitstreamEntry::SubBlock:
1724 default: // Skip unknown content.
1725 if (Stream.SkipBlock())
1726 return Error(InvalidRecord);
1728 case bitc::BLOCKINFO_BLOCK_ID:
1729 if (Stream.ReadBlockInfoBlock())
1730 return Error(MalformedBlock);
1732 case bitc::PARAMATTR_BLOCK_ID:
1733 if (std::error_code EC = ParseAttributeBlock())
1736 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1737 if (std::error_code EC = ParseAttributeGroupBlock())
1740 case bitc::TYPE_BLOCK_ID_NEW:
1741 if (std::error_code EC = ParseTypeTable())
1744 case bitc::VALUE_SYMTAB_BLOCK_ID:
1745 if (std::error_code EC = ParseValueSymbolTable())
1747 SeenValueSymbolTable = true;
1749 case bitc::CONSTANTS_BLOCK_ID:
1750 if (std::error_code EC = ParseConstants())
1752 if (std::error_code EC = ResolveGlobalAndAliasInits())
1755 case bitc::METADATA_BLOCK_ID:
1756 if (std::error_code EC = ParseMetadata())
1759 case bitc::FUNCTION_BLOCK_ID:
1760 // If this is the first function body we've seen, reverse the
1761 // FunctionsWithBodies list.
1762 if (!SeenFirstFunctionBody) {
1763 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1764 if (std::error_code EC = GlobalCleanup())
1766 SeenFirstFunctionBody = true;
1769 if (std::error_code EC = RememberAndSkipFunctionBody())
1771 // For streaming bitcode, suspend parsing when we reach the function
1772 // bodies. Subsequent materialization calls will resume it when
1773 // necessary. For streaming, the function bodies must be at the end of
1774 // the bitcode. If the bitcode file is old, the symbol table will be
1775 // at the end instead and will not have been seen yet. In this case,
1776 // just finish the parse now.
1777 if (LazyStreamer && SeenValueSymbolTable) {
1778 NextUnreadBit = Stream.GetCurrentBitNo();
1779 return std::error_code();
1782 case bitc::USELIST_BLOCK_ID:
1783 if (std::error_code EC = ParseUseLists())
1789 case BitstreamEntry::Record:
1790 // The interesting case.
1796 switch (Stream.readRecord(Entry.ID, Record)) {
1797 default: break; // Default behavior, ignore unknown content.
1798 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1799 if (Record.size() < 1)
1800 return Error(InvalidRecord);
1801 // Only version #0 and #1 are supported so far.
1802 unsigned module_version = Record[0];
1803 switch (module_version) {
1805 return Error(InvalidValue);
1807 UseRelativeIDs = false;
1810 UseRelativeIDs = true;
1815 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1817 if (ConvertToString(Record, 0, S))
1818 return Error(InvalidRecord);
1819 TheModule->setTargetTriple(S);
1822 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1824 if (ConvertToString(Record, 0, S))
1825 return Error(InvalidRecord);
1826 TheModule->setDataLayout(S);
1829 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1831 if (ConvertToString(Record, 0, S))
1832 return Error(InvalidRecord);
1833 TheModule->setModuleInlineAsm(S);
1836 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1837 // FIXME: Remove in 4.0.
1839 if (ConvertToString(Record, 0, S))
1840 return Error(InvalidRecord);
1844 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1846 if (ConvertToString(Record, 0, S))
1847 return Error(InvalidRecord);
1848 SectionTable.push_back(S);
1851 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1853 if (ConvertToString(Record, 0, S))
1854 return Error(InvalidRecord);
1855 GCTable.push_back(S);
1858 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1859 if (Record.size() < 2)
1860 return Error(InvalidRecord);
1861 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1862 unsigned ComdatNameSize = Record[1];
1863 std::string ComdatName;
1864 ComdatName.reserve(ComdatNameSize);
1865 for (unsigned i = 0; i != ComdatNameSize; ++i)
1866 ComdatName += (char)Record[2 + i];
1867 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1868 C->setSelectionKind(SK);
1869 ComdatList.push_back(C);
1872 // GLOBALVAR: [pointer type, isconst, initid,
1873 // linkage, alignment, section, visibility, threadlocal,
1874 // unnamed_addr, dllstorageclass]
1875 case bitc::MODULE_CODE_GLOBALVAR: {
1876 if (Record.size() < 6)
1877 return Error(InvalidRecord);
1878 Type *Ty = getTypeByID(Record[0]);
1880 return Error(InvalidRecord);
1881 if (!Ty->isPointerTy())
1882 return Error(InvalidTypeForValue);
1883 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1884 Ty = cast<PointerType>(Ty)->getElementType();
1886 bool isConstant = Record[1];
1887 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1888 unsigned Alignment = (1 << Record[4]) >> 1;
1889 std::string Section;
1891 if (Record[5]-1 >= SectionTable.size())
1892 return Error(InvalidID);
1893 Section = SectionTable[Record[5]-1];
1895 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1896 // Local linkage must have default visibility.
1897 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1898 // FIXME: Change to an error if non-default in 4.0.
1899 Visibility = GetDecodedVisibility(Record[6]);
1901 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1902 if (Record.size() > 7)
1903 TLM = GetDecodedThreadLocalMode(Record[7]);
1905 bool UnnamedAddr = false;
1906 if (Record.size() > 8)
1907 UnnamedAddr = Record[8];
1909 bool ExternallyInitialized = false;
1910 if (Record.size() > 9)
1911 ExternallyInitialized = Record[9];
1913 GlobalVariable *NewGV =
1914 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1915 TLM, AddressSpace, ExternallyInitialized);
1916 NewGV->setAlignment(Alignment);
1917 if (!Section.empty())
1918 NewGV->setSection(Section);
1919 NewGV->setVisibility(Visibility);
1920 NewGV->setUnnamedAddr(UnnamedAddr);
1922 if (Record.size() > 10)
1923 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1925 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1927 ValueList.push_back(NewGV);
1929 // Remember which value to use for the global initializer.
1930 if (unsigned InitID = Record[2])
1931 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1933 if (Record.size() > 11)
1934 if (unsigned ComdatID = Record[11]) {
1935 assert(ComdatID <= ComdatList.size());
1936 NewGV->setComdat(ComdatList[ComdatID - 1]);
1940 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1941 // alignment, section, visibility, gc, unnamed_addr,
1943 case bitc::MODULE_CODE_FUNCTION: {
1944 if (Record.size() < 8)
1945 return Error(InvalidRecord);
1946 Type *Ty = getTypeByID(Record[0]);
1948 return Error(InvalidRecord);
1949 if (!Ty->isPointerTy())
1950 return Error(InvalidTypeForValue);
1952 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1954 return Error(InvalidTypeForValue);
1956 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1959 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1960 bool isProto = Record[2];
1961 Func->setLinkage(GetDecodedLinkage(Record[3]));
1962 Func->setAttributes(getAttributes(Record[4]));
1964 Func->setAlignment((1 << Record[5]) >> 1);
1966 if (Record[6]-1 >= SectionTable.size())
1967 return Error(InvalidID);
1968 Func->setSection(SectionTable[Record[6]-1]);
1970 // Local linkage must have default visibility.
1971 if (!Func->hasLocalLinkage())
1972 // FIXME: Change to an error if non-default in 4.0.
1973 Func->setVisibility(GetDecodedVisibility(Record[7]));
1974 if (Record.size() > 8 && Record[8]) {
1975 if (Record[8]-1 > GCTable.size())
1976 return Error(InvalidID);
1977 Func->setGC(GCTable[Record[8]-1].c_str());
1979 bool UnnamedAddr = false;
1980 if (Record.size() > 9)
1981 UnnamedAddr = Record[9];
1982 Func->setUnnamedAddr(UnnamedAddr);
1983 if (Record.size() > 10 && Record[10] != 0)
1984 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1986 if (Record.size() > 11)
1987 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1989 UpgradeDLLImportExportLinkage(Func, Record[3]);
1991 if (Record.size() > 12)
1992 if (unsigned ComdatID = Record[12]) {
1993 assert(ComdatID <= ComdatList.size());
1994 Func->setComdat(ComdatList[ComdatID - 1]);
1997 ValueList.push_back(Func);
1999 // If this is a function with a body, remember the prototype we are
2000 // creating now, so that we can match up the body with them later.
2002 FunctionsWithBodies.push_back(Func);
2003 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
2007 // ALIAS: [alias type, aliasee val#, linkage]
2008 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2009 case bitc::MODULE_CODE_ALIAS: {
2010 if (Record.size() < 3)
2011 return Error(InvalidRecord);
2012 Type *Ty = getTypeByID(Record[0]);
2014 return Error(InvalidRecord);
2015 auto *PTy = dyn_cast<PointerType>(Ty);
2017 return Error(InvalidTypeForValue);
2020 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2021 GetDecodedLinkage(Record[2]), "", TheModule);
2022 // Old bitcode files didn't have visibility field.
2023 // Local linkage must have default visibility.
2024 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2025 // FIXME: Change to an error if non-default in 4.0.
2026 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2027 if (Record.size() > 4)
2028 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2030 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2031 if (Record.size() > 5)
2032 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2033 if (Record.size() > 6)
2034 NewGA->setUnnamedAddr(Record[6]);
2035 ValueList.push_back(NewGA);
2036 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2039 /// MODULE_CODE_PURGEVALS: [numvals]
2040 case bitc::MODULE_CODE_PURGEVALS:
2041 // Trim down the value list to the specified size.
2042 if (Record.size() < 1 || Record[0] > ValueList.size())
2043 return Error(InvalidRecord);
2044 ValueList.shrinkTo(Record[0]);
2051 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2052 TheModule = nullptr;
2054 if (std::error_code EC = InitStream())
2057 // Sniff for the signature.
2058 if (Stream.Read(8) != 'B' ||
2059 Stream.Read(8) != 'C' ||
2060 Stream.Read(4) != 0x0 ||
2061 Stream.Read(4) != 0xC ||
2062 Stream.Read(4) != 0xE ||
2063 Stream.Read(4) != 0xD)
2064 return Error(InvalidBitcodeSignature);
2066 // We expect a number of well-defined blocks, though we don't necessarily
2067 // need to understand them all.
2069 if (Stream.AtEndOfStream())
2070 return std::error_code();
2072 BitstreamEntry Entry =
2073 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2075 switch (Entry.Kind) {
2076 case BitstreamEntry::Error:
2077 return Error(MalformedBlock);
2078 case BitstreamEntry::EndBlock:
2079 return std::error_code();
2081 case BitstreamEntry::SubBlock:
2083 case bitc::BLOCKINFO_BLOCK_ID:
2084 if (Stream.ReadBlockInfoBlock())
2085 return Error(MalformedBlock);
2087 case bitc::MODULE_BLOCK_ID:
2088 // Reject multiple MODULE_BLOCK's in a single bitstream.
2090 return Error(InvalidMultipleBlocks);
2092 if (std::error_code EC = ParseModule(false))
2095 return std::error_code();
2098 if (Stream.SkipBlock())
2099 return Error(InvalidRecord);
2103 case BitstreamEntry::Record:
2104 // There should be no records in the top-level of blocks.
2106 // The ranlib in Xcode 4 will align archive members by appending newlines
2107 // to the end of them. If this file size is a multiple of 4 but not 8, we
2108 // have to read and ignore these final 4 bytes :-(
2109 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2110 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2111 Stream.AtEndOfStream())
2112 return std::error_code();
2114 return Error(InvalidRecord);
2119 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2120 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2121 return Error(InvalidRecord);
2123 SmallVector<uint64_t, 64> Record;
2126 // Read all the records for this module.
2128 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2130 switch (Entry.Kind) {
2131 case BitstreamEntry::SubBlock: // Handled for us already.
2132 case BitstreamEntry::Error:
2133 return Error(MalformedBlock);
2134 case BitstreamEntry::EndBlock:
2136 case BitstreamEntry::Record:
2137 // The interesting case.
2142 switch (Stream.readRecord(Entry.ID, Record)) {
2143 default: break; // Default behavior, ignore unknown content.
2144 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2146 if (ConvertToString(Record, 0, S))
2147 return Error(InvalidRecord);
2154 llvm_unreachable("Exit infinite loop");
2157 ErrorOr<std::string> BitcodeReader::parseTriple() {
2158 if (std::error_code EC = InitStream())
2161 // Sniff for the signature.
2162 if (Stream.Read(8) != 'B' ||
2163 Stream.Read(8) != 'C' ||
2164 Stream.Read(4) != 0x0 ||
2165 Stream.Read(4) != 0xC ||
2166 Stream.Read(4) != 0xE ||
2167 Stream.Read(4) != 0xD)
2168 return Error(InvalidBitcodeSignature);
2170 // We expect a number of well-defined blocks, though we don't necessarily
2171 // need to understand them all.
2173 BitstreamEntry Entry = Stream.advance();
2175 switch (Entry.Kind) {
2176 case BitstreamEntry::Error:
2177 return Error(MalformedBlock);
2178 case BitstreamEntry::EndBlock:
2179 return std::error_code();
2181 case BitstreamEntry::SubBlock:
2182 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2183 return parseModuleTriple();
2185 // Ignore other sub-blocks.
2186 if (Stream.SkipBlock())
2187 return Error(MalformedBlock);
2190 case BitstreamEntry::Record:
2191 Stream.skipRecord(Entry.ID);
2197 /// ParseMetadataAttachment - Parse metadata attachments.
2198 std::error_code BitcodeReader::ParseMetadataAttachment() {
2199 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2200 return Error(InvalidRecord);
2202 SmallVector<uint64_t, 64> Record;
2204 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2206 switch (Entry.Kind) {
2207 case BitstreamEntry::SubBlock: // Handled for us already.
2208 case BitstreamEntry::Error:
2209 return Error(MalformedBlock);
2210 case BitstreamEntry::EndBlock:
2211 return std::error_code();
2212 case BitstreamEntry::Record:
2213 // The interesting case.
2217 // Read a metadata attachment record.
2219 switch (Stream.readRecord(Entry.ID, Record)) {
2220 default: // Default behavior: ignore.
2222 case bitc::METADATA_ATTACHMENT: {
2223 unsigned RecordLength = Record.size();
2224 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2225 return Error(InvalidRecord);
2226 Instruction *Inst = InstructionList[Record[0]];
2227 for (unsigned i = 1; i != RecordLength; i = i+2) {
2228 unsigned Kind = Record[i];
2229 DenseMap<unsigned, unsigned>::iterator I =
2230 MDKindMap.find(Kind);
2231 if (I == MDKindMap.end())
2232 return Error(InvalidID);
2233 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2234 Inst->setMetadata(I->second, cast<MDNode>(Node));
2235 if (I->second == LLVMContext::MD_tbaa)
2236 InstsWithTBAATag.push_back(Inst);
2244 /// ParseFunctionBody - Lazily parse the specified function body block.
2245 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2246 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2247 return Error(InvalidRecord);
2249 InstructionList.clear();
2250 unsigned ModuleValueListSize = ValueList.size();
2251 unsigned ModuleMDValueListSize = MDValueList.size();
2253 // Add all the function arguments to the value table.
2254 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2255 ValueList.push_back(I);
2257 unsigned NextValueNo = ValueList.size();
2258 BasicBlock *CurBB = nullptr;
2259 unsigned CurBBNo = 0;
2263 // Read all the records.
2264 SmallVector<uint64_t, 64> Record;
2266 BitstreamEntry Entry = Stream.advance();
2268 switch (Entry.Kind) {
2269 case BitstreamEntry::Error:
2270 return Error(MalformedBlock);
2271 case BitstreamEntry::EndBlock:
2272 goto OutOfRecordLoop;
2274 case BitstreamEntry::SubBlock:
2276 default: // Skip unknown content.
2277 if (Stream.SkipBlock())
2278 return Error(InvalidRecord);
2280 case bitc::CONSTANTS_BLOCK_ID:
2281 if (std::error_code EC = ParseConstants())
2283 NextValueNo = ValueList.size();
2285 case bitc::VALUE_SYMTAB_BLOCK_ID:
2286 if (std::error_code EC = ParseValueSymbolTable())
2289 case bitc::METADATA_ATTACHMENT_ID:
2290 if (std::error_code EC = ParseMetadataAttachment())
2293 case bitc::METADATA_BLOCK_ID:
2294 if (std::error_code EC = ParseMetadata())
2300 case BitstreamEntry::Record:
2301 // The interesting case.
2307 Instruction *I = nullptr;
2308 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2310 default: // Default behavior: reject
2311 return Error(InvalidValue);
2312 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2313 if (Record.size() < 1 || Record[0] == 0)
2314 return Error(InvalidRecord);
2315 // Create all the basic blocks for the function.
2316 FunctionBBs.resize(Record[0]);
2317 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2318 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2319 CurBB = FunctionBBs[0];
2322 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2323 // This record indicates that the last instruction is at the same
2324 // location as the previous instruction with a location.
2327 // Get the last instruction emitted.
2328 if (CurBB && !CurBB->empty())
2330 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2331 !FunctionBBs[CurBBNo-1]->empty())
2332 I = &FunctionBBs[CurBBNo-1]->back();
2335 return Error(InvalidRecord);
2336 I->setDebugLoc(LastLoc);
2340 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2341 I = nullptr; // Get the last instruction emitted.
2342 if (CurBB && !CurBB->empty())
2344 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2345 !FunctionBBs[CurBBNo-1]->empty())
2346 I = &FunctionBBs[CurBBNo-1]->back();
2347 if (!I || Record.size() < 4)
2348 return Error(InvalidRecord);
2350 unsigned Line = Record[0], Col = Record[1];
2351 unsigned ScopeID = Record[2], IAID = Record[3];
2353 MDNode *Scope = nullptr, *IA = nullptr;
2354 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2355 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2356 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2357 I->setDebugLoc(LastLoc);
2362 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2365 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2366 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2367 OpNum+1 > Record.size())
2368 return Error(InvalidRecord);
2370 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2372 return Error(InvalidRecord);
2373 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2374 InstructionList.push_back(I);
2375 if (OpNum < Record.size()) {
2376 if (Opc == Instruction::Add ||
2377 Opc == Instruction::Sub ||
2378 Opc == Instruction::Mul ||
2379 Opc == Instruction::Shl) {
2380 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2381 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2382 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2383 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2384 } else if (Opc == Instruction::SDiv ||
2385 Opc == Instruction::UDiv ||
2386 Opc == Instruction::LShr ||
2387 Opc == Instruction::AShr) {
2388 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2389 cast<BinaryOperator>(I)->setIsExact(true);
2390 } else if (isa<FPMathOperator>(I)) {
2392 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2393 FMF.setUnsafeAlgebra();
2394 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2396 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2398 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2399 FMF.setNoSignedZeros();
2400 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2401 FMF.setAllowReciprocal();
2403 I->setFastMathFlags(FMF);
2409 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2412 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2413 OpNum+2 != Record.size())
2414 return Error(InvalidRecord);
2416 Type *ResTy = getTypeByID(Record[OpNum]);
2417 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2418 if (Opc == -1 || !ResTy)
2419 return Error(InvalidRecord);
2420 Instruction *Temp = nullptr;
2421 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2423 InstructionList.push_back(Temp);
2424 CurBB->getInstList().push_back(Temp);
2427 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2429 InstructionList.push_back(I);
2432 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2433 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2436 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2437 return Error(InvalidRecord);
2439 SmallVector<Value*, 16> GEPIdx;
2440 while (OpNum != Record.size()) {
2442 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2443 return Error(InvalidRecord);
2444 GEPIdx.push_back(Op);
2447 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2448 InstructionList.push_back(I);
2449 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2450 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2454 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2455 // EXTRACTVAL: [opty, opval, n x indices]
2458 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2459 return Error(InvalidRecord);
2461 SmallVector<unsigned, 4> EXTRACTVALIdx;
2462 for (unsigned RecSize = Record.size();
2463 OpNum != RecSize; ++OpNum) {
2464 uint64_t Index = Record[OpNum];
2465 if ((unsigned)Index != Index)
2466 return Error(InvalidValue);
2467 EXTRACTVALIdx.push_back((unsigned)Index);
2470 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2471 InstructionList.push_back(I);
2475 case bitc::FUNC_CODE_INST_INSERTVAL: {
2476 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2479 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2480 return Error(InvalidRecord);
2482 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2483 return Error(InvalidRecord);
2485 SmallVector<unsigned, 4> INSERTVALIdx;
2486 for (unsigned RecSize = Record.size();
2487 OpNum != RecSize; ++OpNum) {
2488 uint64_t Index = Record[OpNum];
2489 if ((unsigned)Index != Index)
2490 return Error(InvalidValue);
2491 INSERTVALIdx.push_back((unsigned)Index);
2494 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2495 InstructionList.push_back(I);
2499 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2500 // obsolete form of select
2501 // handles select i1 ... in old bitcode
2503 Value *TrueVal, *FalseVal, *Cond;
2504 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2505 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2506 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2507 return Error(InvalidRecord);
2509 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2510 InstructionList.push_back(I);
2514 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2515 // new form of select
2516 // handles select i1 or select [N x i1]
2518 Value *TrueVal, *FalseVal, *Cond;
2519 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2520 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2521 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2522 return Error(InvalidRecord);
2524 // select condition can be either i1 or [N x i1]
2525 if (VectorType* vector_type =
2526 dyn_cast<VectorType>(Cond->getType())) {
2528 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2529 return Error(InvalidTypeForValue);
2532 if (Cond->getType() != Type::getInt1Ty(Context))
2533 return Error(InvalidTypeForValue);
2536 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2537 InstructionList.push_back(I);
2541 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2544 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2545 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2546 return Error(InvalidRecord);
2547 I = ExtractElementInst::Create(Vec, Idx);
2548 InstructionList.push_back(I);
2552 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2554 Value *Vec, *Elt, *Idx;
2555 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2556 popValue(Record, OpNum, NextValueNo,
2557 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2558 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2559 return Error(InvalidRecord);
2560 I = InsertElementInst::Create(Vec, Elt, Idx);
2561 InstructionList.push_back(I);
2565 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2567 Value *Vec1, *Vec2, *Mask;
2568 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2569 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2570 return Error(InvalidRecord);
2572 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2573 return Error(InvalidRecord);
2574 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2575 InstructionList.push_back(I);
2579 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2580 // Old form of ICmp/FCmp returning bool
2581 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2582 // both legal on vectors but had different behaviour.
2583 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2584 // FCmp/ICmp returning bool or vector of bool
2588 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2589 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2590 OpNum+1 != Record.size())
2591 return Error(InvalidRecord);
2593 if (LHS->getType()->isFPOrFPVectorTy())
2594 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2596 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2597 InstructionList.push_back(I);
2601 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2603 unsigned Size = Record.size();
2605 I = ReturnInst::Create(Context);
2606 InstructionList.push_back(I);
2611 Value *Op = nullptr;
2612 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2613 return Error(InvalidRecord);
2614 if (OpNum != Record.size())
2615 return Error(InvalidRecord);
2617 I = ReturnInst::Create(Context, Op);
2618 InstructionList.push_back(I);
2621 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2622 if (Record.size() != 1 && Record.size() != 3)
2623 return Error(InvalidRecord);
2624 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2626 return Error(InvalidRecord);
2628 if (Record.size() == 1) {
2629 I = BranchInst::Create(TrueDest);
2630 InstructionList.push_back(I);
2633 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2634 Value *Cond = getValue(Record, 2, NextValueNo,
2635 Type::getInt1Ty(Context));
2636 if (!FalseDest || !Cond)
2637 return Error(InvalidRecord);
2638 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2639 InstructionList.push_back(I);
2643 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2645 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2646 // "New" SwitchInst format with case ranges. The changes to write this
2647 // format were reverted but we still recognize bitcode that uses it.
2648 // Hopefully someday we will have support for case ranges and can use
2649 // this format again.
2651 Type *OpTy = getTypeByID(Record[1]);
2652 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2654 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2655 BasicBlock *Default = getBasicBlock(Record[3]);
2656 if (!OpTy || !Cond || !Default)
2657 return Error(InvalidRecord);
2659 unsigned NumCases = Record[4];
2661 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2662 InstructionList.push_back(SI);
2664 unsigned CurIdx = 5;
2665 for (unsigned i = 0; i != NumCases; ++i) {
2666 SmallVector<ConstantInt*, 1> CaseVals;
2667 unsigned NumItems = Record[CurIdx++];
2668 for (unsigned ci = 0; ci != NumItems; ++ci) {
2669 bool isSingleNumber = Record[CurIdx++];
2672 unsigned ActiveWords = 1;
2673 if (ValueBitWidth > 64)
2674 ActiveWords = Record[CurIdx++];
2675 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2677 CurIdx += ActiveWords;
2679 if (!isSingleNumber) {
2681 if (ValueBitWidth > 64)
2682 ActiveWords = Record[CurIdx++];
2684 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2686 CurIdx += ActiveWords;
2688 // FIXME: It is not clear whether values in the range should be
2689 // compared as signed or unsigned values. The partially
2690 // implemented changes that used this format in the past used
2691 // unsigned comparisons.
2692 for ( ; Low.ule(High); ++Low)
2693 CaseVals.push_back(ConstantInt::get(Context, Low));
2695 CaseVals.push_back(ConstantInt::get(Context, Low));
2697 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2698 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2699 cve = CaseVals.end(); cvi != cve; ++cvi)
2700 SI->addCase(*cvi, DestBB);
2706 // Old SwitchInst format without case ranges.
2708 if (Record.size() < 3 || (Record.size() & 1) == 0)
2709 return Error(InvalidRecord);
2710 Type *OpTy = getTypeByID(Record[0]);
2711 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2712 BasicBlock *Default = getBasicBlock(Record[2]);
2713 if (!OpTy || !Cond || !Default)
2714 return Error(InvalidRecord);
2715 unsigned NumCases = (Record.size()-3)/2;
2716 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2717 InstructionList.push_back(SI);
2718 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2719 ConstantInt *CaseVal =
2720 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2721 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2722 if (!CaseVal || !DestBB) {
2724 return Error(InvalidRecord);
2726 SI->addCase(CaseVal, DestBB);
2731 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2732 if (Record.size() < 2)
2733 return Error(InvalidRecord);
2734 Type *OpTy = getTypeByID(Record[0]);
2735 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2736 if (!OpTy || !Address)
2737 return Error(InvalidRecord);
2738 unsigned NumDests = Record.size()-2;
2739 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2740 InstructionList.push_back(IBI);
2741 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2742 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2743 IBI->addDestination(DestBB);
2746 return Error(InvalidRecord);
2753 case bitc::FUNC_CODE_INST_INVOKE: {
2754 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2755 if (Record.size() < 4)
2756 return Error(InvalidRecord);
2757 AttributeSet PAL = getAttributes(Record[0]);
2758 unsigned CCInfo = Record[1];
2759 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2760 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2764 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2765 return Error(InvalidRecord);
2767 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2768 FunctionType *FTy = !CalleeTy ? nullptr :
2769 dyn_cast<FunctionType>(CalleeTy->getElementType());
2771 // Check that the right number of fixed parameters are here.
2772 if (!FTy || !NormalBB || !UnwindBB ||
2773 Record.size() < OpNum+FTy->getNumParams())
2774 return Error(InvalidRecord);
2776 SmallVector<Value*, 16> Ops;
2777 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2778 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2779 FTy->getParamType(i)));
2781 return Error(InvalidRecord);
2784 if (!FTy->isVarArg()) {
2785 if (Record.size() != OpNum)
2786 return Error(InvalidRecord);
2788 // Read type/value pairs for varargs params.
2789 while (OpNum != Record.size()) {
2791 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2792 return Error(InvalidRecord);
2797 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2798 InstructionList.push_back(I);
2799 cast<InvokeInst>(I)->setCallingConv(
2800 static_cast<CallingConv::ID>(CCInfo));
2801 cast<InvokeInst>(I)->setAttributes(PAL);
2804 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2806 Value *Val = nullptr;
2807 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2808 return Error(InvalidRecord);
2809 I = ResumeInst::Create(Val);
2810 InstructionList.push_back(I);
2813 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2814 I = new UnreachableInst(Context);
2815 InstructionList.push_back(I);
2817 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2818 if (Record.size() < 1 || ((Record.size()-1)&1))
2819 return Error(InvalidRecord);
2820 Type *Ty = getTypeByID(Record[0]);
2822 return Error(InvalidRecord);
2824 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2825 InstructionList.push_back(PN);
2827 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2829 // With the new function encoding, it is possible that operands have
2830 // negative IDs (for forward references). Use a signed VBR
2831 // representation to keep the encoding small.
2833 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2835 V = getValue(Record, 1+i, NextValueNo, Ty);
2836 BasicBlock *BB = getBasicBlock(Record[2+i]);
2838 return Error(InvalidRecord);
2839 PN->addIncoming(V, BB);
2845 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2846 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2848 if (Record.size() < 4)
2849 return Error(InvalidRecord);
2850 Type *Ty = getTypeByID(Record[Idx++]);
2852 return Error(InvalidRecord);
2853 Value *PersFn = nullptr;
2854 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2855 return Error(InvalidRecord);
2857 bool IsCleanup = !!Record[Idx++];
2858 unsigned NumClauses = Record[Idx++];
2859 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2860 LP->setCleanup(IsCleanup);
2861 for (unsigned J = 0; J != NumClauses; ++J) {
2862 LandingPadInst::ClauseType CT =
2863 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2866 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2868 return Error(InvalidRecord);
2871 assert((CT != LandingPadInst::Catch ||
2872 !isa<ArrayType>(Val->getType())) &&
2873 "Catch clause has a invalid type!");
2874 assert((CT != LandingPadInst::Filter ||
2875 isa<ArrayType>(Val->getType())) &&
2876 "Filter clause has invalid type!");
2877 LP->addClause(cast<Constant>(Val));
2881 InstructionList.push_back(I);
2885 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2886 if (Record.size() != 4)
2887 return Error(InvalidRecord);
2889 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2890 Type *OpTy = getTypeByID(Record[1]);
2891 Value *Size = getFnValueByID(Record[2], OpTy);
2892 unsigned AlignRecord = Record[3];
2893 bool InAlloca = AlignRecord & (1 << 5);
2894 unsigned Align = AlignRecord & ((1 << 5) - 1);
2896 return Error(InvalidRecord);
2897 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2898 AI->setUsedWithInAlloca(InAlloca);
2900 InstructionList.push_back(I);
2903 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2906 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2907 OpNum+2 != Record.size())
2908 return Error(InvalidRecord);
2910 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2911 InstructionList.push_back(I);
2914 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2915 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2918 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2919 OpNum+4 != Record.size())
2920 return Error(InvalidRecord);
2923 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2924 if (Ordering == NotAtomic || Ordering == Release ||
2925 Ordering == AcquireRelease)
2926 return Error(InvalidRecord);
2927 if (Ordering != NotAtomic && Record[OpNum] == 0)
2928 return Error(InvalidRecord);
2929 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2931 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2932 Ordering, SynchScope);
2933 InstructionList.push_back(I);
2936 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2939 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2940 popValue(Record, OpNum, NextValueNo,
2941 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2942 OpNum+2 != Record.size())
2943 return Error(InvalidRecord);
2945 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2946 InstructionList.push_back(I);
2949 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2950 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2953 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2954 popValue(Record, OpNum, NextValueNo,
2955 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2956 OpNum+4 != Record.size())
2957 return Error(InvalidRecord);
2959 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2960 if (Ordering == NotAtomic || Ordering == Acquire ||
2961 Ordering == AcquireRelease)
2962 return Error(InvalidRecord);
2963 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2964 if (Ordering != NotAtomic && Record[OpNum] == 0)
2965 return Error(InvalidRecord);
2967 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2968 Ordering, SynchScope);
2969 InstructionList.push_back(I);
2972 case bitc::FUNC_CODE_INST_CMPXCHG: {
2973 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2974 // failureordering?, isweak?]
2976 Value *Ptr, *Cmp, *New;
2977 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2978 popValue(Record, OpNum, NextValueNo,
2979 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2980 popValue(Record, OpNum, NextValueNo,
2981 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2982 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
2983 return Error(InvalidRecord);
2984 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2985 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2986 return Error(InvalidRecord);
2987 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2989 AtomicOrdering FailureOrdering;
2990 if (Record.size() < 7)
2992 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2994 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
2996 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
2998 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3000 if (Record.size() < 8) {
3001 // Before weak cmpxchgs existed, the instruction simply returned the
3002 // value loaded from memory, so bitcode files from that era will be
3003 // expecting the first component of a modern cmpxchg.
3004 CurBB->getInstList().push_back(I);
3005 I = ExtractValueInst::Create(I, 0);
3007 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3010 InstructionList.push_back(I);
3013 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3014 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3017 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3018 popValue(Record, OpNum, NextValueNo,
3019 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3020 OpNum+4 != Record.size())
3021 return Error(InvalidRecord);
3022 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3023 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3024 Operation > AtomicRMWInst::LAST_BINOP)
3025 return Error(InvalidRecord);
3026 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3027 if (Ordering == NotAtomic || Ordering == Unordered)
3028 return Error(InvalidRecord);
3029 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3030 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3031 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3032 InstructionList.push_back(I);
3035 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3036 if (2 != Record.size())
3037 return Error(InvalidRecord);
3038 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3039 if (Ordering == NotAtomic || Ordering == Unordered ||
3040 Ordering == Monotonic)
3041 return Error(InvalidRecord);
3042 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3043 I = new FenceInst(Context, Ordering, SynchScope);
3044 InstructionList.push_back(I);
3047 case bitc::FUNC_CODE_INST_CALL: {
3048 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3049 if (Record.size() < 3)
3050 return Error(InvalidRecord);
3052 AttributeSet PAL = getAttributes(Record[0]);
3053 unsigned CCInfo = Record[1];
3057 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3058 return Error(InvalidRecord);
3060 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3061 FunctionType *FTy = nullptr;
3062 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3063 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3064 return Error(InvalidRecord);
3066 SmallVector<Value*, 16> Args;
3067 // Read the fixed params.
3068 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3069 if (FTy->getParamType(i)->isLabelTy())
3070 Args.push_back(getBasicBlock(Record[OpNum]));
3072 Args.push_back(getValue(Record, OpNum, NextValueNo,
3073 FTy->getParamType(i)));
3075 return Error(InvalidRecord);
3078 // Read type/value pairs for varargs params.
3079 if (!FTy->isVarArg()) {
3080 if (OpNum != Record.size())
3081 return Error(InvalidRecord);
3083 while (OpNum != Record.size()) {
3085 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3086 return Error(InvalidRecord);
3091 I = CallInst::Create(Callee, Args);
3092 InstructionList.push_back(I);
3093 cast<CallInst>(I)->setCallingConv(
3094 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3095 CallInst::TailCallKind TCK = CallInst::TCK_None;
3097 TCK = CallInst::TCK_Tail;
3098 if (CCInfo & (1 << 14))
3099 TCK = CallInst::TCK_MustTail;
3100 cast<CallInst>(I)->setTailCallKind(TCK);
3101 cast<CallInst>(I)->setAttributes(PAL);
3104 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3105 if (Record.size() < 3)
3106 return Error(InvalidRecord);
3107 Type *OpTy = getTypeByID(Record[0]);
3108 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3109 Type *ResTy = getTypeByID(Record[2]);
3110 if (!OpTy || !Op || !ResTy)
3111 return Error(InvalidRecord);
3112 I = new VAArgInst(Op, ResTy);
3113 InstructionList.push_back(I);
3118 // Add instruction to end of current BB. If there is no current BB, reject
3122 return Error(InvalidInstructionWithNoBB);
3124 CurBB->getInstList().push_back(I);
3126 // If this was a terminator instruction, move to the next block.
3127 if (isa<TerminatorInst>(I)) {
3129 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3132 // Non-void values get registered in the value table for future use.
3133 if (I && !I->getType()->isVoidTy())
3134 ValueList.AssignValue(I, NextValueNo++);
3139 // Check the function list for unresolved values.
3140 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3141 if (!A->getParent()) {
3142 // We found at least one unresolved value. Nuke them all to avoid leaks.
3143 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3144 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3145 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3149 return Error(NeverResolvedValueFoundInFunction);
3153 // FIXME: Check for unresolved forward-declared metadata references
3154 // and clean up leaks.
3156 // See if anything took the address of blocks in this function. If so,
3157 // resolve them now.
3158 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3159 BlockAddrFwdRefs.find(F);
3160 if (BAFRI != BlockAddrFwdRefs.end()) {
3161 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3162 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3163 unsigned BlockIdx = RefList[i].first;
3164 if (BlockIdx >= FunctionBBs.size())
3165 return Error(InvalidID);
3167 GlobalVariable *FwdRef = RefList[i].second;
3168 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3169 FwdRef->eraseFromParent();
3172 BlockAddrFwdRefs.erase(BAFRI);
3175 // Trim the value list down to the size it was before we parsed this function.
3176 ValueList.shrinkTo(ModuleValueListSize);
3177 MDValueList.shrinkTo(ModuleMDValueListSize);
3178 std::vector<BasicBlock*>().swap(FunctionBBs);
3179 return std::error_code();
3182 /// Find the function body in the bitcode stream
3183 std::error_code BitcodeReader::FindFunctionInStream(
3185 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3186 while (DeferredFunctionInfoIterator->second == 0) {
3187 if (Stream.AtEndOfStream())
3188 return Error(CouldNotFindFunctionInStream);
3189 // ParseModule will parse the next body in the stream and set its
3190 // position in the DeferredFunctionInfo map.
3191 if (std::error_code EC = ParseModule(true))
3194 return std::error_code();
3197 //===----------------------------------------------------------------------===//
3198 // GVMaterializer implementation
3199 //===----------------------------------------------------------------------===//
3201 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3203 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3204 if (const Function *F = dyn_cast<Function>(GV)) {
3205 return F->isDeclaration() &&
3206 DeferredFunctionInfo.count(const_cast<Function*>(F));
3211 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
3212 Function *F = dyn_cast<Function>(GV);
3213 // If it's not a function or is already material, ignore the request.
3214 if (!F || !F->isMaterializable())
3215 return std::error_code();
3217 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3218 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3219 // If its position is recorded as 0, its body is somewhere in the stream
3220 // but we haven't seen it yet.
3221 if (DFII->second == 0 && LazyStreamer)
3222 if (std::error_code EC = FindFunctionInStream(F, DFII))
3225 // Move the bit stream to the saved position of the deferred function body.
3226 Stream.JumpToBit(DFII->second);
3228 if (std::error_code EC = ParseFunctionBody(F))
3231 // Upgrade any old intrinsic calls in the function.
3232 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3233 E = UpgradedIntrinsics.end(); I != E; ++I) {
3234 if (I->first != I->second) {
3235 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3237 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3238 UpgradeIntrinsicCall(CI, I->second);
3243 return std::error_code();
3246 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3247 const Function *F = dyn_cast<Function>(GV);
3248 if (!F || F->isDeclaration())
3250 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3253 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3254 Function *F = dyn_cast<Function>(GV);
3255 // If this function isn't dematerializable, this is a noop.
3256 if (!F || !isDematerializable(F))
3259 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3261 // Just forget the function body, we can remat it later.
3265 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3266 assert(M == TheModule &&
3267 "Can only Materialize the Module this BitcodeReader is attached to.");
3268 // Iterate over the module, deserializing any functions that are still on
3270 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3272 if (F->isMaterializable()) {
3273 if (std::error_code EC = Materialize(F))
3277 // At this point, if there are any function bodies, the current bit is
3278 // pointing to the END_BLOCK record after them. Now make sure the rest
3279 // of the bits in the module have been read.
3283 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3284 // delete the old functions to clean up. We can't do this unless the entire
3285 // module is materialized because there could always be another function body
3286 // with calls to the old function.
3287 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3288 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3289 if (I->first != I->second) {
3290 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3292 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3293 UpgradeIntrinsicCall(CI, I->second);
3295 if (!I->first->use_empty())
3296 I->first->replaceAllUsesWith(I->second);
3297 I->first->eraseFromParent();
3300 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3302 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3303 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3305 UpgradeDebugInfo(*M);
3306 return std::error_code();
3309 std::error_code BitcodeReader::InitStream() {
3311 return InitLazyStream();
3312 return InitStreamFromBuffer();
3315 std::error_code BitcodeReader::InitStreamFromBuffer() {
3316 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3317 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3319 if (Buffer->getBufferSize() & 3) {
3320 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3321 return Error(InvalidBitcodeSignature);
3323 return Error(BitcodeStreamInvalidSize);
3326 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3327 // The magic number is 0x0B17C0DE stored in little endian.
3328 if (isBitcodeWrapper(BufPtr, BufEnd))
3329 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3330 return Error(InvalidBitcodeWrapperHeader);
3332 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3333 Stream.init(*StreamFile);
3335 return std::error_code();
3338 std::error_code BitcodeReader::InitLazyStream() {
3339 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3341 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3342 StreamFile.reset(new BitstreamReader(Bytes));
3343 Stream.init(*StreamFile);
3345 unsigned char buf[16];
3346 if (Bytes->readBytes(0, 16, buf) == -1)
3347 return Error(BitcodeStreamInvalidSize);
3349 if (!isBitcode(buf, buf + 16))
3350 return Error(InvalidBitcodeSignature);
3352 if (isBitcodeWrapper(buf, buf + 4)) {
3353 const unsigned char *bitcodeStart = buf;
3354 const unsigned char *bitcodeEnd = buf + 16;
3355 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3356 Bytes->dropLeadingBytes(bitcodeStart - buf);
3357 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3359 return std::error_code();
3363 class BitcodeErrorCategoryType : public std::error_category {
3364 const char *name() const LLVM_NOEXCEPT override {
3365 return "llvm.bitcode";
3367 std::string message(int IE) const override {
3368 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3370 case BitcodeReader::BitcodeStreamInvalidSize:
3371 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3372 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3373 return "Conflicting METADATA_KIND records";
3374 case BitcodeReader::CouldNotFindFunctionInStream:
3375 return "Could not find function in stream";
3376 case BitcodeReader::ExpectedConstant:
3377 return "Expected a constant";
3378 case BitcodeReader::InsufficientFunctionProtos:
3379 return "Insufficient function protos";
3380 case BitcodeReader::InvalidBitcodeSignature:
3381 return "Invalid bitcode signature";
3382 case BitcodeReader::InvalidBitcodeWrapperHeader:
3383 return "Invalid bitcode wrapper header";
3384 case BitcodeReader::InvalidConstantReference:
3385 return "Invalid ronstant reference";
3386 case BitcodeReader::InvalidID:
3387 return "Invalid ID";
3388 case BitcodeReader::InvalidInstructionWithNoBB:
3389 return "Invalid instruction with no BB";
3390 case BitcodeReader::InvalidRecord:
3391 return "Invalid record";
3392 case BitcodeReader::InvalidTypeForValue:
3393 return "Invalid type for value";
3394 case BitcodeReader::InvalidTYPETable:
3395 return "Invalid TYPE table";
3396 case BitcodeReader::InvalidType:
3397 return "Invalid type";
3398 case BitcodeReader::MalformedBlock:
3399 return "Malformed block";
3400 case BitcodeReader::MalformedGlobalInitializerSet:
3401 return "Malformed global initializer set";
3402 case BitcodeReader::InvalidMultipleBlocks:
3403 return "Invalid multiple blocks";
3404 case BitcodeReader::NeverResolvedValueFoundInFunction:
3405 return "Never resolved value found in function";
3406 case BitcodeReader::InvalidValue:
3407 return "Invalid value";
3409 llvm_unreachable("Unknown error type!");
3414 const std::error_category &BitcodeReader::BitcodeErrorCategory() {
3415 static BitcodeErrorCategoryType O;
3419 //===----------------------------------------------------------------------===//
3420 // External interface
3421 //===----------------------------------------------------------------------===//
3423 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3425 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3426 LLVMContext &Context) {
3427 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3428 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3429 M->setMaterializer(R);
3430 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3431 R->releaseBuffer(); // Never take ownership on error.
3432 delete M; // Also deletes R.
3436 R->materializeForwardReferencedFunctions();
3442 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3443 DataStreamer *streamer,
3444 LLVMContext &Context,
3445 std::string *ErrMsg) {
3446 Module *M = new Module(name, Context);
3447 BitcodeReader *R = new BitcodeReader(streamer, Context);
3448 M->setMaterializer(R);
3449 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3451 *ErrMsg = EC.message();
3452 delete M; // Also deletes R.
3458 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3459 LLVMContext &Context) {
3460 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3463 Module *M = ModuleOrErr.get();
3464 // Read in the entire module, and destroy the BitcodeReader.
3465 if (std::error_code EC = M->materializeAllPermanently(true)) {
3470 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3471 // written. We must defer until the Module has been fully materialized.
3476 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3477 LLVMContext &Context) {
3478 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3479 ErrorOr<std::string> Triple = R->parseTriple();
3482 if (Triple.getError())
3484 return Triple.get();