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 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
35 if (WillMaterializeAllForwardRefs)
36 return std::error_code();
39 WillMaterializeAllForwardRefs = true;
41 while (!BasicBlockFwdRefs.empty()) {
42 Function *F = BasicBlockFwdRefs.begin()->first;
43 assert(F && "Expected valid function");
44 // Check for a function that isn't materializable to prevent an infinite
45 // loop. When parsing a blockaddress stored in a global variable, there
46 // isn't a trivial way to check if a function will have a body without a
47 // linear search through FunctionsWithBodies, so just check it here.
48 if (!F->isMaterializable())
49 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
51 // Try to materialize F.
52 if (std::error_code EC = Materialize(F))
57 WillMaterializeAllForwardRefs = false;
58 return std::error_code();
61 void BitcodeReader::FreeState() {
63 std::vector<Type*>().swap(TypeList);
66 std::vector<Comdat *>().swap(ComdatList);
68 std::vector<AttributeSet>().swap(MAttributes);
69 std::vector<BasicBlock*>().swap(FunctionBBs);
70 std::vector<Function*>().swap(FunctionsWithBodies);
71 DeferredFunctionInfo.clear();
74 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
77 //===----------------------------------------------------------------------===//
78 // Helper functions to implement forward reference resolution, etc.
79 //===----------------------------------------------------------------------===//
81 /// ConvertToString - Convert a string from a record into an std::string, return
83 template<typename StrTy>
84 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
86 if (Idx > Record.size())
89 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
90 Result += (char)Record[i];
94 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
96 default: // Map unknown/new linkages to external
97 case 0: return GlobalValue::ExternalLinkage;
98 case 1: return GlobalValue::WeakAnyLinkage;
99 case 2: return GlobalValue::AppendingLinkage;
100 case 3: return GlobalValue::InternalLinkage;
101 case 4: return GlobalValue::LinkOnceAnyLinkage;
102 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
103 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
104 case 7: return GlobalValue::ExternalWeakLinkage;
105 case 8: return GlobalValue::CommonLinkage;
106 case 9: return GlobalValue::PrivateLinkage;
107 case 10: return GlobalValue::WeakODRLinkage;
108 case 11: return GlobalValue::LinkOnceODRLinkage;
109 case 12: return GlobalValue::AvailableExternallyLinkage;
111 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
113 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
117 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
119 default: // Map unknown visibilities to default.
120 case 0: return GlobalValue::DefaultVisibility;
121 case 1: return GlobalValue::HiddenVisibility;
122 case 2: return GlobalValue::ProtectedVisibility;
126 static GlobalValue::DLLStorageClassTypes
127 GetDecodedDLLStorageClass(unsigned Val) {
129 default: // Map unknown values to default.
130 case 0: return GlobalValue::DefaultStorageClass;
131 case 1: return GlobalValue::DLLImportStorageClass;
132 case 2: return GlobalValue::DLLExportStorageClass;
136 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
138 case 0: return GlobalVariable::NotThreadLocal;
139 default: // Map unknown non-zero value to general dynamic.
140 case 1: return GlobalVariable::GeneralDynamicTLSModel;
141 case 2: return GlobalVariable::LocalDynamicTLSModel;
142 case 3: return GlobalVariable::InitialExecTLSModel;
143 case 4: return GlobalVariable::LocalExecTLSModel;
147 static int GetDecodedCastOpcode(unsigned Val) {
150 case bitc::CAST_TRUNC : return Instruction::Trunc;
151 case bitc::CAST_ZEXT : return Instruction::ZExt;
152 case bitc::CAST_SEXT : return Instruction::SExt;
153 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
154 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
155 case bitc::CAST_UITOFP : return Instruction::UIToFP;
156 case bitc::CAST_SITOFP : return Instruction::SIToFP;
157 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
158 case bitc::CAST_FPEXT : return Instruction::FPExt;
159 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
160 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
161 case bitc::CAST_BITCAST : return Instruction::BitCast;
162 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
165 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
168 case bitc::BINOP_ADD:
169 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
170 case bitc::BINOP_SUB:
171 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
172 case bitc::BINOP_MUL:
173 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
174 case bitc::BINOP_UDIV: return Instruction::UDiv;
175 case bitc::BINOP_SDIV:
176 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
177 case bitc::BINOP_UREM: return Instruction::URem;
178 case bitc::BINOP_SREM:
179 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
180 case bitc::BINOP_SHL: return Instruction::Shl;
181 case bitc::BINOP_LSHR: return Instruction::LShr;
182 case bitc::BINOP_ASHR: return Instruction::AShr;
183 case bitc::BINOP_AND: return Instruction::And;
184 case bitc::BINOP_OR: return Instruction::Or;
185 case bitc::BINOP_XOR: return Instruction::Xor;
189 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
191 default: return AtomicRMWInst::BAD_BINOP;
192 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
193 case bitc::RMW_ADD: return AtomicRMWInst::Add;
194 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
195 case bitc::RMW_AND: return AtomicRMWInst::And;
196 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
197 case bitc::RMW_OR: return AtomicRMWInst::Or;
198 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
199 case bitc::RMW_MAX: return AtomicRMWInst::Max;
200 case bitc::RMW_MIN: return AtomicRMWInst::Min;
201 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
202 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
206 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
208 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
209 case bitc::ORDERING_UNORDERED: return Unordered;
210 case bitc::ORDERING_MONOTONIC: return Monotonic;
211 case bitc::ORDERING_ACQUIRE: return Acquire;
212 case bitc::ORDERING_RELEASE: return Release;
213 case bitc::ORDERING_ACQREL: return AcquireRelease;
214 default: // Map unknown orderings to sequentially-consistent.
215 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
219 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
221 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
222 default: // Map unknown scopes to cross-thread.
223 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
227 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
229 default: // Map unknown selection kinds to any.
230 case bitc::COMDAT_SELECTION_KIND_ANY:
232 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
233 return Comdat::ExactMatch;
234 case bitc::COMDAT_SELECTION_KIND_LARGEST:
235 return Comdat::Largest;
236 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
237 return Comdat::NoDuplicates;
238 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
239 return Comdat::SameSize;
243 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
245 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
246 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
252 /// @brief A class for maintaining the slot number definition
253 /// as a placeholder for the actual definition for forward constants defs.
254 class ConstantPlaceHolder : public ConstantExpr {
255 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
257 // allocate space for exactly one operand
258 void *operator new(size_t s) {
259 return User::operator new(s, 1);
261 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
262 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
263 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
266 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
267 static bool classof(const Value *V) {
268 return isa<ConstantExpr>(V) &&
269 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
273 /// Provide fast operand accessors
274 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
278 // FIXME: can we inherit this from ConstantExpr?
280 struct OperandTraits<ConstantPlaceHolder> :
281 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
286 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
295 WeakVH &OldV = ValuePtrs[Idx];
301 // Handle constants and non-constants (e.g. instrs) differently for
303 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
304 ResolveConstants.push_back(std::make_pair(PHC, Idx));
307 // If there was a forward reference to this value, replace it.
308 Value *PrevVal = OldV;
309 OldV->replaceAllUsesWith(V);
315 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
320 if (Value *V = ValuePtrs[Idx]) {
321 assert(Ty == V->getType() && "Type mismatch in constant table!");
322 return cast<Constant>(V);
325 // Create and return a placeholder, which will later be RAUW'd.
326 Constant *C = new ConstantPlaceHolder(Ty, Context);
331 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
335 if (Value *V = ValuePtrs[Idx]) {
336 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
340 // No type specified, must be invalid reference.
341 if (!Ty) return nullptr;
343 // Create and return a placeholder, which will later be RAUW'd.
344 Value *V = new Argument(Ty);
349 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
350 /// resolves any forward references. The idea behind this is that we sometimes
351 /// get constants (such as large arrays) which reference *many* forward ref
352 /// constants. Replacing each of these causes a lot of thrashing when
353 /// building/reuniquing the constant. Instead of doing this, we look at all the
354 /// uses and rewrite all the place holders at once for any constant that uses
356 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
357 // Sort the values by-pointer so that they are efficient to look up with a
359 std::sort(ResolveConstants.begin(), ResolveConstants.end());
361 SmallVector<Constant*, 64> NewOps;
363 while (!ResolveConstants.empty()) {
364 Value *RealVal = operator[](ResolveConstants.back().second);
365 Constant *Placeholder = ResolveConstants.back().first;
366 ResolveConstants.pop_back();
368 // Loop over all users of the placeholder, updating them to reference the
369 // new value. If they reference more than one placeholder, update them all
371 while (!Placeholder->use_empty()) {
372 auto UI = Placeholder->user_begin();
375 // If the using object isn't uniqued, just update the operands. This
376 // handles instructions and initializers for global variables.
377 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
378 UI.getUse().set(RealVal);
382 // Otherwise, we have a constant that uses the placeholder. Replace that
383 // constant with a new constant that has *all* placeholder uses updated.
384 Constant *UserC = cast<Constant>(U);
385 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
388 if (!isa<ConstantPlaceHolder>(*I)) {
389 // Not a placeholder reference.
391 } else if (*I == Placeholder) {
392 // Common case is that it just references this one placeholder.
395 // Otherwise, look up the placeholder in ResolveConstants.
396 ResolveConstantsTy::iterator It =
397 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
398 std::pair<Constant*, unsigned>(cast<Constant>(*I),
400 assert(It != ResolveConstants.end() && It->first == *I);
401 NewOp = operator[](It->second);
404 NewOps.push_back(cast<Constant>(NewOp));
407 // Make the new constant.
409 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
410 NewC = ConstantArray::get(UserCA->getType(), NewOps);
411 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
412 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
413 } else if (isa<ConstantVector>(UserC)) {
414 NewC = ConstantVector::get(NewOps);
416 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
417 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
420 UserC->replaceAllUsesWith(NewC);
421 UserC->destroyConstant();
425 // Update all ValueHandles, they should be the only users at this point.
426 Placeholder->replaceAllUsesWith(RealVal);
431 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
440 WeakVH &OldV = MDValuePtrs[Idx];
446 // If there was a forward reference to this value, replace it.
447 MDNode *PrevVal = cast<MDNode>(OldV);
448 OldV->replaceAllUsesWith(V);
449 MDNode::deleteTemporary(PrevVal);
450 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
452 MDValuePtrs[Idx] = V;
455 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
459 if (Value *V = MDValuePtrs[Idx]) {
460 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
464 // Create and return a placeholder, which will later be RAUW'd.
465 Value *V = MDNode::getTemporary(Context, None);
466 MDValuePtrs[Idx] = V;
470 Type *BitcodeReader::getTypeByID(unsigned ID) {
471 // The type table size is always specified correctly.
472 if (ID >= TypeList.size())
475 if (Type *Ty = TypeList[ID])
478 // If we have a forward reference, the only possible case is when it is to a
479 // named struct. Just create a placeholder for now.
480 return TypeList[ID] = StructType::create(Context);
484 //===----------------------------------------------------------------------===//
485 // Functions for parsing blocks from the bitcode file
486 //===----------------------------------------------------------------------===//
489 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
490 /// been decoded from the given integer. This function must stay in sync with
491 /// 'encodeLLVMAttributesForBitcode'.
492 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
493 uint64_t EncodedAttrs) {
494 // FIXME: Remove in 4.0.
496 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
497 // the bits above 31 down by 11 bits.
498 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
499 assert((!Alignment || isPowerOf2_32(Alignment)) &&
500 "Alignment must be a power of two.");
503 B.addAlignmentAttr(Alignment);
504 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
505 (EncodedAttrs & 0xffff));
508 std::error_code BitcodeReader::ParseAttributeBlock() {
509 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
510 return Error(BitcodeError::InvalidRecord);
512 if (!MAttributes.empty())
513 return Error(BitcodeError::InvalidMultipleBlocks);
515 SmallVector<uint64_t, 64> Record;
517 SmallVector<AttributeSet, 8> Attrs;
519 // Read all the records.
521 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
523 switch (Entry.Kind) {
524 case BitstreamEntry::SubBlock: // Handled for us already.
525 case BitstreamEntry::Error:
526 return Error(BitcodeError::MalformedBlock);
527 case BitstreamEntry::EndBlock:
528 return std::error_code();
529 case BitstreamEntry::Record:
530 // The interesting case.
536 switch (Stream.readRecord(Entry.ID, Record)) {
537 default: // Default behavior: ignore.
539 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
540 // FIXME: Remove in 4.0.
541 if (Record.size() & 1)
542 return Error(BitcodeError::InvalidRecord);
544 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
546 decodeLLVMAttributesForBitcode(B, Record[i+1]);
547 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
550 MAttributes.push_back(AttributeSet::get(Context, Attrs));
554 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
555 for (unsigned i = 0, e = Record.size(); i != e; ++i)
556 Attrs.push_back(MAttributeGroups[Record[i]]);
558 MAttributes.push_back(AttributeSet::get(Context, Attrs));
566 // Returns Attribute::None on unrecognized codes.
567 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
570 return Attribute::None;
571 case bitc::ATTR_KIND_ALIGNMENT:
572 return Attribute::Alignment;
573 case bitc::ATTR_KIND_ALWAYS_INLINE:
574 return Attribute::AlwaysInline;
575 case bitc::ATTR_KIND_BUILTIN:
576 return Attribute::Builtin;
577 case bitc::ATTR_KIND_BY_VAL:
578 return Attribute::ByVal;
579 case bitc::ATTR_KIND_IN_ALLOCA:
580 return Attribute::InAlloca;
581 case bitc::ATTR_KIND_COLD:
582 return Attribute::Cold;
583 case bitc::ATTR_KIND_INLINE_HINT:
584 return Attribute::InlineHint;
585 case bitc::ATTR_KIND_IN_REG:
586 return Attribute::InReg;
587 case bitc::ATTR_KIND_JUMP_TABLE:
588 return Attribute::JumpTable;
589 case bitc::ATTR_KIND_MIN_SIZE:
590 return Attribute::MinSize;
591 case bitc::ATTR_KIND_NAKED:
592 return Attribute::Naked;
593 case bitc::ATTR_KIND_NEST:
594 return Attribute::Nest;
595 case bitc::ATTR_KIND_NO_ALIAS:
596 return Attribute::NoAlias;
597 case bitc::ATTR_KIND_NO_BUILTIN:
598 return Attribute::NoBuiltin;
599 case bitc::ATTR_KIND_NO_CAPTURE:
600 return Attribute::NoCapture;
601 case bitc::ATTR_KIND_NO_DUPLICATE:
602 return Attribute::NoDuplicate;
603 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
604 return Attribute::NoImplicitFloat;
605 case bitc::ATTR_KIND_NO_INLINE:
606 return Attribute::NoInline;
607 case bitc::ATTR_KIND_NON_LAZY_BIND:
608 return Attribute::NonLazyBind;
609 case bitc::ATTR_KIND_NON_NULL:
610 return Attribute::NonNull;
611 case bitc::ATTR_KIND_DEREFERENCEABLE:
612 return Attribute::Dereferenceable;
613 case bitc::ATTR_KIND_NO_RED_ZONE:
614 return Attribute::NoRedZone;
615 case bitc::ATTR_KIND_NO_RETURN:
616 return Attribute::NoReturn;
617 case bitc::ATTR_KIND_NO_UNWIND:
618 return Attribute::NoUnwind;
619 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
620 return Attribute::OptimizeForSize;
621 case bitc::ATTR_KIND_OPTIMIZE_NONE:
622 return Attribute::OptimizeNone;
623 case bitc::ATTR_KIND_READ_NONE:
624 return Attribute::ReadNone;
625 case bitc::ATTR_KIND_READ_ONLY:
626 return Attribute::ReadOnly;
627 case bitc::ATTR_KIND_RETURNED:
628 return Attribute::Returned;
629 case bitc::ATTR_KIND_RETURNS_TWICE:
630 return Attribute::ReturnsTwice;
631 case bitc::ATTR_KIND_S_EXT:
632 return Attribute::SExt;
633 case bitc::ATTR_KIND_STACK_ALIGNMENT:
634 return Attribute::StackAlignment;
635 case bitc::ATTR_KIND_STACK_PROTECT:
636 return Attribute::StackProtect;
637 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
638 return Attribute::StackProtectReq;
639 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
640 return Attribute::StackProtectStrong;
641 case bitc::ATTR_KIND_STRUCT_RET:
642 return Attribute::StructRet;
643 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
644 return Attribute::SanitizeAddress;
645 case bitc::ATTR_KIND_SANITIZE_THREAD:
646 return Attribute::SanitizeThread;
647 case bitc::ATTR_KIND_SANITIZE_MEMORY:
648 return Attribute::SanitizeMemory;
649 case bitc::ATTR_KIND_UW_TABLE:
650 return Attribute::UWTable;
651 case bitc::ATTR_KIND_Z_EXT:
652 return Attribute::ZExt;
656 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
657 Attribute::AttrKind *Kind) {
658 *Kind = GetAttrFromCode(Code);
659 if (*Kind == Attribute::None)
660 return Error(BitcodeError::InvalidValue);
661 return std::error_code();
664 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
665 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
666 return Error(BitcodeError::InvalidRecord);
668 if (!MAttributeGroups.empty())
669 return Error(BitcodeError::InvalidMultipleBlocks);
671 SmallVector<uint64_t, 64> Record;
673 // Read all the records.
675 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
677 switch (Entry.Kind) {
678 case BitstreamEntry::SubBlock: // Handled for us already.
679 case BitstreamEntry::Error:
680 return Error(BitcodeError::MalformedBlock);
681 case BitstreamEntry::EndBlock:
682 return std::error_code();
683 case BitstreamEntry::Record:
684 // The interesting case.
690 switch (Stream.readRecord(Entry.ID, Record)) {
691 default: // Default behavior: ignore.
693 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
694 if (Record.size() < 3)
695 return Error(BitcodeError::InvalidRecord);
697 uint64_t GrpID = Record[0];
698 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
701 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
702 if (Record[i] == 0) { // Enum attribute
703 Attribute::AttrKind Kind;
704 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
707 B.addAttribute(Kind);
708 } else if (Record[i] == 1) { // Integer attribute
709 Attribute::AttrKind Kind;
710 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
712 if (Kind == Attribute::Alignment)
713 B.addAlignmentAttr(Record[++i]);
714 else if (Kind == Attribute::StackAlignment)
715 B.addStackAlignmentAttr(Record[++i]);
716 else if (Kind == Attribute::Dereferenceable)
717 B.addDereferenceableAttr(Record[++i]);
718 } else { // String attribute
719 assert((Record[i] == 3 || Record[i] == 4) &&
720 "Invalid attribute group entry");
721 bool HasValue = (Record[i++] == 4);
722 SmallString<64> KindStr;
723 SmallString<64> ValStr;
725 while (Record[i] != 0 && i != e)
726 KindStr += Record[i++];
727 assert(Record[i] == 0 && "Kind string not null terminated");
730 // Has a value associated with it.
731 ++i; // Skip the '0' that terminates the "kind" string.
732 while (Record[i] != 0 && i != e)
733 ValStr += Record[i++];
734 assert(Record[i] == 0 && "Value string not null terminated");
737 B.addAttribute(KindStr.str(), ValStr.str());
741 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
748 std::error_code BitcodeReader::ParseTypeTable() {
749 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
750 return Error(BitcodeError::InvalidRecord);
752 return ParseTypeTableBody();
755 std::error_code BitcodeReader::ParseTypeTableBody() {
756 if (!TypeList.empty())
757 return Error(BitcodeError::InvalidMultipleBlocks);
759 SmallVector<uint64_t, 64> Record;
760 unsigned NumRecords = 0;
762 SmallString<64> TypeName;
764 // Read all the records for this type table.
766 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
768 switch (Entry.Kind) {
769 case BitstreamEntry::SubBlock: // Handled for us already.
770 case BitstreamEntry::Error:
771 return Error(BitcodeError::MalformedBlock);
772 case BitstreamEntry::EndBlock:
773 if (NumRecords != TypeList.size())
774 return Error(BitcodeError::MalformedBlock);
775 return std::error_code();
776 case BitstreamEntry::Record:
777 // The interesting case.
783 Type *ResultTy = nullptr;
784 switch (Stream.readRecord(Entry.ID, Record)) {
786 return Error(BitcodeError::InvalidValue);
787 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
788 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
789 // type list. This allows us to reserve space.
790 if (Record.size() < 1)
791 return Error(BitcodeError::InvalidRecord);
792 TypeList.resize(Record[0]);
794 case bitc::TYPE_CODE_VOID: // VOID
795 ResultTy = Type::getVoidTy(Context);
797 case bitc::TYPE_CODE_HALF: // HALF
798 ResultTy = Type::getHalfTy(Context);
800 case bitc::TYPE_CODE_FLOAT: // FLOAT
801 ResultTy = Type::getFloatTy(Context);
803 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
804 ResultTy = Type::getDoubleTy(Context);
806 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
807 ResultTy = Type::getX86_FP80Ty(Context);
809 case bitc::TYPE_CODE_FP128: // FP128
810 ResultTy = Type::getFP128Ty(Context);
812 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
813 ResultTy = Type::getPPC_FP128Ty(Context);
815 case bitc::TYPE_CODE_LABEL: // LABEL
816 ResultTy = Type::getLabelTy(Context);
818 case bitc::TYPE_CODE_METADATA: // METADATA
819 ResultTy = Type::getMetadataTy(Context);
821 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
822 ResultTy = Type::getX86_MMXTy(Context);
824 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
825 if (Record.size() < 1)
826 return Error(BitcodeError::InvalidRecord);
828 ResultTy = IntegerType::get(Context, Record[0]);
830 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
831 // [pointee type, address space]
832 if (Record.size() < 1)
833 return Error(BitcodeError::InvalidRecord);
834 unsigned AddressSpace = 0;
835 if (Record.size() == 2)
836 AddressSpace = Record[1];
837 ResultTy = getTypeByID(Record[0]);
839 return Error(BitcodeError::InvalidType);
840 ResultTy = PointerType::get(ResultTy, AddressSpace);
843 case bitc::TYPE_CODE_FUNCTION_OLD: {
844 // FIXME: attrid is dead, remove it in LLVM 4.0
845 // FUNCTION: [vararg, attrid, retty, paramty x N]
846 if (Record.size() < 3)
847 return Error(BitcodeError::InvalidRecord);
848 SmallVector<Type*, 8> ArgTys;
849 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
850 if (Type *T = getTypeByID(Record[i]))
856 ResultTy = getTypeByID(Record[2]);
857 if (!ResultTy || ArgTys.size() < Record.size()-3)
858 return Error(BitcodeError::InvalidType);
860 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
863 case bitc::TYPE_CODE_FUNCTION: {
864 // FUNCTION: [vararg, retty, paramty x N]
865 if (Record.size() < 2)
866 return Error(BitcodeError::InvalidRecord);
867 SmallVector<Type*, 8> ArgTys;
868 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
869 if (Type *T = getTypeByID(Record[i]))
875 ResultTy = getTypeByID(Record[1]);
876 if (!ResultTy || ArgTys.size() < Record.size()-2)
877 return Error(BitcodeError::InvalidType);
879 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
882 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
883 if (Record.size() < 1)
884 return Error(BitcodeError::InvalidRecord);
885 SmallVector<Type*, 8> EltTys;
886 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
887 if (Type *T = getTypeByID(Record[i]))
892 if (EltTys.size() != Record.size()-1)
893 return Error(BitcodeError::InvalidType);
894 ResultTy = StructType::get(Context, EltTys, Record[0]);
897 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
898 if (ConvertToString(Record, 0, TypeName))
899 return Error(BitcodeError::InvalidRecord);
902 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
903 if (Record.size() < 1)
904 return Error(BitcodeError::InvalidRecord);
906 if (NumRecords >= TypeList.size())
907 return Error(BitcodeError::InvalidTYPETable);
909 // Check to see if this was forward referenced, if so fill in the temp.
910 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
912 Res->setName(TypeName);
913 TypeList[NumRecords] = nullptr;
914 } else // Otherwise, create a new struct.
915 Res = StructType::create(Context, TypeName);
918 SmallVector<Type*, 8> EltTys;
919 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
920 if (Type *T = getTypeByID(Record[i]))
925 if (EltTys.size() != Record.size()-1)
926 return Error(BitcodeError::InvalidRecord);
927 Res->setBody(EltTys, Record[0]);
931 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
932 if (Record.size() != 1)
933 return Error(BitcodeError::InvalidRecord);
935 if (NumRecords >= TypeList.size())
936 return Error(BitcodeError::InvalidTYPETable);
938 // Check to see if this was forward referenced, if so fill in the temp.
939 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
941 Res->setName(TypeName);
942 TypeList[NumRecords] = nullptr;
943 } else // Otherwise, create a new struct with no body.
944 Res = StructType::create(Context, TypeName);
949 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
950 if (Record.size() < 2)
951 return Error(BitcodeError::InvalidRecord);
952 if ((ResultTy = getTypeByID(Record[1])))
953 ResultTy = ArrayType::get(ResultTy, Record[0]);
955 return Error(BitcodeError::InvalidType);
957 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
958 if (Record.size() < 2)
959 return Error(BitcodeError::InvalidRecord);
960 if ((ResultTy = getTypeByID(Record[1])))
961 ResultTy = VectorType::get(ResultTy, Record[0]);
963 return Error(BitcodeError::InvalidType);
967 if (NumRecords >= TypeList.size())
968 return Error(BitcodeError::InvalidTYPETable);
969 assert(ResultTy && "Didn't read a type?");
970 assert(!TypeList[NumRecords] && "Already read type?");
971 TypeList[NumRecords++] = ResultTy;
975 std::error_code BitcodeReader::ParseValueSymbolTable() {
976 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
977 return Error(BitcodeError::InvalidRecord);
979 SmallVector<uint64_t, 64> Record;
981 // Read all the records for this value table.
982 SmallString<128> ValueName;
984 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
986 switch (Entry.Kind) {
987 case BitstreamEntry::SubBlock: // Handled for us already.
988 case BitstreamEntry::Error:
989 return Error(BitcodeError::MalformedBlock);
990 case BitstreamEntry::EndBlock:
991 return std::error_code();
992 case BitstreamEntry::Record:
993 // The interesting case.
999 switch (Stream.readRecord(Entry.ID, Record)) {
1000 default: // Default behavior: unknown type.
1002 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1003 if (ConvertToString(Record, 1, ValueName))
1004 return Error(BitcodeError::InvalidRecord);
1005 unsigned ValueID = Record[0];
1006 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1007 return Error(BitcodeError::InvalidRecord);
1008 Value *V = ValueList[ValueID];
1010 V->setName(StringRef(ValueName.data(), ValueName.size()));
1014 case bitc::VST_CODE_BBENTRY: {
1015 if (ConvertToString(Record, 1, ValueName))
1016 return Error(BitcodeError::InvalidRecord);
1017 BasicBlock *BB = getBasicBlock(Record[0]);
1019 return Error(BitcodeError::InvalidRecord);
1021 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1029 std::error_code BitcodeReader::ParseMetadata() {
1030 unsigned NextMDValueNo = MDValueList.size();
1032 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1033 return Error(BitcodeError::InvalidRecord);
1035 SmallVector<uint64_t, 64> Record;
1037 // Read all the records.
1039 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1041 switch (Entry.Kind) {
1042 case BitstreamEntry::SubBlock: // Handled for us already.
1043 case BitstreamEntry::Error:
1044 return Error(BitcodeError::MalformedBlock);
1045 case BitstreamEntry::EndBlock:
1046 return std::error_code();
1047 case BitstreamEntry::Record:
1048 // The interesting case.
1052 bool IsFunctionLocal = false;
1055 unsigned Code = Stream.readRecord(Entry.ID, Record);
1057 default: // Default behavior: ignore.
1059 case bitc::METADATA_NAME: {
1060 // Read name of the named metadata.
1061 SmallString<8> Name(Record.begin(), Record.end());
1063 Code = Stream.ReadCode();
1065 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1066 unsigned NextBitCode = Stream.readRecord(Code, Record);
1067 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1069 // Read named metadata elements.
1070 unsigned Size = Record.size();
1071 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1072 for (unsigned i = 0; i != Size; ++i) {
1073 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1075 return Error(BitcodeError::InvalidRecord);
1076 NMD->addOperand(MD);
1080 case bitc::METADATA_FN_NODE:
1081 IsFunctionLocal = true;
1083 case bitc::METADATA_NODE: {
1084 if (Record.size() % 2 == 1)
1085 return Error(BitcodeError::InvalidRecord);
1087 unsigned Size = Record.size();
1088 SmallVector<Value*, 8> Elts;
1089 for (unsigned i = 0; i != Size; i += 2) {
1090 Type *Ty = getTypeByID(Record[i]);
1092 return Error(BitcodeError::InvalidRecord);
1093 if (Ty->isMetadataTy())
1094 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1095 else if (!Ty->isVoidTy())
1096 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1098 Elts.push_back(nullptr);
1100 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1101 IsFunctionLocal = false;
1102 MDValueList.AssignValue(V, NextMDValueNo++);
1105 case bitc::METADATA_STRING: {
1106 std::string String(Record.begin(), Record.end());
1107 llvm::UpgradeMDStringConstant(String);
1108 Value *V = MDString::get(Context, String);
1109 MDValueList.AssignValue(V, NextMDValueNo++);
1112 case bitc::METADATA_KIND: {
1113 if (Record.size() < 2)
1114 return Error(BitcodeError::InvalidRecord);
1116 unsigned Kind = Record[0];
1117 SmallString<8> Name(Record.begin()+1, Record.end());
1119 unsigned NewKind = TheModule->getMDKindID(Name.str());
1120 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1121 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1128 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1129 /// the LSB for dense VBR encoding.
1130 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1135 // There is no such thing as -0 with integers. "-0" really means MININT.
1139 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1140 /// values and aliases that we can.
1141 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1142 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1143 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1144 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1146 GlobalInitWorklist.swap(GlobalInits);
1147 AliasInitWorklist.swap(AliasInits);
1148 FunctionPrefixWorklist.swap(FunctionPrefixes);
1150 while (!GlobalInitWorklist.empty()) {
1151 unsigned ValID = GlobalInitWorklist.back().second;
1152 if (ValID >= ValueList.size()) {
1153 // Not ready to resolve this yet, it requires something later in the file.
1154 GlobalInits.push_back(GlobalInitWorklist.back());
1156 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1157 GlobalInitWorklist.back().first->setInitializer(C);
1159 return Error(BitcodeError::ExpectedConstant);
1161 GlobalInitWorklist.pop_back();
1164 while (!AliasInitWorklist.empty()) {
1165 unsigned ValID = AliasInitWorklist.back().second;
1166 if (ValID >= ValueList.size()) {
1167 AliasInits.push_back(AliasInitWorklist.back());
1169 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1170 AliasInitWorklist.back().first->setAliasee(C);
1172 return Error(BitcodeError::ExpectedConstant);
1174 AliasInitWorklist.pop_back();
1177 while (!FunctionPrefixWorklist.empty()) {
1178 unsigned ValID = FunctionPrefixWorklist.back().second;
1179 if (ValID >= ValueList.size()) {
1180 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1182 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1183 FunctionPrefixWorklist.back().first->setPrefixData(C);
1185 return Error(BitcodeError::ExpectedConstant);
1187 FunctionPrefixWorklist.pop_back();
1190 return std::error_code();
1193 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1194 SmallVector<uint64_t, 8> Words(Vals.size());
1195 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1196 BitcodeReader::decodeSignRotatedValue);
1198 return APInt(TypeBits, Words);
1201 std::error_code BitcodeReader::ParseConstants() {
1202 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1203 return Error(BitcodeError::InvalidRecord);
1205 SmallVector<uint64_t, 64> Record;
1207 // Read all the records for this value table.
1208 Type *CurTy = Type::getInt32Ty(Context);
1209 unsigned NextCstNo = ValueList.size();
1211 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1213 switch (Entry.Kind) {
1214 case BitstreamEntry::SubBlock: // Handled for us already.
1215 case BitstreamEntry::Error:
1216 return Error(BitcodeError::MalformedBlock);
1217 case BitstreamEntry::EndBlock:
1218 if (NextCstNo != ValueList.size())
1219 return Error(BitcodeError::InvalidConstantReference);
1221 // Once all the constants have been read, go through and resolve forward
1223 ValueList.ResolveConstantForwardRefs();
1224 return std::error_code();
1225 case BitstreamEntry::Record:
1226 // The interesting case.
1233 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1235 default: // Default behavior: unknown constant
1236 case bitc::CST_CODE_UNDEF: // UNDEF
1237 V = UndefValue::get(CurTy);
1239 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1241 return Error(BitcodeError::InvalidRecord);
1242 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1243 return Error(BitcodeError::InvalidRecord);
1244 CurTy = TypeList[Record[0]];
1245 continue; // Skip the ValueList manipulation.
1246 case bitc::CST_CODE_NULL: // NULL
1247 V = Constant::getNullValue(CurTy);
1249 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1250 if (!CurTy->isIntegerTy() || Record.empty())
1251 return Error(BitcodeError::InvalidRecord);
1252 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1254 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1255 if (!CurTy->isIntegerTy() || Record.empty())
1256 return Error(BitcodeError::InvalidRecord);
1258 APInt VInt = ReadWideAPInt(Record,
1259 cast<IntegerType>(CurTy)->getBitWidth());
1260 V = ConstantInt::get(Context, VInt);
1264 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1266 return Error(BitcodeError::InvalidRecord);
1267 if (CurTy->isHalfTy())
1268 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1269 APInt(16, (uint16_t)Record[0])));
1270 else if (CurTy->isFloatTy())
1271 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1272 APInt(32, (uint32_t)Record[0])));
1273 else if (CurTy->isDoubleTy())
1274 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1275 APInt(64, Record[0])));
1276 else if (CurTy->isX86_FP80Ty()) {
1277 // Bits are not stored the same way as a normal i80 APInt, compensate.
1278 uint64_t Rearrange[2];
1279 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1280 Rearrange[1] = Record[0] >> 48;
1281 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1282 APInt(80, Rearrange)));
1283 } else if (CurTy->isFP128Ty())
1284 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1285 APInt(128, Record)));
1286 else if (CurTy->isPPC_FP128Ty())
1287 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1288 APInt(128, Record)));
1290 V = UndefValue::get(CurTy);
1294 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1296 return Error(BitcodeError::InvalidRecord);
1298 unsigned Size = Record.size();
1299 SmallVector<Constant*, 16> Elts;
1301 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1302 for (unsigned i = 0; i != Size; ++i)
1303 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1304 STy->getElementType(i)));
1305 V = ConstantStruct::get(STy, Elts);
1306 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1307 Type *EltTy = ATy->getElementType();
1308 for (unsigned i = 0; i != Size; ++i)
1309 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1310 V = ConstantArray::get(ATy, Elts);
1311 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1312 Type *EltTy = VTy->getElementType();
1313 for (unsigned i = 0; i != Size; ++i)
1314 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1315 V = ConstantVector::get(Elts);
1317 V = UndefValue::get(CurTy);
1321 case bitc::CST_CODE_STRING: // STRING: [values]
1322 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1324 return Error(BitcodeError::InvalidRecord);
1326 SmallString<16> Elts(Record.begin(), Record.end());
1327 V = ConstantDataArray::getString(Context, Elts,
1328 BitCode == bitc::CST_CODE_CSTRING);
1331 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1333 return Error(BitcodeError::InvalidRecord);
1335 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1336 unsigned Size = Record.size();
1338 if (EltTy->isIntegerTy(8)) {
1339 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1340 if (isa<VectorType>(CurTy))
1341 V = ConstantDataVector::get(Context, Elts);
1343 V = ConstantDataArray::get(Context, Elts);
1344 } else if (EltTy->isIntegerTy(16)) {
1345 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1346 if (isa<VectorType>(CurTy))
1347 V = ConstantDataVector::get(Context, Elts);
1349 V = ConstantDataArray::get(Context, Elts);
1350 } else if (EltTy->isIntegerTy(32)) {
1351 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1352 if (isa<VectorType>(CurTy))
1353 V = ConstantDataVector::get(Context, Elts);
1355 V = ConstantDataArray::get(Context, Elts);
1356 } else if (EltTy->isIntegerTy(64)) {
1357 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1358 if (isa<VectorType>(CurTy))
1359 V = ConstantDataVector::get(Context, Elts);
1361 V = ConstantDataArray::get(Context, Elts);
1362 } else if (EltTy->isFloatTy()) {
1363 SmallVector<float, 16> Elts(Size);
1364 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1365 if (isa<VectorType>(CurTy))
1366 V = ConstantDataVector::get(Context, Elts);
1368 V = ConstantDataArray::get(Context, Elts);
1369 } else if (EltTy->isDoubleTy()) {
1370 SmallVector<double, 16> Elts(Size);
1371 std::transform(Record.begin(), Record.end(), Elts.begin(),
1373 if (isa<VectorType>(CurTy))
1374 V = ConstantDataVector::get(Context, Elts);
1376 V = ConstantDataArray::get(Context, Elts);
1378 return Error(BitcodeError::InvalidTypeForValue);
1383 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1384 if (Record.size() < 3)
1385 return Error(BitcodeError::InvalidRecord);
1386 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1388 V = UndefValue::get(CurTy); // Unknown binop.
1390 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1391 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1393 if (Record.size() >= 4) {
1394 if (Opc == Instruction::Add ||
1395 Opc == Instruction::Sub ||
1396 Opc == Instruction::Mul ||
1397 Opc == Instruction::Shl) {
1398 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1399 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1400 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1401 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1402 } else if (Opc == Instruction::SDiv ||
1403 Opc == Instruction::UDiv ||
1404 Opc == Instruction::LShr ||
1405 Opc == Instruction::AShr) {
1406 if (Record[3] & (1 << bitc::PEO_EXACT))
1407 Flags |= SDivOperator::IsExact;
1410 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1414 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1415 if (Record.size() < 3)
1416 return Error(BitcodeError::InvalidRecord);
1417 int Opc = GetDecodedCastOpcode(Record[0]);
1419 V = UndefValue::get(CurTy); // Unknown cast.
1421 Type *OpTy = getTypeByID(Record[1]);
1423 return Error(BitcodeError::InvalidRecord);
1424 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1425 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1426 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1430 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1431 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1432 if (Record.size() & 1)
1433 return Error(BitcodeError::InvalidRecord);
1434 SmallVector<Constant*, 16> Elts;
1435 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1436 Type *ElTy = getTypeByID(Record[i]);
1438 return Error(BitcodeError::InvalidRecord);
1439 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1441 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1442 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1444 bitc::CST_CODE_CE_INBOUNDS_GEP);
1447 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1448 if (Record.size() < 3)
1449 return Error(BitcodeError::InvalidRecord);
1451 Type *SelectorTy = Type::getInt1Ty(Context);
1453 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1454 // vector. Otherwise, it must be a single bit.
1455 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1456 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1457 VTy->getNumElements());
1459 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1461 ValueList.getConstantFwdRef(Record[1],CurTy),
1462 ValueList.getConstantFwdRef(Record[2],CurTy));
1465 case bitc::CST_CODE_CE_EXTRACTELT
1466 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1467 if (Record.size() < 3)
1468 return Error(BitcodeError::InvalidRecord);
1470 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1472 return Error(BitcodeError::InvalidRecord);
1473 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1474 Constant *Op1 = nullptr;
1475 if (Record.size() == 4) {
1476 Type *IdxTy = getTypeByID(Record[2]);
1478 return Error(BitcodeError::InvalidRecord);
1479 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1480 } else // TODO: Remove with llvm 4.0
1481 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1483 return Error(BitcodeError::InvalidRecord);
1484 V = ConstantExpr::getExtractElement(Op0, Op1);
1487 case bitc::CST_CODE_CE_INSERTELT
1488 : { // CE_INSERTELT: [opval, opval, opty, opval]
1489 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1490 if (Record.size() < 3 || !OpTy)
1491 return Error(BitcodeError::InvalidRecord);
1492 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1493 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1494 OpTy->getElementType());
1495 Constant *Op2 = nullptr;
1496 if (Record.size() == 4) {
1497 Type *IdxTy = getTypeByID(Record[2]);
1499 return Error(BitcodeError::InvalidRecord);
1500 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1501 } else // TODO: Remove with llvm 4.0
1502 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1504 return Error(BitcodeError::InvalidRecord);
1505 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1508 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1509 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1510 if (Record.size() < 3 || !OpTy)
1511 return Error(BitcodeError::InvalidRecord);
1512 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1513 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1514 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1515 OpTy->getNumElements());
1516 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1517 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1520 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1521 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1523 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1524 if (Record.size() < 4 || !RTy || !OpTy)
1525 return Error(BitcodeError::InvalidRecord);
1526 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1527 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1528 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1529 RTy->getNumElements());
1530 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1531 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1534 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1535 if (Record.size() < 4)
1536 return Error(BitcodeError::InvalidRecord);
1537 Type *OpTy = getTypeByID(Record[0]);
1539 return Error(BitcodeError::InvalidRecord);
1540 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1541 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1543 if (OpTy->isFPOrFPVectorTy())
1544 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1546 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1549 // This maintains backward compatibility, pre-asm dialect keywords.
1550 // FIXME: Remove with the 4.0 release.
1551 case bitc::CST_CODE_INLINEASM_OLD: {
1552 if (Record.size() < 2)
1553 return Error(BitcodeError::InvalidRecord);
1554 std::string AsmStr, ConstrStr;
1555 bool HasSideEffects = Record[0] & 1;
1556 bool IsAlignStack = Record[0] >> 1;
1557 unsigned AsmStrSize = Record[1];
1558 if (2+AsmStrSize >= Record.size())
1559 return Error(BitcodeError::InvalidRecord);
1560 unsigned ConstStrSize = Record[2+AsmStrSize];
1561 if (3+AsmStrSize+ConstStrSize > Record.size())
1562 return Error(BitcodeError::InvalidRecord);
1564 for (unsigned i = 0; i != AsmStrSize; ++i)
1565 AsmStr += (char)Record[2+i];
1566 for (unsigned i = 0; i != ConstStrSize; ++i)
1567 ConstrStr += (char)Record[3+AsmStrSize+i];
1568 PointerType *PTy = cast<PointerType>(CurTy);
1569 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1570 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1573 // This version adds support for the asm dialect keywords (e.g.,
1575 case bitc::CST_CODE_INLINEASM: {
1576 if (Record.size() < 2)
1577 return Error(BitcodeError::InvalidRecord);
1578 std::string AsmStr, ConstrStr;
1579 bool HasSideEffects = Record[0] & 1;
1580 bool IsAlignStack = (Record[0] >> 1) & 1;
1581 unsigned AsmDialect = Record[0] >> 2;
1582 unsigned AsmStrSize = Record[1];
1583 if (2+AsmStrSize >= Record.size())
1584 return Error(BitcodeError::InvalidRecord);
1585 unsigned ConstStrSize = Record[2+AsmStrSize];
1586 if (3+AsmStrSize+ConstStrSize > Record.size())
1587 return Error(BitcodeError::InvalidRecord);
1589 for (unsigned i = 0; i != AsmStrSize; ++i)
1590 AsmStr += (char)Record[2+i];
1591 for (unsigned i = 0; i != ConstStrSize; ++i)
1592 ConstrStr += (char)Record[3+AsmStrSize+i];
1593 PointerType *PTy = cast<PointerType>(CurTy);
1594 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1595 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1596 InlineAsm::AsmDialect(AsmDialect));
1599 case bitc::CST_CODE_BLOCKADDRESS:{
1600 if (Record.size() < 3)
1601 return Error(BitcodeError::InvalidRecord);
1602 Type *FnTy = getTypeByID(Record[0]);
1604 return Error(BitcodeError::InvalidRecord);
1606 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1608 return Error(BitcodeError::InvalidRecord);
1610 // Don't let Fn get dematerialized.
1611 BlockAddressesTaken.insert(Fn);
1613 // If the function is already parsed we can insert the block address right
1616 unsigned BBID = Record[2];
1618 // Invalid reference to entry block.
1619 return Error(BitcodeError::InvalidID);
1621 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1622 for (size_t I = 0, E = BBID; I != E; ++I) {
1624 return Error(BitcodeError::InvalidID);
1629 // Otherwise insert a placeholder and remember it so it can be inserted
1630 // when the function is parsed.
1631 BB = BasicBlock::Create(Context);
1632 BasicBlockFwdRefs[Fn].emplace_back(BBID, BB);
1634 V = BlockAddress::get(Fn, BB);
1639 ValueList.AssignValue(V, NextCstNo);
1644 std::error_code BitcodeReader::ParseUseLists() {
1645 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1646 return Error(BitcodeError::InvalidRecord);
1648 // Read all the records.
1649 SmallVector<uint64_t, 64> Record;
1651 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1653 switch (Entry.Kind) {
1654 case BitstreamEntry::SubBlock: // Handled for us already.
1655 case BitstreamEntry::Error:
1656 return Error(BitcodeError::MalformedBlock);
1657 case BitstreamEntry::EndBlock:
1658 return std::error_code();
1659 case BitstreamEntry::Record:
1660 // The interesting case.
1664 // Read a use list record.
1667 switch (Stream.readRecord(Entry.ID, Record)) {
1668 default: // Default behavior: unknown type.
1670 case bitc::USELIST_CODE_BB:
1673 case bitc::USELIST_CODE_DEFAULT: {
1674 unsigned RecordLength = Record.size();
1675 if (RecordLength < 3)
1676 // Records should have at least an ID and two indexes.
1677 return Error(BitcodeError::InvalidRecord);
1678 unsigned ID = Record.back();
1683 assert(ID < FunctionBBs.size() && "Basic block not found");
1684 V = FunctionBBs[ID];
1687 unsigned NumUses = 0;
1688 SmallDenseMap<const Use *, unsigned, 16> Order;
1689 for (const Use &U : V->uses()) {
1690 if (NumUses > Record.size())
1692 Order[&U] = Record[NumUses++];
1694 if (Order.size() != Record.size() || NumUses > Record.size())
1695 // Mismatches can happen if the functions are being materialized lazily
1696 // (out-of-order), or a value has been upgraded.
1699 V->sortUseList([&](const Use &L, const Use &R) {
1700 return Order.lookup(&L) < Order.lookup(&R);
1708 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1709 /// remember where it is and then skip it. This lets us lazily deserialize the
1711 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1712 // Get the function we are talking about.
1713 if (FunctionsWithBodies.empty())
1714 return Error(BitcodeError::InsufficientFunctionProtos);
1716 Function *Fn = FunctionsWithBodies.back();
1717 FunctionsWithBodies.pop_back();
1719 // Save the current stream state.
1720 uint64_t CurBit = Stream.GetCurrentBitNo();
1721 DeferredFunctionInfo[Fn] = CurBit;
1723 // Skip over the function block for now.
1724 if (Stream.SkipBlock())
1725 return Error(BitcodeError::InvalidRecord);
1726 return std::error_code();
1729 std::error_code BitcodeReader::GlobalCleanup() {
1730 // Patch the initializers for globals and aliases up.
1731 ResolveGlobalAndAliasInits();
1732 if (!GlobalInits.empty() || !AliasInits.empty())
1733 return Error(BitcodeError::MalformedGlobalInitializerSet);
1735 // Look for intrinsic functions which need to be upgraded at some point
1736 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1739 if (UpgradeIntrinsicFunction(FI, NewFn))
1740 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1743 // Look for global variables which need to be renamed.
1744 for (Module::global_iterator
1745 GI = TheModule->global_begin(), GE = TheModule->global_end();
1747 GlobalVariable *GV = GI++;
1748 UpgradeGlobalVariable(GV);
1751 // Force deallocation of memory for these vectors to favor the client that
1752 // want lazy deserialization.
1753 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1754 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1755 return std::error_code();
1758 std::error_code BitcodeReader::ParseModule(bool Resume) {
1760 Stream.JumpToBit(NextUnreadBit);
1761 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1762 return Error(BitcodeError::InvalidRecord);
1764 SmallVector<uint64_t, 64> Record;
1765 std::vector<std::string> SectionTable;
1766 std::vector<std::string> GCTable;
1768 // Read all the records for this module.
1770 BitstreamEntry Entry = Stream.advance();
1772 switch (Entry.Kind) {
1773 case BitstreamEntry::Error:
1774 return Error(BitcodeError::MalformedBlock);
1775 case BitstreamEntry::EndBlock:
1776 return GlobalCleanup();
1778 case BitstreamEntry::SubBlock:
1780 default: // Skip unknown content.
1781 if (Stream.SkipBlock())
1782 return Error(BitcodeError::InvalidRecord);
1784 case bitc::BLOCKINFO_BLOCK_ID:
1785 if (Stream.ReadBlockInfoBlock())
1786 return Error(BitcodeError::MalformedBlock);
1788 case bitc::PARAMATTR_BLOCK_ID:
1789 if (std::error_code EC = ParseAttributeBlock())
1792 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1793 if (std::error_code EC = ParseAttributeGroupBlock())
1796 case bitc::TYPE_BLOCK_ID_NEW:
1797 if (std::error_code EC = ParseTypeTable())
1800 case bitc::VALUE_SYMTAB_BLOCK_ID:
1801 if (std::error_code EC = ParseValueSymbolTable())
1803 SeenValueSymbolTable = true;
1805 case bitc::CONSTANTS_BLOCK_ID:
1806 if (std::error_code EC = ParseConstants())
1808 if (std::error_code EC = ResolveGlobalAndAliasInits())
1811 case bitc::METADATA_BLOCK_ID:
1812 if (std::error_code EC = ParseMetadata())
1815 case bitc::FUNCTION_BLOCK_ID:
1816 // If this is the first function body we've seen, reverse the
1817 // FunctionsWithBodies list.
1818 if (!SeenFirstFunctionBody) {
1819 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1820 if (std::error_code EC = GlobalCleanup())
1822 SeenFirstFunctionBody = true;
1825 if (std::error_code EC = RememberAndSkipFunctionBody())
1827 // For streaming bitcode, suspend parsing when we reach the function
1828 // bodies. Subsequent materialization calls will resume it when
1829 // necessary. For streaming, the function bodies must be at the end of
1830 // the bitcode. If the bitcode file is old, the symbol table will be
1831 // at the end instead and will not have been seen yet. In this case,
1832 // just finish the parse now.
1833 if (LazyStreamer && SeenValueSymbolTable) {
1834 NextUnreadBit = Stream.GetCurrentBitNo();
1835 return std::error_code();
1838 case bitc::USELIST_BLOCK_ID:
1839 if (std::error_code EC = ParseUseLists())
1845 case BitstreamEntry::Record:
1846 // The interesting case.
1852 switch (Stream.readRecord(Entry.ID, Record)) {
1853 default: break; // Default behavior, ignore unknown content.
1854 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1855 if (Record.size() < 1)
1856 return Error(BitcodeError::InvalidRecord);
1857 // Only version #0 and #1 are supported so far.
1858 unsigned module_version = Record[0];
1859 switch (module_version) {
1861 return Error(BitcodeError::InvalidValue);
1863 UseRelativeIDs = false;
1866 UseRelativeIDs = true;
1871 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1873 if (ConvertToString(Record, 0, S))
1874 return Error(BitcodeError::InvalidRecord);
1875 TheModule->setTargetTriple(S);
1878 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1880 if (ConvertToString(Record, 0, S))
1881 return Error(BitcodeError::InvalidRecord);
1882 TheModule->setDataLayout(S);
1885 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1887 if (ConvertToString(Record, 0, S))
1888 return Error(BitcodeError::InvalidRecord);
1889 TheModule->setModuleInlineAsm(S);
1892 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1893 // FIXME: Remove in 4.0.
1895 if (ConvertToString(Record, 0, S))
1896 return Error(BitcodeError::InvalidRecord);
1900 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1902 if (ConvertToString(Record, 0, S))
1903 return Error(BitcodeError::InvalidRecord);
1904 SectionTable.push_back(S);
1907 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1909 if (ConvertToString(Record, 0, S))
1910 return Error(BitcodeError::InvalidRecord);
1911 GCTable.push_back(S);
1914 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1915 if (Record.size() < 2)
1916 return Error(BitcodeError::InvalidRecord);
1917 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1918 unsigned ComdatNameSize = Record[1];
1919 std::string ComdatName;
1920 ComdatName.reserve(ComdatNameSize);
1921 for (unsigned i = 0; i != ComdatNameSize; ++i)
1922 ComdatName += (char)Record[2 + i];
1923 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1924 C->setSelectionKind(SK);
1925 ComdatList.push_back(C);
1928 // GLOBALVAR: [pointer type, isconst, initid,
1929 // linkage, alignment, section, visibility, threadlocal,
1930 // unnamed_addr, dllstorageclass]
1931 case bitc::MODULE_CODE_GLOBALVAR: {
1932 if (Record.size() < 6)
1933 return Error(BitcodeError::InvalidRecord);
1934 Type *Ty = getTypeByID(Record[0]);
1936 return Error(BitcodeError::InvalidRecord);
1937 if (!Ty->isPointerTy())
1938 return Error(BitcodeError::InvalidTypeForValue);
1939 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1940 Ty = cast<PointerType>(Ty)->getElementType();
1942 bool isConstant = Record[1];
1943 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1944 unsigned Alignment = (1 << Record[4]) >> 1;
1945 std::string Section;
1947 if (Record[5]-1 >= SectionTable.size())
1948 return Error(BitcodeError::InvalidID);
1949 Section = SectionTable[Record[5]-1];
1951 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1952 // Local linkage must have default visibility.
1953 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1954 // FIXME: Change to an error if non-default in 4.0.
1955 Visibility = GetDecodedVisibility(Record[6]);
1957 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1958 if (Record.size() > 7)
1959 TLM = GetDecodedThreadLocalMode(Record[7]);
1961 bool UnnamedAddr = false;
1962 if (Record.size() > 8)
1963 UnnamedAddr = Record[8];
1965 bool ExternallyInitialized = false;
1966 if (Record.size() > 9)
1967 ExternallyInitialized = Record[9];
1969 GlobalVariable *NewGV =
1970 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1971 TLM, AddressSpace, ExternallyInitialized);
1972 NewGV->setAlignment(Alignment);
1973 if (!Section.empty())
1974 NewGV->setSection(Section);
1975 NewGV->setVisibility(Visibility);
1976 NewGV->setUnnamedAddr(UnnamedAddr);
1978 if (Record.size() > 10)
1979 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1981 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1983 ValueList.push_back(NewGV);
1985 // Remember which value to use for the global initializer.
1986 if (unsigned InitID = Record[2])
1987 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1989 if (Record.size() > 11)
1990 if (unsigned ComdatID = Record[11]) {
1991 assert(ComdatID <= ComdatList.size());
1992 NewGV->setComdat(ComdatList[ComdatID - 1]);
1996 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1997 // alignment, section, visibility, gc, unnamed_addr,
1999 case bitc::MODULE_CODE_FUNCTION: {
2000 if (Record.size() < 8)
2001 return Error(BitcodeError::InvalidRecord);
2002 Type *Ty = getTypeByID(Record[0]);
2004 return Error(BitcodeError::InvalidRecord);
2005 if (!Ty->isPointerTy())
2006 return Error(BitcodeError::InvalidTypeForValue);
2008 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2010 return Error(BitcodeError::InvalidTypeForValue);
2012 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2015 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2016 bool isProto = Record[2];
2017 Func->setLinkage(GetDecodedLinkage(Record[3]));
2018 Func->setAttributes(getAttributes(Record[4]));
2020 Func->setAlignment((1 << Record[5]) >> 1);
2022 if (Record[6]-1 >= SectionTable.size())
2023 return Error(BitcodeError::InvalidID);
2024 Func->setSection(SectionTable[Record[6]-1]);
2026 // Local linkage must have default visibility.
2027 if (!Func->hasLocalLinkage())
2028 // FIXME: Change to an error if non-default in 4.0.
2029 Func->setVisibility(GetDecodedVisibility(Record[7]));
2030 if (Record.size() > 8 && Record[8]) {
2031 if (Record[8]-1 > GCTable.size())
2032 return Error(BitcodeError::InvalidID);
2033 Func->setGC(GCTable[Record[8]-1].c_str());
2035 bool UnnamedAddr = false;
2036 if (Record.size() > 9)
2037 UnnamedAddr = Record[9];
2038 Func->setUnnamedAddr(UnnamedAddr);
2039 if (Record.size() > 10 && Record[10] != 0)
2040 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
2042 if (Record.size() > 11)
2043 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2045 UpgradeDLLImportExportLinkage(Func, Record[3]);
2047 if (Record.size() > 12)
2048 if (unsigned ComdatID = Record[12]) {
2049 assert(ComdatID <= ComdatList.size());
2050 Func->setComdat(ComdatList[ComdatID - 1]);
2053 ValueList.push_back(Func);
2055 // If this is a function with a body, remember the prototype we are
2056 // creating now, so that we can match up the body with them later.
2058 FunctionsWithBodies.push_back(Func);
2059 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
2063 // ALIAS: [alias type, aliasee val#, linkage]
2064 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2065 case bitc::MODULE_CODE_ALIAS: {
2066 if (Record.size() < 3)
2067 return Error(BitcodeError::InvalidRecord);
2068 Type *Ty = getTypeByID(Record[0]);
2070 return Error(BitcodeError::InvalidRecord);
2071 auto *PTy = dyn_cast<PointerType>(Ty);
2073 return Error(BitcodeError::InvalidTypeForValue);
2076 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2077 GetDecodedLinkage(Record[2]), "", TheModule);
2078 // Old bitcode files didn't have visibility field.
2079 // Local linkage must have default visibility.
2080 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2081 // FIXME: Change to an error if non-default in 4.0.
2082 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2083 if (Record.size() > 4)
2084 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2086 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2087 if (Record.size() > 5)
2088 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2089 if (Record.size() > 6)
2090 NewGA->setUnnamedAddr(Record[6]);
2091 ValueList.push_back(NewGA);
2092 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2095 /// MODULE_CODE_PURGEVALS: [numvals]
2096 case bitc::MODULE_CODE_PURGEVALS:
2097 // Trim down the value list to the specified size.
2098 if (Record.size() < 1 || Record[0] > ValueList.size())
2099 return Error(BitcodeError::InvalidRecord);
2100 ValueList.shrinkTo(Record[0]);
2107 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2108 TheModule = nullptr;
2110 if (std::error_code EC = InitStream())
2113 // Sniff for the signature.
2114 if (Stream.Read(8) != 'B' ||
2115 Stream.Read(8) != 'C' ||
2116 Stream.Read(4) != 0x0 ||
2117 Stream.Read(4) != 0xC ||
2118 Stream.Read(4) != 0xE ||
2119 Stream.Read(4) != 0xD)
2120 return Error(BitcodeError::InvalidBitcodeSignature);
2122 // We expect a number of well-defined blocks, though we don't necessarily
2123 // need to understand them all.
2125 if (Stream.AtEndOfStream())
2126 return std::error_code();
2128 BitstreamEntry Entry =
2129 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2131 switch (Entry.Kind) {
2132 case BitstreamEntry::Error:
2133 return Error(BitcodeError::MalformedBlock);
2134 case BitstreamEntry::EndBlock:
2135 return std::error_code();
2137 case BitstreamEntry::SubBlock:
2139 case bitc::BLOCKINFO_BLOCK_ID:
2140 if (Stream.ReadBlockInfoBlock())
2141 return Error(BitcodeError::MalformedBlock);
2143 case bitc::MODULE_BLOCK_ID:
2144 // Reject multiple MODULE_BLOCK's in a single bitstream.
2146 return Error(BitcodeError::InvalidMultipleBlocks);
2148 if (std::error_code EC = ParseModule(false))
2151 return std::error_code();
2154 if (Stream.SkipBlock())
2155 return Error(BitcodeError::InvalidRecord);
2159 case BitstreamEntry::Record:
2160 // There should be no records in the top-level of blocks.
2162 // The ranlib in Xcode 4 will align archive members by appending newlines
2163 // to the end of them. If this file size is a multiple of 4 but not 8, we
2164 // have to read and ignore these final 4 bytes :-(
2165 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2166 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2167 Stream.AtEndOfStream())
2168 return std::error_code();
2170 return Error(BitcodeError::InvalidRecord);
2175 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2176 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2177 return Error(BitcodeError::InvalidRecord);
2179 SmallVector<uint64_t, 64> Record;
2182 // Read all the records for this module.
2184 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2186 switch (Entry.Kind) {
2187 case BitstreamEntry::SubBlock: // Handled for us already.
2188 case BitstreamEntry::Error:
2189 return Error(BitcodeError::MalformedBlock);
2190 case BitstreamEntry::EndBlock:
2192 case BitstreamEntry::Record:
2193 // The interesting case.
2198 switch (Stream.readRecord(Entry.ID, Record)) {
2199 default: break; // Default behavior, ignore unknown content.
2200 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2202 if (ConvertToString(Record, 0, S))
2203 return Error(BitcodeError::InvalidRecord);
2210 llvm_unreachable("Exit infinite loop");
2213 ErrorOr<std::string> BitcodeReader::parseTriple() {
2214 if (std::error_code EC = InitStream())
2217 // Sniff for the signature.
2218 if (Stream.Read(8) != 'B' ||
2219 Stream.Read(8) != 'C' ||
2220 Stream.Read(4) != 0x0 ||
2221 Stream.Read(4) != 0xC ||
2222 Stream.Read(4) != 0xE ||
2223 Stream.Read(4) != 0xD)
2224 return Error(BitcodeError::InvalidBitcodeSignature);
2226 // We expect a number of well-defined blocks, though we don't necessarily
2227 // need to understand them all.
2229 BitstreamEntry Entry = Stream.advance();
2231 switch (Entry.Kind) {
2232 case BitstreamEntry::Error:
2233 return Error(BitcodeError::MalformedBlock);
2234 case BitstreamEntry::EndBlock:
2235 return std::error_code();
2237 case BitstreamEntry::SubBlock:
2238 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2239 return parseModuleTriple();
2241 // Ignore other sub-blocks.
2242 if (Stream.SkipBlock())
2243 return Error(BitcodeError::MalformedBlock);
2246 case BitstreamEntry::Record:
2247 Stream.skipRecord(Entry.ID);
2253 /// ParseMetadataAttachment - Parse metadata attachments.
2254 std::error_code BitcodeReader::ParseMetadataAttachment() {
2255 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2256 return Error(BitcodeError::InvalidRecord);
2258 SmallVector<uint64_t, 64> Record;
2260 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2262 switch (Entry.Kind) {
2263 case BitstreamEntry::SubBlock: // Handled for us already.
2264 case BitstreamEntry::Error:
2265 return Error(BitcodeError::MalformedBlock);
2266 case BitstreamEntry::EndBlock:
2267 return std::error_code();
2268 case BitstreamEntry::Record:
2269 // The interesting case.
2273 // Read a metadata attachment record.
2275 switch (Stream.readRecord(Entry.ID, Record)) {
2276 default: // Default behavior: ignore.
2278 case bitc::METADATA_ATTACHMENT: {
2279 unsigned RecordLength = Record.size();
2280 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2281 return Error(BitcodeError::InvalidRecord);
2282 Instruction *Inst = InstructionList[Record[0]];
2283 for (unsigned i = 1; i != RecordLength; i = i+2) {
2284 unsigned Kind = Record[i];
2285 DenseMap<unsigned, unsigned>::iterator I =
2286 MDKindMap.find(Kind);
2287 if (I == MDKindMap.end())
2288 return Error(BitcodeError::InvalidID);
2289 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2290 Inst->setMetadata(I->second, cast<MDNode>(Node));
2291 if (I->second == LLVMContext::MD_tbaa)
2292 InstsWithTBAATag.push_back(Inst);
2300 /// ParseFunctionBody - Lazily parse the specified function body block.
2301 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2302 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2303 return Error(BitcodeError::InvalidRecord);
2305 InstructionList.clear();
2306 unsigned ModuleValueListSize = ValueList.size();
2307 unsigned ModuleMDValueListSize = MDValueList.size();
2309 // Add all the function arguments to the value table.
2310 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2311 ValueList.push_back(I);
2313 unsigned NextValueNo = ValueList.size();
2314 BasicBlock *CurBB = nullptr;
2315 unsigned CurBBNo = 0;
2319 // Read all the records.
2320 SmallVector<uint64_t, 64> Record;
2322 BitstreamEntry Entry = Stream.advance();
2324 switch (Entry.Kind) {
2325 case BitstreamEntry::Error:
2326 return Error(BitcodeError::MalformedBlock);
2327 case BitstreamEntry::EndBlock:
2328 goto OutOfRecordLoop;
2330 case BitstreamEntry::SubBlock:
2332 default: // Skip unknown content.
2333 if (Stream.SkipBlock())
2334 return Error(BitcodeError::InvalidRecord);
2336 case bitc::CONSTANTS_BLOCK_ID:
2337 if (std::error_code EC = ParseConstants())
2339 NextValueNo = ValueList.size();
2341 case bitc::VALUE_SYMTAB_BLOCK_ID:
2342 if (std::error_code EC = ParseValueSymbolTable())
2345 case bitc::METADATA_ATTACHMENT_ID:
2346 if (std::error_code EC = ParseMetadataAttachment())
2349 case bitc::METADATA_BLOCK_ID:
2350 if (std::error_code EC = ParseMetadata())
2353 case bitc::USELIST_BLOCK_ID:
2354 if (std::error_code EC = ParseUseLists())
2360 case BitstreamEntry::Record:
2361 // The interesting case.
2367 Instruction *I = nullptr;
2368 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2370 default: // Default behavior: reject
2371 return Error(BitcodeError::InvalidValue);
2372 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2373 if (Record.size() < 1 || Record[0] == 0)
2374 return Error(BitcodeError::InvalidRecord);
2375 // Create all the basic blocks for the function.
2376 FunctionBBs.resize(Record[0]);
2378 // See if anything took the address of blocks in this function.
2379 auto BBFRI = BasicBlockFwdRefs.find(F);
2380 if (BBFRI == BasicBlockFwdRefs.end()) {
2381 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2382 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2384 auto &BBRefs = BBFRI->second;
2385 std::sort(BBRefs.begin(), BBRefs.end(),
2386 [](const std::pair<unsigned, BasicBlock *> &LHS,
2387 const std::pair<unsigned, BasicBlock *> &RHS) {
2388 return LHS.first < RHS.first;
2390 unsigned R = 0, RE = BBRefs.size();
2391 for (unsigned I = 0, E = FunctionBBs.size(); I != E; ++I)
2392 if (R != RE && BBRefs[R].first == I) {
2393 assert(I != 0 && "Invalid reference to entry block");
2394 BasicBlock *BB = BBRefs[R++].second;
2396 FunctionBBs[I] = BB;
2398 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2400 // Check for invalid basic block references.
2402 return Error(BitcodeError::InvalidID);
2404 // Erase from the table.
2405 BasicBlockFwdRefs.erase(BBFRI);
2408 CurBB = FunctionBBs[0];
2412 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2413 // This record indicates that the last instruction is at the same
2414 // location as the previous instruction with a location.
2417 // Get the last instruction emitted.
2418 if (CurBB && !CurBB->empty())
2420 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2421 !FunctionBBs[CurBBNo-1]->empty())
2422 I = &FunctionBBs[CurBBNo-1]->back();
2425 return Error(BitcodeError::InvalidRecord);
2426 I->setDebugLoc(LastLoc);
2430 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2431 I = nullptr; // Get the last instruction emitted.
2432 if (CurBB && !CurBB->empty())
2434 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2435 !FunctionBBs[CurBBNo-1]->empty())
2436 I = &FunctionBBs[CurBBNo-1]->back();
2437 if (!I || Record.size() < 4)
2438 return Error(BitcodeError::InvalidRecord);
2440 unsigned Line = Record[0], Col = Record[1];
2441 unsigned ScopeID = Record[2], IAID = Record[3];
2443 MDNode *Scope = nullptr, *IA = nullptr;
2444 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2445 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2446 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2447 I->setDebugLoc(LastLoc);
2452 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2455 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2456 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2457 OpNum+1 > Record.size())
2458 return Error(BitcodeError::InvalidRecord);
2460 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2462 return Error(BitcodeError::InvalidRecord);
2463 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2464 InstructionList.push_back(I);
2465 if (OpNum < Record.size()) {
2466 if (Opc == Instruction::Add ||
2467 Opc == Instruction::Sub ||
2468 Opc == Instruction::Mul ||
2469 Opc == Instruction::Shl) {
2470 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2471 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2472 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2473 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2474 } else if (Opc == Instruction::SDiv ||
2475 Opc == Instruction::UDiv ||
2476 Opc == Instruction::LShr ||
2477 Opc == Instruction::AShr) {
2478 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2479 cast<BinaryOperator>(I)->setIsExact(true);
2480 } else if (isa<FPMathOperator>(I)) {
2482 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2483 FMF.setUnsafeAlgebra();
2484 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2486 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2488 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2489 FMF.setNoSignedZeros();
2490 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2491 FMF.setAllowReciprocal();
2493 I->setFastMathFlags(FMF);
2499 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2502 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2503 OpNum+2 != Record.size())
2504 return Error(BitcodeError::InvalidRecord);
2506 Type *ResTy = getTypeByID(Record[OpNum]);
2507 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2508 if (Opc == -1 || !ResTy)
2509 return Error(BitcodeError::InvalidRecord);
2510 Instruction *Temp = nullptr;
2511 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2513 InstructionList.push_back(Temp);
2514 CurBB->getInstList().push_back(Temp);
2517 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2519 InstructionList.push_back(I);
2522 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2523 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2526 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2527 return Error(BitcodeError::InvalidRecord);
2529 SmallVector<Value*, 16> GEPIdx;
2530 while (OpNum != Record.size()) {
2532 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2533 return Error(BitcodeError::InvalidRecord);
2534 GEPIdx.push_back(Op);
2537 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2538 InstructionList.push_back(I);
2539 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2540 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2544 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2545 // EXTRACTVAL: [opty, opval, n x indices]
2548 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2549 return Error(BitcodeError::InvalidRecord);
2551 SmallVector<unsigned, 4> EXTRACTVALIdx;
2552 for (unsigned RecSize = Record.size();
2553 OpNum != RecSize; ++OpNum) {
2554 uint64_t Index = Record[OpNum];
2555 if ((unsigned)Index != Index)
2556 return Error(BitcodeError::InvalidValue);
2557 EXTRACTVALIdx.push_back((unsigned)Index);
2560 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2561 InstructionList.push_back(I);
2565 case bitc::FUNC_CODE_INST_INSERTVAL: {
2566 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2569 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2570 return Error(BitcodeError::InvalidRecord);
2572 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2573 return Error(BitcodeError::InvalidRecord);
2575 SmallVector<unsigned, 4> INSERTVALIdx;
2576 for (unsigned RecSize = Record.size();
2577 OpNum != RecSize; ++OpNum) {
2578 uint64_t Index = Record[OpNum];
2579 if ((unsigned)Index != Index)
2580 return Error(BitcodeError::InvalidValue);
2581 INSERTVALIdx.push_back((unsigned)Index);
2584 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2585 InstructionList.push_back(I);
2589 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2590 // obsolete form of select
2591 // handles select i1 ... in old bitcode
2593 Value *TrueVal, *FalseVal, *Cond;
2594 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2595 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2596 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2597 return Error(BitcodeError::InvalidRecord);
2599 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2600 InstructionList.push_back(I);
2604 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2605 // new form of select
2606 // handles select i1 or select [N x i1]
2608 Value *TrueVal, *FalseVal, *Cond;
2609 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2610 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2611 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2612 return Error(BitcodeError::InvalidRecord);
2614 // select condition can be either i1 or [N x i1]
2615 if (VectorType* vector_type =
2616 dyn_cast<VectorType>(Cond->getType())) {
2618 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2619 return Error(BitcodeError::InvalidTypeForValue);
2622 if (Cond->getType() != Type::getInt1Ty(Context))
2623 return Error(BitcodeError::InvalidTypeForValue);
2626 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2627 InstructionList.push_back(I);
2631 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2634 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2635 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2636 return Error(BitcodeError::InvalidRecord);
2637 I = ExtractElementInst::Create(Vec, Idx);
2638 InstructionList.push_back(I);
2642 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2644 Value *Vec, *Elt, *Idx;
2645 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2646 popValue(Record, OpNum, NextValueNo,
2647 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2648 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2649 return Error(BitcodeError::InvalidRecord);
2650 I = InsertElementInst::Create(Vec, Elt, Idx);
2651 InstructionList.push_back(I);
2655 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2657 Value *Vec1, *Vec2, *Mask;
2658 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2659 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2660 return Error(BitcodeError::InvalidRecord);
2662 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2663 return Error(BitcodeError::InvalidRecord);
2664 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2665 InstructionList.push_back(I);
2669 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2670 // Old form of ICmp/FCmp returning bool
2671 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2672 // both legal on vectors but had different behaviour.
2673 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2674 // FCmp/ICmp returning bool or vector of bool
2678 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2679 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2680 OpNum+1 != Record.size())
2681 return Error(BitcodeError::InvalidRecord);
2683 if (LHS->getType()->isFPOrFPVectorTy())
2684 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2686 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2687 InstructionList.push_back(I);
2691 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2693 unsigned Size = Record.size();
2695 I = ReturnInst::Create(Context);
2696 InstructionList.push_back(I);
2701 Value *Op = nullptr;
2702 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2703 return Error(BitcodeError::InvalidRecord);
2704 if (OpNum != Record.size())
2705 return Error(BitcodeError::InvalidRecord);
2707 I = ReturnInst::Create(Context, Op);
2708 InstructionList.push_back(I);
2711 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2712 if (Record.size() != 1 && Record.size() != 3)
2713 return Error(BitcodeError::InvalidRecord);
2714 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2716 return Error(BitcodeError::InvalidRecord);
2718 if (Record.size() == 1) {
2719 I = BranchInst::Create(TrueDest);
2720 InstructionList.push_back(I);
2723 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2724 Value *Cond = getValue(Record, 2, NextValueNo,
2725 Type::getInt1Ty(Context));
2726 if (!FalseDest || !Cond)
2727 return Error(BitcodeError::InvalidRecord);
2728 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2729 InstructionList.push_back(I);
2733 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2735 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2736 // "New" SwitchInst format with case ranges. The changes to write this
2737 // format were reverted but we still recognize bitcode that uses it.
2738 // Hopefully someday we will have support for case ranges and can use
2739 // this format again.
2741 Type *OpTy = getTypeByID(Record[1]);
2742 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2744 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2745 BasicBlock *Default = getBasicBlock(Record[3]);
2746 if (!OpTy || !Cond || !Default)
2747 return Error(BitcodeError::InvalidRecord);
2749 unsigned NumCases = Record[4];
2751 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2752 InstructionList.push_back(SI);
2754 unsigned CurIdx = 5;
2755 for (unsigned i = 0; i != NumCases; ++i) {
2756 SmallVector<ConstantInt*, 1> CaseVals;
2757 unsigned NumItems = Record[CurIdx++];
2758 for (unsigned ci = 0; ci != NumItems; ++ci) {
2759 bool isSingleNumber = Record[CurIdx++];
2762 unsigned ActiveWords = 1;
2763 if (ValueBitWidth > 64)
2764 ActiveWords = Record[CurIdx++];
2765 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2767 CurIdx += ActiveWords;
2769 if (!isSingleNumber) {
2771 if (ValueBitWidth > 64)
2772 ActiveWords = Record[CurIdx++];
2774 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2776 CurIdx += ActiveWords;
2778 // FIXME: It is not clear whether values in the range should be
2779 // compared as signed or unsigned values. The partially
2780 // implemented changes that used this format in the past used
2781 // unsigned comparisons.
2782 for ( ; Low.ule(High); ++Low)
2783 CaseVals.push_back(ConstantInt::get(Context, Low));
2785 CaseVals.push_back(ConstantInt::get(Context, Low));
2787 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2788 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2789 cve = CaseVals.end(); cvi != cve; ++cvi)
2790 SI->addCase(*cvi, DestBB);
2796 // Old SwitchInst format without case ranges.
2798 if (Record.size() < 3 || (Record.size() & 1) == 0)
2799 return Error(BitcodeError::InvalidRecord);
2800 Type *OpTy = getTypeByID(Record[0]);
2801 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2802 BasicBlock *Default = getBasicBlock(Record[2]);
2803 if (!OpTy || !Cond || !Default)
2804 return Error(BitcodeError::InvalidRecord);
2805 unsigned NumCases = (Record.size()-3)/2;
2806 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2807 InstructionList.push_back(SI);
2808 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2809 ConstantInt *CaseVal =
2810 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2811 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2812 if (!CaseVal || !DestBB) {
2814 return Error(BitcodeError::InvalidRecord);
2816 SI->addCase(CaseVal, DestBB);
2821 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2822 if (Record.size() < 2)
2823 return Error(BitcodeError::InvalidRecord);
2824 Type *OpTy = getTypeByID(Record[0]);
2825 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2826 if (!OpTy || !Address)
2827 return Error(BitcodeError::InvalidRecord);
2828 unsigned NumDests = Record.size()-2;
2829 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2830 InstructionList.push_back(IBI);
2831 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2832 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2833 IBI->addDestination(DestBB);
2836 return Error(BitcodeError::InvalidRecord);
2843 case bitc::FUNC_CODE_INST_INVOKE: {
2844 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2845 if (Record.size() < 4)
2846 return Error(BitcodeError::InvalidRecord);
2847 AttributeSet PAL = getAttributes(Record[0]);
2848 unsigned CCInfo = Record[1];
2849 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2850 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2854 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2855 return Error(BitcodeError::InvalidRecord);
2857 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2858 FunctionType *FTy = !CalleeTy ? nullptr :
2859 dyn_cast<FunctionType>(CalleeTy->getElementType());
2861 // Check that the right number of fixed parameters are here.
2862 if (!FTy || !NormalBB || !UnwindBB ||
2863 Record.size() < OpNum+FTy->getNumParams())
2864 return Error(BitcodeError::InvalidRecord);
2866 SmallVector<Value*, 16> Ops;
2867 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2868 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2869 FTy->getParamType(i)));
2871 return Error(BitcodeError::InvalidRecord);
2874 if (!FTy->isVarArg()) {
2875 if (Record.size() != OpNum)
2876 return Error(BitcodeError::InvalidRecord);
2878 // Read type/value pairs for varargs params.
2879 while (OpNum != Record.size()) {
2881 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2882 return Error(BitcodeError::InvalidRecord);
2887 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2888 InstructionList.push_back(I);
2889 cast<InvokeInst>(I)->setCallingConv(
2890 static_cast<CallingConv::ID>(CCInfo));
2891 cast<InvokeInst>(I)->setAttributes(PAL);
2894 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2896 Value *Val = nullptr;
2897 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2898 return Error(BitcodeError::InvalidRecord);
2899 I = ResumeInst::Create(Val);
2900 InstructionList.push_back(I);
2903 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2904 I = new UnreachableInst(Context);
2905 InstructionList.push_back(I);
2907 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2908 if (Record.size() < 1 || ((Record.size()-1)&1))
2909 return Error(BitcodeError::InvalidRecord);
2910 Type *Ty = getTypeByID(Record[0]);
2912 return Error(BitcodeError::InvalidRecord);
2914 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2915 InstructionList.push_back(PN);
2917 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2919 // With the new function encoding, it is possible that operands have
2920 // negative IDs (for forward references). Use a signed VBR
2921 // representation to keep the encoding small.
2923 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2925 V = getValue(Record, 1+i, NextValueNo, Ty);
2926 BasicBlock *BB = getBasicBlock(Record[2+i]);
2928 return Error(BitcodeError::InvalidRecord);
2929 PN->addIncoming(V, BB);
2935 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2936 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2938 if (Record.size() < 4)
2939 return Error(BitcodeError::InvalidRecord);
2940 Type *Ty = getTypeByID(Record[Idx++]);
2942 return Error(BitcodeError::InvalidRecord);
2943 Value *PersFn = nullptr;
2944 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2945 return Error(BitcodeError::InvalidRecord);
2947 bool IsCleanup = !!Record[Idx++];
2948 unsigned NumClauses = Record[Idx++];
2949 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2950 LP->setCleanup(IsCleanup);
2951 for (unsigned J = 0; J != NumClauses; ++J) {
2952 LandingPadInst::ClauseType CT =
2953 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2956 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2958 return Error(BitcodeError::InvalidRecord);
2961 assert((CT != LandingPadInst::Catch ||
2962 !isa<ArrayType>(Val->getType())) &&
2963 "Catch clause has a invalid type!");
2964 assert((CT != LandingPadInst::Filter ||
2965 isa<ArrayType>(Val->getType())) &&
2966 "Filter clause has invalid type!");
2967 LP->addClause(cast<Constant>(Val));
2971 InstructionList.push_back(I);
2975 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2976 if (Record.size() != 4)
2977 return Error(BitcodeError::InvalidRecord);
2979 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2980 Type *OpTy = getTypeByID(Record[1]);
2981 Value *Size = getFnValueByID(Record[2], OpTy);
2982 unsigned AlignRecord = Record[3];
2983 bool InAlloca = AlignRecord & (1 << 5);
2984 unsigned Align = AlignRecord & ((1 << 5) - 1);
2986 return Error(BitcodeError::InvalidRecord);
2987 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2988 AI->setUsedWithInAlloca(InAlloca);
2990 InstructionList.push_back(I);
2993 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2996 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2997 OpNum+2 != Record.size())
2998 return Error(BitcodeError::InvalidRecord);
3000 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3001 InstructionList.push_back(I);
3004 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3005 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3008 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3009 OpNum+4 != Record.size())
3010 return Error(BitcodeError::InvalidRecord);
3012 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3013 if (Ordering == NotAtomic || Ordering == Release ||
3014 Ordering == AcquireRelease)
3015 return Error(BitcodeError::InvalidRecord);
3016 if (Ordering != NotAtomic && Record[OpNum] == 0)
3017 return Error(BitcodeError::InvalidRecord);
3018 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3020 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3021 Ordering, SynchScope);
3022 InstructionList.push_back(I);
3025 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3028 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3029 popValue(Record, OpNum, NextValueNo,
3030 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3031 OpNum+2 != Record.size())
3032 return Error(BitcodeError::InvalidRecord);
3034 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3035 InstructionList.push_back(I);
3038 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3039 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3042 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3043 popValue(Record, OpNum, NextValueNo,
3044 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3045 OpNum+4 != Record.size())
3046 return Error(BitcodeError::InvalidRecord);
3048 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3049 if (Ordering == NotAtomic || Ordering == Acquire ||
3050 Ordering == AcquireRelease)
3051 return Error(BitcodeError::InvalidRecord);
3052 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3053 if (Ordering != NotAtomic && Record[OpNum] == 0)
3054 return Error(BitcodeError::InvalidRecord);
3056 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3057 Ordering, SynchScope);
3058 InstructionList.push_back(I);
3061 case bitc::FUNC_CODE_INST_CMPXCHG: {
3062 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3063 // failureordering?, isweak?]
3065 Value *Ptr, *Cmp, *New;
3066 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3067 popValue(Record, OpNum, NextValueNo,
3068 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3069 popValue(Record, OpNum, NextValueNo,
3070 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3071 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3072 return Error(BitcodeError::InvalidRecord);
3073 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3074 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3075 return Error(BitcodeError::InvalidRecord);
3076 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3078 AtomicOrdering FailureOrdering;
3079 if (Record.size() < 7)
3081 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3083 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3085 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3087 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3089 if (Record.size() < 8) {
3090 // Before weak cmpxchgs existed, the instruction simply returned the
3091 // value loaded from memory, so bitcode files from that era will be
3092 // expecting the first component of a modern cmpxchg.
3093 CurBB->getInstList().push_back(I);
3094 I = ExtractValueInst::Create(I, 0);
3096 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3099 InstructionList.push_back(I);
3102 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3103 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3106 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3107 popValue(Record, OpNum, NextValueNo,
3108 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3109 OpNum+4 != Record.size())
3110 return Error(BitcodeError::InvalidRecord);
3111 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3112 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3113 Operation > AtomicRMWInst::LAST_BINOP)
3114 return Error(BitcodeError::InvalidRecord);
3115 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3116 if (Ordering == NotAtomic || Ordering == Unordered)
3117 return Error(BitcodeError::InvalidRecord);
3118 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3119 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3120 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3121 InstructionList.push_back(I);
3124 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3125 if (2 != Record.size())
3126 return Error(BitcodeError::InvalidRecord);
3127 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3128 if (Ordering == NotAtomic || Ordering == Unordered ||
3129 Ordering == Monotonic)
3130 return Error(BitcodeError::InvalidRecord);
3131 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3132 I = new FenceInst(Context, Ordering, SynchScope);
3133 InstructionList.push_back(I);
3136 case bitc::FUNC_CODE_INST_CALL: {
3137 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3138 if (Record.size() < 3)
3139 return Error(BitcodeError::InvalidRecord);
3141 AttributeSet PAL = getAttributes(Record[0]);
3142 unsigned CCInfo = Record[1];
3146 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3147 return Error(BitcodeError::InvalidRecord);
3149 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3150 FunctionType *FTy = nullptr;
3151 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3152 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3153 return Error(BitcodeError::InvalidRecord);
3155 SmallVector<Value*, 16> Args;
3156 // Read the fixed params.
3157 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3158 if (FTy->getParamType(i)->isLabelTy())
3159 Args.push_back(getBasicBlock(Record[OpNum]));
3161 Args.push_back(getValue(Record, OpNum, NextValueNo,
3162 FTy->getParamType(i)));
3164 return Error(BitcodeError::InvalidRecord);
3167 // Read type/value pairs for varargs params.
3168 if (!FTy->isVarArg()) {
3169 if (OpNum != Record.size())
3170 return Error(BitcodeError::InvalidRecord);
3172 while (OpNum != Record.size()) {
3174 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3175 return Error(BitcodeError::InvalidRecord);
3180 I = CallInst::Create(Callee, Args);
3181 InstructionList.push_back(I);
3182 cast<CallInst>(I)->setCallingConv(
3183 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3184 CallInst::TailCallKind TCK = CallInst::TCK_None;
3186 TCK = CallInst::TCK_Tail;
3187 if (CCInfo & (1 << 14))
3188 TCK = CallInst::TCK_MustTail;
3189 cast<CallInst>(I)->setTailCallKind(TCK);
3190 cast<CallInst>(I)->setAttributes(PAL);
3193 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3194 if (Record.size() < 3)
3195 return Error(BitcodeError::InvalidRecord);
3196 Type *OpTy = getTypeByID(Record[0]);
3197 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3198 Type *ResTy = getTypeByID(Record[2]);
3199 if (!OpTy || !Op || !ResTy)
3200 return Error(BitcodeError::InvalidRecord);
3201 I = new VAArgInst(Op, ResTy);
3202 InstructionList.push_back(I);
3207 // Add instruction to end of current BB. If there is no current BB, reject
3211 return Error(BitcodeError::InvalidInstructionWithNoBB);
3213 CurBB->getInstList().push_back(I);
3215 // If this was a terminator instruction, move to the next block.
3216 if (isa<TerminatorInst>(I)) {
3218 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3221 // Non-void values get registered in the value table for future use.
3222 if (I && !I->getType()->isVoidTy())
3223 ValueList.AssignValue(I, NextValueNo++);
3228 // Check the function list for unresolved values.
3229 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3230 if (!A->getParent()) {
3231 // We found at least one unresolved value. Nuke them all to avoid leaks.
3232 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3233 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3234 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3238 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3242 // FIXME: Check for unresolved forward-declared metadata references
3243 // and clean up leaks.
3245 // Trim the value list down to the size it was before we parsed this function.
3246 ValueList.shrinkTo(ModuleValueListSize);
3247 MDValueList.shrinkTo(ModuleMDValueListSize);
3248 std::vector<BasicBlock*>().swap(FunctionBBs);
3249 return std::error_code();
3252 /// Find the function body in the bitcode stream
3253 std::error_code BitcodeReader::FindFunctionInStream(
3255 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3256 while (DeferredFunctionInfoIterator->second == 0) {
3257 if (Stream.AtEndOfStream())
3258 return Error(BitcodeError::CouldNotFindFunctionInStream);
3259 // ParseModule will parse the next body in the stream and set its
3260 // position in the DeferredFunctionInfo map.
3261 if (std::error_code EC = ParseModule(true))
3264 return std::error_code();
3267 //===----------------------------------------------------------------------===//
3268 // GVMaterializer implementation
3269 //===----------------------------------------------------------------------===//
3271 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3273 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3274 if (const Function *F = dyn_cast<Function>(GV)) {
3275 return F->isDeclaration() &&
3276 DeferredFunctionInfo.count(const_cast<Function*>(F));
3281 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
3282 Function *F = dyn_cast<Function>(GV);
3283 // If it's not a function or is already material, ignore the request.
3284 if (!F || !F->isMaterializable())
3285 return std::error_code();
3287 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3288 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3289 // If its position is recorded as 0, its body is somewhere in the stream
3290 // but we haven't seen it yet.
3291 if (DFII->second == 0 && LazyStreamer)
3292 if (std::error_code EC = FindFunctionInStream(F, DFII))
3295 // Move the bit stream to the saved position of the deferred function body.
3296 Stream.JumpToBit(DFII->second);
3298 if (std::error_code EC = ParseFunctionBody(F))
3301 // Upgrade any old intrinsic calls in the function.
3302 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3303 E = UpgradedIntrinsics.end(); I != E; ++I) {
3304 if (I->first != I->second) {
3305 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3307 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3308 UpgradeIntrinsicCall(CI, I->second);
3313 // Bring in any functions that this function forward-referenced via
3315 return materializeForwardReferencedFunctions();
3318 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3319 const Function *F = dyn_cast<Function>(GV);
3320 if (!F || F->isDeclaration())
3323 // Dematerializing F would leave dangling references that wouldn't be
3324 // reconnected on re-materialization.
3325 if (BlockAddressesTaken.count(F))
3328 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3331 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3332 Function *F = dyn_cast<Function>(GV);
3333 // If this function isn't dematerializable, this is a noop.
3334 if (!F || !isDematerializable(F))
3337 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3339 // Just forget the function body, we can remat it later.
3343 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3344 assert(M == TheModule &&
3345 "Can only Materialize the Module this BitcodeReader is attached to.");
3347 // Promise to materialize all forward references.
3348 WillMaterializeAllForwardRefs = true;
3350 // Iterate over the module, deserializing any functions that are still on
3352 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3354 if (F->isMaterializable()) {
3355 if (std::error_code EC = Materialize(F))
3359 // At this point, if there are any function bodies, the current bit is
3360 // pointing to the END_BLOCK record after them. Now make sure the rest
3361 // of the bits in the module have been read.
3365 // Check that all block address forward references got resolved (as we
3367 if (!BasicBlockFwdRefs.empty())
3368 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3370 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3371 // delete the old functions to clean up. We can't do this unless the entire
3372 // module is materialized because there could always be another function body
3373 // with calls to the old function.
3374 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3375 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3376 if (I->first != I->second) {
3377 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3379 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3380 UpgradeIntrinsicCall(CI, I->second);
3382 if (!I->first->use_empty())
3383 I->first->replaceAllUsesWith(I->second);
3384 I->first->eraseFromParent();
3387 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3389 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3390 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3392 UpgradeDebugInfo(*M);
3393 return std::error_code();
3396 std::error_code BitcodeReader::InitStream() {
3398 return InitLazyStream();
3399 return InitStreamFromBuffer();
3402 std::error_code BitcodeReader::InitStreamFromBuffer() {
3403 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3404 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3406 if (Buffer->getBufferSize() & 3)
3407 return Error(BitcodeError::InvalidBitcodeSignature);
3409 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3410 // The magic number is 0x0B17C0DE stored in little endian.
3411 if (isBitcodeWrapper(BufPtr, BufEnd))
3412 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3413 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3415 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3416 Stream.init(*StreamFile);
3418 return std::error_code();
3421 std::error_code BitcodeReader::InitLazyStream() {
3422 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3424 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3425 StreamFile.reset(new BitstreamReader(Bytes));
3426 Stream.init(*StreamFile);
3428 unsigned char buf[16];
3429 if (Bytes->readBytes(0, 16, buf) == -1)
3430 return Error(BitcodeError::InvalidBitcodeSignature);
3432 if (!isBitcode(buf, buf + 16))
3433 return Error(BitcodeError::InvalidBitcodeSignature);
3435 if (isBitcodeWrapper(buf, buf + 4)) {
3436 const unsigned char *bitcodeStart = buf;
3437 const unsigned char *bitcodeEnd = buf + 16;
3438 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3439 Bytes->dropLeadingBytes(bitcodeStart - buf);
3440 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3442 return std::error_code();
3446 class BitcodeErrorCategoryType : public std::error_category {
3447 const char *name() const LLVM_NOEXCEPT override {
3448 return "llvm.bitcode";
3450 std::string message(int IE) const override {
3451 BitcodeError E = static_cast<BitcodeError>(IE);
3453 case BitcodeError::ConflictingMETADATA_KINDRecords:
3454 return "Conflicting METADATA_KIND records";
3455 case BitcodeError::CouldNotFindFunctionInStream:
3456 return "Could not find function in stream";
3457 case BitcodeError::ExpectedConstant:
3458 return "Expected a constant";
3459 case BitcodeError::InsufficientFunctionProtos:
3460 return "Insufficient function protos";
3461 case BitcodeError::InvalidBitcodeSignature:
3462 return "Invalid bitcode signature";
3463 case BitcodeError::InvalidBitcodeWrapperHeader:
3464 return "Invalid bitcode wrapper header";
3465 case BitcodeError::InvalidConstantReference:
3466 return "Invalid ronstant reference";
3467 case BitcodeError::InvalidID:
3468 return "Invalid ID";
3469 case BitcodeError::InvalidInstructionWithNoBB:
3470 return "Invalid instruction with no BB";
3471 case BitcodeError::InvalidRecord:
3472 return "Invalid record";
3473 case BitcodeError::InvalidTypeForValue:
3474 return "Invalid type for value";
3475 case BitcodeError::InvalidTYPETable:
3476 return "Invalid TYPE table";
3477 case BitcodeError::InvalidType:
3478 return "Invalid type";
3479 case BitcodeError::MalformedBlock:
3480 return "Malformed block";
3481 case BitcodeError::MalformedGlobalInitializerSet:
3482 return "Malformed global initializer set";
3483 case BitcodeError::InvalidMultipleBlocks:
3484 return "Invalid multiple blocks";
3485 case BitcodeError::NeverResolvedValueFoundInFunction:
3486 return "Never resolved value found in function";
3487 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3488 return "Never resolved function from blockaddress";
3489 case BitcodeError::InvalidValue:
3490 return "Invalid value";
3492 llvm_unreachable("Unknown error type!");
3497 const std::error_category &llvm::BitcodeErrorCategory() {
3498 static BitcodeErrorCategoryType O;
3502 //===----------------------------------------------------------------------===//
3503 // External interface
3504 //===----------------------------------------------------------------------===//
3506 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3508 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3509 LLVMContext &Context) {
3510 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3511 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3512 M->setMaterializer(R);
3514 auto cleanupOnError = [&](std::error_code EC) {
3515 R->releaseBuffer(); // Never take ownership on error.
3516 delete M; // Also deletes R.
3520 if (std::error_code EC = R->ParseBitcodeInto(M))
3521 return cleanupOnError(EC);
3523 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3524 return cleanupOnError(EC);
3530 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3531 DataStreamer *streamer,
3532 LLVMContext &Context,
3533 std::string *ErrMsg) {
3534 Module *M = new Module(name, Context);
3535 BitcodeReader *R = new BitcodeReader(streamer, Context);
3536 M->setMaterializer(R);
3537 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3539 *ErrMsg = EC.message();
3540 delete M; // Also deletes R.
3546 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3547 LLVMContext &Context) {
3548 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3551 Module *M = ModuleOrErr.get();
3552 // Read in the entire module, and destroy the BitcodeReader.
3553 if (std::error_code EC = M->materializeAllPermanently(true)) {
3558 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3559 // written. We must defer until the Module has been fully materialized.
3564 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3565 LLVMContext &Context) {
3566 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3567 ErrorOr<std::string> Triple = R->parseTriple();
3570 if (Triple.getError())
3572 return Triple.get();