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"
28 #include "llvm/Support/ManagedStatic.h"
33 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
36 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
37 if (WillMaterializeAllForwardRefs)
38 return std::error_code();
41 WillMaterializeAllForwardRefs = true;
43 while (!BasicBlockFwdRefQueue.empty()) {
44 Function *F = BasicBlockFwdRefQueue.front();
45 BasicBlockFwdRefQueue.pop_front();
46 assert(F && "Expected valid function");
47 if (!BasicBlockFwdRefs.count(F))
48 // Already materialized.
51 // Check for a function that isn't materializable to prevent an infinite
52 // loop. When parsing a blockaddress stored in a global variable, there
53 // isn't a trivial way to check if a function will have a body without a
54 // linear search through FunctionsWithBodies, so just check it here.
55 if (!F->isMaterializable())
56 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
58 // Try to materialize F.
59 if (std::error_code EC = materialize(F))
62 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
65 WillMaterializeAllForwardRefs = false;
66 return std::error_code();
69 void BitcodeReader::FreeState() {
71 std::vector<Type*>().swap(TypeList);
74 std::vector<Comdat *>().swap(ComdatList);
76 std::vector<AttributeSet>().swap(MAttributes);
77 std::vector<BasicBlock*>().swap(FunctionBBs);
78 std::vector<Function*>().swap(FunctionsWithBodies);
79 DeferredFunctionInfo.clear();
82 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
83 BasicBlockFwdRefQueue.clear();
86 //===----------------------------------------------------------------------===//
87 // Helper functions to implement forward reference resolution, etc.
88 //===----------------------------------------------------------------------===//
90 /// ConvertToString - Convert a string from a record into an std::string, return
92 template<typename StrTy>
93 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
95 if (Idx > Record.size())
98 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
99 Result += (char)Record[i];
103 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
105 default: // Map unknown/new linkages to external
107 return GlobalValue::ExternalLinkage;
109 return GlobalValue::WeakAnyLinkage;
111 return GlobalValue::AppendingLinkage;
113 return GlobalValue::InternalLinkage;
115 return GlobalValue::LinkOnceAnyLinkage;
117 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
119 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
121 return GlobalValue::ExternalWeakLinkage;
123 return GlobalValue::CommonLinkage;
125 return GlobalValue::PrivateLinkage;
127 return GlobalValue::WeakODRLinkage;
129 return GlobalValue::LinkOnceODRLinkage;
131 return GlobalValue::AvailableExternallyLinkage;
133 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
135 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
137 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
141 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
143 default: // Map unknown visibilities to default.
144 case 0: return GlobalValue::DefaultVisibility;
145 case 1: return GlobalValue::HiddenVisibility;
146 case 2: return GlobalValue::ProtectedVisibility;
150 static GlobalValue::DLLStorageClassTypes
151 GetDecodedDLLStorageClass(unsigned Val) {
153 default: // Map unknown values to default.
154 case 0: return GlobalValue::DefaultStorageClass;
155 case 1: return GlobalValue::DLLImportStorageClass;
156 case 2: return GlobalValue::DLLExportStorageClass;
160 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
162 case 0: return GlobalVariable::NotThreadLocal;
163 default: // Map unknown non-zero value to general dynamic.
164 case 1: return GlobalVariable::GeneralDynamicTLSModel;
165 case 2: return GlobalVariable::LocalDynamicTLSModel;
166 case 3: return GlobalVariable::InitialExecTLSModel;
167 case 4: return GlobalVariable::LocalExecTLSModel;
171 static int GetDecodedCastOpcode(unsigned Val) {
174 case bitc::CAST_TRUNC : return Instruction::Trunc;
175 case bitc::CAST_ZEXT : return Instruction::ZExt;
176 case bitc::CAST_SEXT : return Instruction::SExt;
177 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
178 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
179 case bitc::CAST_UITOFP : return Instruction::UIToFP;
180 case bitc::CAST_SITOFP : return Instruction::SIToFP;
181 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
182 case bitc::CAST_FPEXT : return Instruction::FPExt;
183 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
184 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
185 case bitc::CAST_BITCAST : return Instruction::BitCast;
186 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
189 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
192 case bitc::BINOP_ADD:
193 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
194 case bitc::BINOP_SUB:
195 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
196 case bitc::BINOP_MUL:
197 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
198 case bitc::BINOP_UDIV: return Instruction::UDiv;
199 case bitc::BINOP_SDIV:
200 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
201 case bitc::BINOP_UREM: return Instruction::URem;
202 case bitc::BINOP_SREM:
203 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
204 case bitc::BINOP_SHL: return Instruction::Shl;
205 case bitc::BINOP_LSHR: return Instruction::LShr;
206 case bitc::BINOP_ASHR: return Instruction::AShr;
207 case bitc::BINOP_AND: return Instruction::And;
208 case bitc::BINOP_OR: return Instruction::Or;
209 case bitc::BINOP_XOR: return Instruction::Xor;
213 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
215 default: return AtomicRMWInst::BAD_BINOP;
216 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
217 case bitc::RMW_ADD: return AtomicRMWInst::Add;
218 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
219 case bitc::RMW_AND: return AtomicRMWInst::And;
220 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
221 case bitc::RMW_OR: return AtomicRMWInst::Or;
222 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
223 case bitc::RMW_MAX: return AtomicRMWInst::Max;
224 case bitc::RMW_MIN: return AtomicRMWInst::Min;
225 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
226 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
230 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
232 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
233 case bitc::ORDERING_UNORDERED: return Unordered;
234 case bitc::ORDERING_MONOTONIC: return Monotonic;
235 case bitc::ORDERING_ACQUIRE: return Acquire;
236 case bitc::ORDERING_RELEASE: return Release;
237 case bitc::ORDERING_ACQREL: return AcquireRelease;
238 default: // Map unknown orderings to sequentially-consistent.
239 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
243 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
245 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
246 default: // Map unknown scopes to cross-thread.
247 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
251 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
253 default: // Map unknown selection kinds to any.
254 case bitc::COMDAT_SELECTION_KIND_ANY:
256 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
257 return Comdat::ExactMatch;
258 case bitc::COMDAT_SELECTION_KIND_LARGEST:
259 return Comdat::Largest;
260 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
261 return Comdat::NoDuplicates;
262 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
263 return Comdat::SameSize;
267 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
269 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
270 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
276 /// @brief A class for maintaining the slot number definition
277 /// as a placeholder for the actual definition for forward constants defs.
278 class ConstantPlaceHolder : public ConstantExpr {
279 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
281 // allocate space for exactly one operand
282 void *operator new(size_t s) {
283 return User::operator new(s, 1);
285 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
286 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
287 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
290 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
291 static bool classof(const Value *V) {
292 return isa<ConstantExpr>(V) &&
293 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
297 /// Provide fast operand accessors
298 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
302 // FIXME: can we inherit this from ConstantExpr?
304 struct OperandTraits<ConstantPlaceHolder> :
305 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
307 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
311 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
320 WeakVH &OldV = ValuePtrs[Idx];
326 // Handle constants and non-constants (e.g. instrs) differently for
328 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
329 ResolveConstants.push_back(std::make_pair(PHC, Idx));
332 // If there was a forward reference to this value, replace it.
333 Value *PrevVal = OldV;
334 OldV->replaceAllUsesWith(V);
340 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
345 if (Value *V = ValuePtrs[Idx]) {
346 assert(Ty == V->getType() && "Type mismatch in constant table!");
347 return cast<Constant>(V);
350 // Create and return a placeholder, which will later be RAUW'd.
351 Constant *C = new ConstantPlaceHolder(Ty, Context);
356 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
360 if (Value *V = ValuePtrs[Idx]) {
361 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
365 // No type specified, must be invalid reference.
366 if (!Ty) return nullptr;
368 // Create and return a placeholder, which will later be RAUW'd.
369 Value *V = new Argument(Ty);
374 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
375 /// resolves any forward references. The idea behind this is that we sometimes
376 /// get constants (such as large arrays) which reference *many* forward ref
377 /// constants. Replacing each of these causes a lot of thrashing when
378 /// building/reuniquing the constant. Instead of doing this, we look at all the
379 /// uses and rewrite all the place holders at once for any constant that uses
381 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
382 // Sort the values by-pointer so that they are efficient to look up with a
384 std::sort(ResolveConstants.begin(), ResolveConstants.end());
386 SmallVector<Constant*, 64> NewOps;
388 while (!ResolveConstants.empty()) {
389 Value *RealVal = operator[](ResolveConstants.back().second);
390 Constant *Placeholder = ResolveConstants.back().first;
391 ResolveConstants.pop_back();
393 // Loop over all users of the placeholder, updating them to reference the
394 // new value. If they reference more than one placeholder, update them all
396 while (!Placeholder->use_empty()) {
397 auto UI = Placeholder->user_begin();
400 // If the using object isn't uniqued, just update the operands. This
401 // handles instructions and initializers for global variables.
402 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
403 UI.getUse().set(RealVal);
407 // Otherwise, we have a constant that uses the placeholder. Replace that
408 // constant with a new constant that has *all* placeholder uses updated.
409 Constant *UserC = cast<Constant>(U);
410 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
413 if (!isa<ConstantPlaceHolder>(*I)) {
414 // Not a placeholder reference.
416 } else if (*I == Placeholder) {
417 // Common case is that it just references this one placeholder.
420 // Otherwise, look up the placeholder in ResolveConstants.
421 ResolveConstantsTy::iterator It =
422 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
423 std::pair<Constant*, unsigned>(cast<Constant>(*I),
425 assert(It != ResolveConstants.end() && It->first == *I);
426 NewOp = operator[](It->second);
429 NewOps.push_back(cast<Constant>(NewOp));
432 // Make the new constant.
434 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
435 NewC = ConstantArray::get(UserCA->getType(), NewOps);
436 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
437 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
438 } else if (isa<ConstantVector>(UserC)) {
439 NewC = ConstantVector::get(NewOps);
441 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
442 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
445 UserC->replaceAllUsesWith(NewC);
446 UserC->destroyConstant();
450 // Update all ValueHandles, they should be the only users at this point.
451 Placeholder->replaceAllUsesWith(RealVal);
456 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
465 TrackingMDRef &OldMD = MDValuePtrs[Idx];
471 // If there was a forward reference to this value, replace it.
472 MDNodeFwdDecl *PrevMD = cast<MDNodeFwdDecl>(OldMD.get());
473 PrevMD->replaceAllUsesWith(MD);
474 MDNode::deleteTemporary(PrevMD);
478 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
482 if (Metadata *MD = MDValuePtrs[Idx])
485 // Create and return a placeholder, which will later be RAUW'd.
488 Metadata *MD = MDNode::getTemporary(Context, None);
489 MDValuePtrs[Idx].reset(MD);
493 void BitcodeReaderMDValueList::tryToResolveCycles() {
499 // Still forward references... can't resolve cycles.
502 // Resolve any cycles.
503 for (auto &MD : MDValuePtrs) {
504 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Unexpected forward reference");
505 if (auto *G = dyn_cast_or_null<GenericMDNode>(MD))
510 Type *BitcodeReader::getTypeByID(unsigned ID) {
511 // The type table size is always specified correctly.
512 if (ID >= TypeList.size())
515 if (Type *Ty = TypeList[ID])
518 // If we have a forward reference, the only possible case is when it is to a
519 // named struct. Just create a placeholder for now.
520 return TypeList[ID] = createIdentifiedStructType(Context);
523 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
525 auto *Ret = StructType::create(Context, Name);
526 IdentifiedStructTypes.push_back(Ret);
530 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
531 auto *Ret = StructType::create(Context);
532 IdentifiedStructTypes.push_back(Ret);
537 //===----------------------------------------------------------------------===//
538 // Functions for parsing blocks from the bitcode file
539 //===----------------------------------------------------------------------===//
542 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
543 /// been decoded from the given integer. This function must stay in sync with
544 /// 'encodeLLVMAttributesForBitcode'.
545 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
546 uint64_t EncodedAttrs) {
547 // FIXME: Remove in 4.0.
549 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
550 // the bits above 31 down by 11 bits.
551 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
552 assert((!Alignment || isPowerOf2_32(Alignment)) &&
553 "Alignment must be a power of two.");
556 B.addAlignmentAttr(Alignment);
557 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
558 (EncodedAttrs & 0xffff));
561 std::error_code BitcodeReader::ParseAttributeBlock() {
562 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
563 return Error(BitcodeError::InvalidRecord);
565 if (!MAttributes.empty())
566 return Error(BitcodeError::InvalidMultipleBlocks);
568 SmallVector<uint64_t, 64> Record;
570 SmallVector<AttributeSet, 8> Attrs;
572 // Read all the records.
574 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
576 switch (Entry.Kind) {
577 case BitstreamEntry::SubBlock: // Handled for us already.
578 case BitstreamEntry::Error:
579 return Error(BitcodeError::MalformedBlock);
580 case BitstreamEntry::EndBlock:
581 return std::error_code();
582 case BitstreamEntry::Record:
583 // The interesting case.
589 switch (Stream.readRecord(Entry.ID, Record)) {
590 default: // Default behavior: ignore.
592 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
593 // FIXME: Remove in 4.0.
594 if (Record.size() & 1)
595 return Error(BitcodeError::InvalidRecord);
597 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
599 decodeLLVMAttributesForBitcode(B, Record[i+1]);
600 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
603 MAttributes.push_back(AttributeSet::get(Context, Attrs));
607 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
608 for (unsigned i = 0, e = Record.size(); i != e; ++i)
609 Attrs.push_back(MAttributeGroups[Record[i]]);
611 MAttributes.push_back(AttributeSet::get(Context, Attrs));
619 // Returns Attribute::None on unrecognized codes.
620 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
623 return Attribute::None;
624 case bitc::ATTR_KIND_ALIGNMENT:
625 return Attribute::Alignment;
626 case bitc::ATTR_KIND_ALWAYS_INLINE:
627 return Attribute::AlwaysInline;
628 case bitc::ATTR_KIND_BUILTIN:
629 return Attribute::Builtin;
630 case bitc::ATTR_KIND_BY_VAL:
631 return Attribute::ByVal;
632 case bitc::ATTR_KIND_IN_ALLOCA:
633 return Attribute::InAlloca;
634 case bitc::ATTR_KIND_COLD:
635 return Attribute::Cold;
636 case bitc::ATTR_KIND_INLINE_HINT:
637 return Attribute::InlineHint;
638 case bitc::ATTR_KIND_IN_REG:
639 return Attribute::InReg;
640 case bitc::ATTR_KIND_JUMP_TABLE:
641 return Attribute::JumpTable;
642 case bitc::ATTR_KIND_MIN_SIZE:
643 return Attribute::MinSize;
644 case bitc::ATTR_KIND_NAKED:
645 return Attribute::Naked;
646 case bitc::ATTR_KIND_NEST:
647 return Attribute::Nest;
648 case bitc::ATTR_KIND_NO_ALIAS:
649 return Attribute::NoAlias;
650 case bitc::ATTR_KIND_NO_BUILTIN:
651 return Attribute::NoBuiltin;
652 case bitc::ATTR_KIND_NO_CAPTURE:
653 return Attribute::NoCapture;
654 case bitc::ATTR_KIND_NO_DUPLICATE:
655 return Attribute::NoDuplicate;
656 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
657 return Attribute::NoImplicitFloat;
658 case bitc::ATTR_KIND_NO_INLINE:
659 return Attribute::NoInline;
660 case bitc::ATTR_KIND_NON_LAZY_BIND:
661 return Attribute::NonLazyBind;
662 case bitc::ATTR_KIND_NON_NULL:
663 return Attribute::NonNull;
664 case bitc::ATTR_KIND_DEREFERENCEABLE:
665 return Attribute::Dereferenceable;
666 case bitc::ATTR_KIND_NO_RED_ZONE:
667 return Attribute::NoRedZone;
668 case bitc::ATTR_KIND_NO_RETURN:
669 return Attribute::NoReturn;
670 case bitc::ATTR_KIND_NO_UNWIND:
671 return Attribute::NoUnwind;
672 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
673 return Attribute::OptimizeForSize;
674 case bitc::ATTR_KIND_OPTIMIZE_NONE:
675 return Attribute::OptimizeNone;
676 case bitc::ATTR_KIND_READ_NONE:
677 return Attribute::ReadNone;
678 case bitc::ATTR_KIND_READ_ONLY:
679 return Attribute::ReadOnly;
680 case bitc::ATTR_KIND_RETURNED:
681 return Attribute::Returned;
682 case bitc::ATTR_KIND_RETURNS_TWICE:
683 return Attribute::ReturnsTwice;
684 case bitc::ATTR_KIND_S_EXT:
685 return Attribute::SExt;
686 case bitc::ATTR_KIND_STACK_ALIGNMENT:
687 return Attribute::StackAlignment;
688 case bitc::ATTR_KIND_STACK_PROTECT:
689 return Attribute::StackProtect;
690 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
691 return Attribute::StackProtectReq;
692 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
693 return Attribute::StackProtectStrong;
694 case bitc::ATTR_KIND_STRUCT_RET:
695 return Attribute::StructRet;
696 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
697 return Attribute::SanitizeAddress;
698 case bitc::ATTR_KIND_SANITIZE_THREAD:
699 return Attribute::SanitizeThread;
700 case bitc::ATTR_KIND_SANITIZE_MEMORY:
701 return Attribute::SanitizeMemory;
702 case bitc::ATTR_KIND_UW_TABLE:
703 return Attribute::UWTable;
704 case bitc::ATTR_KIND_Z_EXT:
705 return Attribute::ZExt;
709 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
710 Attribute::AttrKind *Kind) {
711 *Kind = GetAttrFromCode(Code);
712 if (*Kind == Attribute::None)
713 return Error(BitcodeError::InvalidValue);
714 return std::error_code();
717 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
718 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
719 return Error(BitcodeError::InvalidRecord);
721 if (!MAttributeGroups.empty())
722 return Error(BitcodeError::InvalidMultipleBlocks);
724 SmallVector<uint64_t, 64> Record;
726 // Read all the records.
728 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
730 switch (Entry.Kind) {
731 case BitstreamEntry::SubBlock: // Handled for us already.
732 case BitstreamEntry::Error:
733 return Error(BitcodeError::MalformedBlock);
734 case BitstreamEntry::EndBlock:
735 return std::error_code();
736 case BitstreamEntry::Record:
737 // The interesting case.
743 switch (Stream.readRecord(Entry.ID, Record)) {
744 default: // Default behavior: ignore.
746 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
747 if (Record.size() < 3)
748 return Error(BitcodeError::InvalidRecord);
750 uint64_t GrpID = Record[0];
751 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
754 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
755 if (Record[i] == 0) { // Enum attribute
756 Attribute::AttrKind Kind;
757 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
760 B.addAttribute(Kind);
761 } else if (Record[i] == 1) { // Integer attribute
762 Attribute::AttrKind Kind;
763 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
765 if (Kind == Attribute::Alignment)
766 B.addAlignmentAttr(Record[++i]);
767 else if (Kind == Attribute::StackAlignment)
768 B.addStackAlignmentAttr(Record[++i]);
769 else if (Kind == Attribute::Dereferenceable)
770 B.addDereferenceableAttr(Record[++i]);
771 } else { // String attribute
772 assert((Record[i] == 3 || Record[i] == 4) &&
773 "Invalid attribute group entry");
774 bool HasValue = (Record[i++] == 4);
775 SmallString<64> KindStr;
776 SmallString<64> ValStr;
778 while (Record[i] != 0 && i != e)
779 KindStr += Record[i++];
780 assert(Record[i] == 0 && "Kind string not null terminated");
783 // Has a value associated with it.
784 ++i; // Skip the '0' that terminates the "kind" string.
785 while (Record[i] != 0 && i != e)
786 ValStr += Record[i++];
787 assert(Record[i] == 0 && "Value string not null terminated");
790 B.addAttribute(KindStr.str(), ValStr.str());
794 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
801 std::error_code BitcodeReader::ParseTypeTable() {
802 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
803 return Error(BitcodeError::InvalidRecord);
805 return ParseTypeTableBody();
808 std::error_code BitcodeReader::ParseTypeTableBody() {
809 if (!TypeList.empty())
810 return Error(BitcodeError::InvalidMultipleBlocks);
812 SmallVector<uint64_t, 64> Record;
813 unsigned NumRecords = 0;
815 SmallString<64> TypeName;
817 // Read all the records for this type table.
819 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
821 switch (Entry.Kind) {
822 case BitstreamEntry::SubBlock: // Handled for us already.
823 case BitstreamEntry::Error:
824 return Error(BitcodeError::MalformedBlock);
825 case BitstreamEntry::EndBlock:
826 if (NumRecords != TypeList.size())
827 return Error(BitcodeError::MalformedBlock);
828 return std::error_code();
829 case BitstreamEntry::Record:
830 // The interesting case.
836 Type *ResultTy = nullptr;
837 switch (Stream.readRecord(Entry.ID, Record)) {
839 return Error(BitcodeError::InvalidValue);
840 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
841 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
842 // type list. This allows us to reserve space.
843 if (Record.size() < 1)
844 return Error(BitcodeError::InvalidRecord);
845 TypeList.resize(Record[0]);
847 case bitc::TYPE_CODE_VOID: // VOID
848 ResultTy = Type::getVoidTy(Context);
850 case bitc::TYPE_CODE_HALF: // HALF
851 ResultTy = Type::getHalfTy(Context);
853 case bitc::TYPE_CODE_FLOAT: // FLOAT
854 ResultTy = Type::getFloatTy(Context);
856 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
857 ResultTy = Type::getDoubleTy(Context);
859 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
860 ResultTy = Type::getX86_FP80Ty(Context);
862 case bitc::TYPE_CODE_FP128: // FP128
863 ResultTy = Type::getFP128Ty(Context);
865 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
866 ResultTy = Type::getPPC_FP128Ty(Context);
868 case bitc::TYPE_CODE_LABEL: // LABEL
869 ResultTy = Type::getLabelTy(Context);
871 case bitc::TYPE_CODE_METADATA: // METADATA
872 ResultTy = Type::getMetadataTy(Context);
874 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
875 ResultTy = Type::getX86_MMXTy(Context);
877 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
878 if (Record.size() < 1)
879 return Error(BitcodeError::InvalidRecord);
881 ResultTy = IntegerType::get(Context, Record[0]);
883 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
884 // [pointee type, address space]
885 if (Record.size() < 1)
886 return Error(BitcodeError::InvalidRecord);
887 unsigned AddressSpace = 0;
888 if (Record.size() == 2)
889 AddressSpace = Record[1];
890 ResultTy = getTypeByID(Record[0]);
892 return Error(BitcodeError::InvalidType);
893 ResultTy = PointerType::get(ResultTy, AddressSpace);
896 case bitc::TYPE_CODE_FUNCTION_OLD: {
897 // FIXME: attrid is dead, remove it in LLVM 4.0
898 // FUNCTION: [vararg, attrid, retty, paramty x N]
899 if (Record.size() < 3)
900 return Error(BitcodeError::InvalidRecord);
901 SmallVector<Type*, 8> ArgTys;
902 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
903 if (Type *T = getTypeByID(Record[i]))
909 ResultTy = getTypeByID(Record[2]);
910 if (!ResultTy || ArgTys.size() < Record.size()-3)
911 return Error(BitcodeError::InvalidType);
913 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
916 case bitc::TYPE_CODE_FUNCTION: {
917 // FUNCTION: [vararg, retty, paramty x N]
918 if (Record.size() < 2)
919 return Error(BitcodeError::InvalidRecord);
920 SmallVector<Type*, 8> ArgTys;
921 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
922 if (Type *T = getTypeByID(Record[i]))
928 ResultTy = getTypeByID(Record[1]);
929 if (!ResultTy || ArgTys.size() < Record.size()-2)
930 return Error(BitcodeError::InvalidType);
932 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
935 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
936 if (Record.size() < 1)
937 return Error(BitcodeError::InvalidRecord);
938 SmallVector<Type*, 8> EltTys;
939 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
940 if (Type *T = getTypeByID(Record[i]))
945 if (EltTys.size() != Record.size()-1)
946 return Error(BitcodeError::InvalidType);
947 ResultTy = StructType::get(Context, EltTys, Record[0]);
950 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
951 if (ConvertToString(Record, 0, TypeName))
952 return Error(BitcodeError::InvalidRecord);
955 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
956 if (Record.size() < 1)
957 return Error(BitcodeError::InvalidRecord);
959 if (NumRecords >= TypeList.size())
960 return Error(BitcodeError::InvalidTYPETable);
962 // Check to see if this was forward referenced, if so fill in the temp.
963 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
965 Res->setName(TypeName);
966 TypeList[NumRecords] = nullptr;
967 } else // Otherwise, create a new struct.
968 Res = createIdentifiedStructType(Context, TypeName);
971 SmallVector<Type*, 8> EltTys;
972 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
973 if (Type *T = getTypeByID(Record[i]))
978 if (EltTys.size() != Record.size()-1)
979 return Error(BitcodeError::InvalidRecord);
980 Res->setBody(EltTys, Record[0]);
984 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
985 if (Record.size() != 1)
986 return Error(BitcodeError::InvalidRecord);
988 if (NumRecords >= TypeList.size())
989 return Error(BitcodeError::InvalidTYPETable);
991 // Check to see if this was forward referenced, if so fill in the temp.
992 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
994 Res->setName(TypeName);
995 TypeList[NumRecords] = nullptr;
996 } else // Otherwise, create a new struct with no body.
997 Res = createIdentifiedStructType(Context, TypeName);
1002 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1003 if (Record.size() < 2)
1004 return Error(BitcodeError::InvalidRecord);
1005 if ((ResultTy = getTypeByID(Record[1])))
1006 ResultTy = ArrayType::get(ResultTy, Record[0]);
1008 return Error(BitcodeError::InvalidType);
1010 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1011 if (Record.size() < 2)
1012 return Error(BitcodeError::InvalidRecord);
1013 if ((ResultTy = getTypeByID(Record[1])))
1014 ResultTy = VectorType::get(ResultTy, Record[0]);
1016 return Error(BitcodeError::InvalidType);
1020 if (NumRecords >= TypeList.size())
1021 return Error(BitcodeError::InvalidTYPETable);
1022 assert(ResultTy && "Didn't read a type?");
1023 assert(!TypeList[NumRecords] && "Already read type?");
1024 TypeList[NumRecords++] = ResultTy;
1028 std::error_code BitcodeReader::ParseValueSymbolTable() {
1029 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1030 return Error(BitcodeError::InvalidRecord);
1032 SmallVector<uint64_t, 64> Record;
1034 // Read all the records for this value table.
1035 SmallString<128> ValueName;
1037 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1039 switch (Entry.Kind) {
1040 case BitstreamEntry::SubBlock: // Handled for us already.
1041 case BitstreamEntry::Error:
1042 return Error(BitcodeError::MalformedBlock);
1043 case BitstreamEntry::EndBlock:
1044 return std::error_code();
1045 case BitstreamEntry::Record:
1046 // The interesting case.
1052 switch (Stream.readRecord(Entry.ID, Record)) {
1053 default: // Default behavior: unknown type.
1055 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1056 if (ConvertToString(Record, 1, ValueName))
1057 return Error(BitcodeError::InvalidRecord);
1058 unsigned ValueID = Record[0];
1059 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1060 return Error(BitcodeError::InvalidRecord);
1061 Value *V = ValueList[ValueID];
1063 V->setName(StringRef(ValueName.data(), ValueName.size()));
1067 case bitc::VST_CODE_BBENTRY: {
1068 if (ConvertToString(Record, 1, ValueName))
1069 return Error(BitcodeError::InvalidRecord);
1070 BasicBlock *BB = getBasicBlock(Record[0]);
1072 return Error(BitcodeError::InvalidRecord);
1074 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1082 std::error_code BitcodeReader::ParseMetadata() {
1083 unsigned NextMDValueNo = MDValueList.size();
1085 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1086 return Error(BitcodeError::InvalidRecord);
1088 SmallVector<uint64_t, 64> Record;
1090 // Read all the records.
1092 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1094 switch (Entry.Kind) {
1095 case BitstreamEntry::SubBlock: // Handled for us already.
1096 case BitstreamEntry::Error:
1097 return Error(BitcodeError::MalformedBlock);
1098 case BitstreamEntry::EndBlock:
1099 MDValueList.tryToResolveCycles();
1100 return std::error_code();
1101 case BitstreamEntry::Record:
1102 // The interesting case.
1108 unsigned Code = Stream.readRecord(Entry.ID, Record);
1109 bool IsDistinct = false;
1111 default: // Default behavior: ignore.
1113 case bitc::METADATA_NAME: {
1114 // Read name of the named metadata.
1115 SmallString<8> Name(Record.begin(), Record.end());
1117 Code = Stream.ReadCode();
1119 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1120 unsigned NextBitCode = Stream.readRecord(Code, Record);
1121 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1123 // Read named metadata elements.
1124 unsigned Size = Record.size();
1125 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1126 for (unsigned i = 0; i != Size; ++i) {
1127 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1129 return Error(BitcodeError::InvalidRecord);
1130 NMD->addOperand(MD);
1134 case bitc::METADATA_OLD_FN_NODE: {
1135 // FIXME: Remove in 4.0.
1136 // This is a LocalAsMetadata record, the only type of function-local
1138 if (Record.size() % 2 == 1)
1139 return Error(BitcodeError::InvalidRecord);
1141 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1142 // to be legal, but there's no upgrade path.
1143 auto dropRecord = [&] {
1144 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1146 if (Record.size() != 2) {
1151 Type *Ty = getTypeByID(Record[0]);
1152 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1157 MDValueList.AssignValue(
1158 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1162 case bitc::METADATA_OLD_NODE: {
1163 // FIXME: Remove in 4.0.
1164 if (Record.size() % 2 == 1)
1165 return Error(BitcodeError::InvalidRecord);
1167 unsigned Size = Record.size();
1168 SmallVector<Metadata *, 8> Elts;
1169 for (unsigned i = 0; i != Size; i += 2) {
1170 Type *Ty = getTypeByID(Record[i]);
1172 return Error(BitcodeError::InvalidRecord);
1173 if (Ty->isMetadataTy())
1174 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1175 else if (!Ty->isVoidTy()) {
1177 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1178 assert(isa<ConstantAsMetadata>(MD) &&
1179 "Expected non-function-local metadata");
1182 Elts.push_back(nullptr);
1184 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1187 case bitc::METADATA_VALUE: {
1188 if (Record.size() != 2)
1189 return Error(BitcodeError::InvalidRecord);
1191 Type *Ty = getTypeByID(Record[0]);
1192 if (Ty->isMetadataTy() || Ty->isVoidTy())
1193 return Error(BitcodeError::InvalidRecord);
1195 MDValueList.AssignValue(
1196 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1200 case bitc::METADATA_DISTINCT_NODE:
1203 case bitc::METADATA_NODE: {
1204 SmallVector<Metadata *, 8> Elts;
1205 Elts.reserve(Record.size());
1206 for (unsigned ID : Record)
1207 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1208 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1209 : MDNode::get(Context, Elts),
1213 case bitc::METADATA_STRING: {
1214 std::string String(Record.begin(), Record.end());
1215 llvm::UpgradeMDStringConstant(String);
1216 Metadata *MD = MDString::get(Context, String);
1217 MDValueList.AssignValue(MD, NextMDValueNo++);
1220 case bitc::METADATA_KIND: {
1221 if (Record.size() < 2)
1222 return Error(BitcodeError::InvalidRecord);
1224 unsigned Kind = Record[0];
1225 SmallString<8> Name(Record.begin()+1, Record.end());
1227 unsigned NewKind = TheModule->getMDKindID(Name.str());
1228 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1229 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1236 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1237 /// the LSB for dense VBR encoding.
1238 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1243 // There is no such thing as -0 with integers. "-0" really means MININT.
1247 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1248 /// values and aliases that we can.
1249 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1250 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1251 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1252 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1253 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1255 GlobalInitWorklist.swap(GlobalInits);
1256 AliasInitWorklist.swap(AliasInits);
1257 FunctionPrefixWorklist.swap(FunctionPrefixes);
1258 FunctionPrologueWorklist.swap(FunctionPrologues);
1260 while (!GlobalInitWorklist.empty()) {
1261 unsigned ValID = GlobalInitWorklist.back().second;
1262 if (ValID >= ValueList.size()) {
1263 // Not ready to resolve this yet, it requires something later in the file.
1264 GlobalInits.push_back(GlobalInitWorklist.back());
1266 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1267 GlobalInitWorklist.back().first->setInitializer(C);
1269 return Error(BitcodeError::ExpectedConstant);
1271 GlobalInitWorklist.pop_back();
1274 while (!AliasInitWorklist.empty()) {
1275 unsigned ValID = AliasInitWorklist.back().second;
1276 if (ValID >= ValueList.size()) {
1277 AliasInits.push_back(AliasInitWorklist.back());
1279 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1280 AliasInitWorklist.back().first->setAliasee(C);
1282 return Error(BitcodeError::ExpectedConstant);
1284 AliasInitWorklist.pop_back();
1287 while (!FunctionPrefixWorklist.empty()) {
1288 unsigned ValID = FunctionPrefixWorklist.back().second;
1289 if (ValID >= ValueList.size()) {
1290 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1292 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1293 FunctionPrefixWorklist.back().first->setPrefixData(C);
1295 return Error(BitcodeError::ExpectedConstant);
1297 FunctionPrefixWorklist.pop_back();
1300 while (!FunctionPrologueWorklist.empty()) {
1301 unsigned ValID = FunctionPrologueWorklist.back().second;
1302 if (ValID >= ValueList.size()) {
1303 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1305 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1306 FunctionPrologueWorklist.back().first->setPrologueData(C);
1308 return Error(BitcodeError::ExpectedConstant);
1310 FunctionPrologueWorklist.pop_back();
1313 return std::error_code();
1316 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1317 SmallVector<uint64_t, 8> Words(Vals.size());
1318 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1319 BitcodeReader::decodeSignRotatedValue);
1321 return APInt(TypeBits, Words);
1324 std::error_code BitcodeReader::ParseConstants() {
1325 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1326 return Error(BitcodeError::InvalidRecord);
1328 SmallVector<uint64_t, 64> Record;
1330 // Read all the records for this value table.
1331 Type *CurTy = Type::getInt32Ty(Context);
1332 unsigned NextCstNo = ValueList.size();
1334 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1336 switch (Entry.Kind) {
1337 case BitstreamEntry::SubBlock: // Handled for us already.
1338 case BitstreamEntry::Error:
1339 return Error(BitcodeError::MalformedBlock);
1340 case BitstreamEntry::EndBlock:
1341 if (NextCstNo != ValueList.size())
1342 return Error(BitcodeError::InvalidConstantReference);
1344 // Once all the constants have been read, go through and resolve forward
1346 ValueList.ResolveConstantForwardRefs();
1347 return std::error_code();
1348 case BitstreamEntry::Record:
1349 // The interesting case.
1356 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1358 default: // Default behavior: unknown constant
1359 case bitc::CST_CODE_UNDEF: // UNDEF
1360 V = UndefValue::get(CurTy);
1362 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1364 return Error(BitcodeError::InvalidRecord);
1365 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1366 return Error(BitcodeError::InvalidRecord);
1367 CurTy = TypeList[Record[0]];
1368 continue; // Skip the ValueList manipulation.
1369 case bitc::CST_CODE_NULL: // NULL
1370 V = Constant::getNullValue(CurTy);
1372 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1373 if (!CurTy->isIntegerTy() || Record.empty())
1374 return Error(BitcodeError::InvalidRecord);
1375 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1377 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1378 if (!CurTy->isIntegerTy() || Record.empty())
1379 return Error(BitcodeError::InvalidRecord);
1381 APInt VInt = ReadWideAPInt(Record,
1382 cast<IntegerType>(CurTy)->getBitWidth());
1383 V = ConstantInt::get(Context, VInt);
1387 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1389 return Error(BitcodeError::InvalidRecord);
1390 if (CurTy->isHalfTy())
1391 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1392 APInt(16, (uint16_t)Record[0])));
1393 else if (CurTy->isFloatTy())
1394 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1395 APInt(32, (uint32_t)Record[0])));
1396 else if (CurTy->isDoubleTy())
1397 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1398 APInt(64, Record[0])));
1399 else if (CurTy->isX86_FP80Ty()) {
1400 // Bits are not stored the same way as a normal i80 APInt, compensate.
1401 uint64_t Rearrange[2];
1402 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1403 Rearrange[1] = Record[0] >> 48;
1404 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1405 APInt(80, Rearrange)));
1406 } else if (CurTy->isFP128Ty())
1407 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1408 APInt(128, Record)));
1409 else if (CurTy->isPPC_FP128Ty())
1410 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1411 APInt(128, Record)));
1413 V = UndefValue::get(CurTy);
1417 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1419 return Error(BitcodeError::InvalidRecord);
1421 unsigned Size = Record.size();
1422 SmallVector<Constant*, 16> Elts;
1424 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1425 for (unsigned i = 0; i != Size; ++i)
1426 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1427 STy->getElementType(i)));
1428 V = ConstantStruct::get(STy, Elts);
1429 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1430 Type *EltTy = ATy->getElementType();
1431 for (unsigned i = 0; i != Size; ++i)
1432 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1433 V = ConstantArray::get(ATy, Elts);
1434 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1435 Type *EltTy = VTy->getElementType();
1436 for (unsigned i = 0; i != Size; ++i)
1437 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1438 V = ConstantVector::get(Elts);
1440 V = UndefValue::get(CurTy);
1444 case bitc::CST_CODE_STRING: // STRING: [values]
1445 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1447 return Error(BitcodeError::InvalidRecord);
1449 SmallString<16> Elts(Record.begin(), Record.end());
1450 V = ConstantDataArray::getString(Context, Elts,
1451 BitCode == bitc::CST_CODE_CSTRING);
1454 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1456 return Error(BitcodeError::InvalidRecord);
1458 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1459 unsigned Size = Record.size();
1461 if (EltTy->isIntegerTy(8)) {
1462 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1463 if (isa<VectorType>(CurTy))
1464 V = ConstantDataVector::get(Context, Elts);
1466 V = ConstantDataArray::get(Context, Elts);
1467 } else if (EltTy->isIntegerTy(16)) {
1468 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1469 if (isa<VectorType>(CurTy))
1470 V = ConstantDataVector::get(Context, Elts);
1472 V = ConstantDataArray::get(Context, Elts);
1473 } else if (EltTy->isIntegerTy(32)) {
1474 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1475 if (isa<VectorType>(CurTy))
1476 V = ConstantDataVector::get(Context, Elts);
1478 V = ConstantDataArray::get(Context, Elts);
1479 } else if (EltTy->isIntegerTy(64)) {
1480 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1481 if (isa<VectorType>(CurTy))
1482 V = ConstantDataVector::get(Context, Elts);
1484 V = ConstantDataArray::get(Context, Elts);
1485 } else if (EltTy->isFloatTy()) {
1486 SmallVector<float, 16> Elts(Size);
1487 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1488 if (isa<VectorType>(CurTy))
1489 V = ConstantDataVector::get(Context, Elts);
1491 V = ConstantDataArray::get(Context, Elts);
1492 } else if (EltTy->isDoubleTy()) {
1493 SmallVector<double, 16> Elts(Size);
1494 std::transform(Record.begin(), Record.end(), Elts.begin(),
1496 if (isa<VectorType>(CurTy))
1497 V = ConstantDataVector::get(Context, Elts);
1499 V = ConstantDataArray::get(Context, Elts);
1501 return Error(BitcodeError::InvalidTypeForValue);
1506 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1507 if (Record.size() < 3)
1508 return Error(BitcodeError::InvalidRecord);
1509 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1511 V = UndefValue::get(CurTy); // Unknown binop.
1513 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1514 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1516 if (Record.size() >= 4) {
1517 if (Opc == Instruction::Add ||
1518 Opc == Instruction::Sub ||
1519 Opc == Instruction::Mul ||
1520 Opc == Instruction::Shl) {
1521 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1522 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1523 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1524 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1525 } else if (Opc == Instruction::SDiv ||
1526 Opc == Instruction::UDiv ||
1527 Opc == Instruction::LShr ||
1528 Opc == Instruction::AShr) {
1529 if (Record[3] & (1 << bitc::PEO_EXACT))
1530 Flags |= SDivOperator::IsExact;
1533 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1537 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1538 if (Record.size() < 3)
1539 return Error(BitcodeError::InvalidRecord);
1540 int Opc = GetDecodedCastOpcode(Record[0]);
1542 V = UndefValue::get(CurTy); // Unknown cast.
1544 Type *OpTy = getTypeByID(Record[1]);
1546 return Error(BitcodeError::InvalidRecord);
1547 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1548 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1549 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1553 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1554 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1555 if (Record.size() & 1)
1556 return Error(BitcodeError::InvalidRecord);
1557 SmallVector<Constant*, 16> Elts;
1558 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1559 Type *ElTy = getTypeByID(Record[i]);
1561 return Error(BitcodeError::InvalidRecord);
1562 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1564 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1565 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1567 bitc::CST_CODE_CE_INBOUNDS_GEP);
1570 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1571 if (Record.size() < 3)
1572 return Error(BitcodeError::InvalidRecord);
1574 Type *SelectorTy = Type::getInt1Ty(Context);
1576 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1577 // vector. Otherwise, it must be a single bit.
1578 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1579 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1580 VTy->getNumElements());
1582 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1584 ValueList.getConstantFwdRef(Record[1],CurTy),
1585 ValueList.getConstantFwdRef(Record[2],CurTy));
1588 case bitc::CST_CODE_CE_EXTRACTELT
1589 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1590 if (Record.size() < 3)
1591 return Error(BitcodeError::InvalidRecord);
1593 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1595 return Error(BitcodeError::InvalidRecord);
1596 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1597 Constant *Op1 = nullptr;
1598 if (Record.size() == 4) {
1599 Type *IdxTy = getTypeByID(Record[2]);
1601 return Error(BitcodeError::InvalidRecord);
1602 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1603 } else // TODO: Remove with llvm 4.0
1604 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1606 return Error(BitcodeError::InvalidRecord);
1607 V = ConstantExpr::getExtractElement(Op0, Op1);
1610 case bitc::CST_CODE_CE_INSERTELT
1611 : { // CE_INSERTELT: [opval, opval, opty, opval]
1612 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1613 if (Record.size() < 3 || !OpTy)
1614 return Error(BitcodeError::InvalidRecord);
1615 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1616 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1617 OpTy->getElementType());
1618 Constant *Op2 = nullptr;
1619 if (Record.size() == 4) {
1620 Type *IdxTy = getTypeByID(Record[2]);
1622 return Error(BitcodeError::InvalidRecord);
1623 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1624 } else // TODO: Remove with llvm 4.0
1625 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1627 return Error(BitcodeError::InvalidRecord);
1628 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1631 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1632 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1633 if (Record.size() < 3 || !OpTy)
1634 return Error(BitcodeError::InvalidRecord);
1635 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1636 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1637 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1638 OpTy->getNumElements());
1639 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1640 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1643 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1644 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1646 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1647 if (Record.size() < 4 || !RTy || !OpTy)
1648 return Error(BitcodeError::InvalidRecord);
1649 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1650 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1651 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1652 RTy->getNumElements());
1653 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1654 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1657 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1658 if (Record.size() < 4)
1659 return Error(BitcodeError::InvalidRecord);
1660 Type *OpTy = getTypeByID(Record[0]);
1662 return Error(BitcodeError::InvalidRecord);
1663 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1664 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1666 if (OpTy->isFPOrFPVectorTy())
1667 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1669 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1672 // This maintains backward compatibility, pre-asm dialect keywords.
1673 // FIXME: Remove with the 4.0 release.
1674 case bitc::CST_CODE_INLINEASM_OLD: {
1675 if (Record.size() < 2)
1676 return Error(BitcodeError::InvalidRecord);
1677 std::string AsmStr, ConstrStr;
1678 bool HasSideEffects = Record[0] & 1;
1679 bool IsAlignStack = Record[0] >> 1;
1680 unsigned AsmStrSize = Record[1];
1681 if (2+AsmStrSize >= Record.size())
1682 return Error(BitcodeError::InvalidRecord);
1683 unsigned ConstStrSize = Record[2+AsmStrSize];
1684 if (3+AsmStrSize+ConstStrSize > Record.size())
1685 return Error(BitcodeError::InvalidRecord);
1687 for (unsigned i = 0; i != AsmStrSize; ++i)
1688 AsmStr += (char)Record[2+i];
1689 for (unsigned i = 0; i != ConstStrSize; ++i)
1690 ConstrStr += (char)Record[3+AsmStrSize+i];
1691 PointerType *PTy = cast<PointerType>(CurTy);
1692 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1693 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1696 // This version adds support for the asm dialect keywords (e.g.,
1698 case bitc::CST_CODE_INLINEASM: {
1699 if (Record.size() < 2)
1700 return Error(BitcodeError::InvalidRecord);
1701 std::string AsmStr, ConstrStr;
1702 bool HasSideEffects = Record[0] & 1;
1703 bool IsAlignStack = (Record[0] >> 1) & 1;
1704 unsigned AsmDialect = Record[0] >> 2;
1705 unsigned AsmStrSize = Record[1];
1706 if (2+AsmStrSize >= Record.size())
1707 return Error(BitcodeError::InvalidRecord);
1708 unsigned ConstStrSize = Record[2+AsmStrSize];
1709 if (3+AsmStrSize+ConstStrSize > Record.size())
1710 return Error(BitcodeError::InvalidRecord);
1712 for (unsigned i = 0; i != AsmStrSize; ++i)
1713 AsmStr += (char)Record[2+i];
1714 for (unsigned i = 0; i != ConstStrSize; ++i)
1715 ConstrStr += (char)Record[3+AsmStrSize+i];
1716 PointerType *PTy = cast<PointerType>(CurTy);
1717 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1718 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1719 InlineAsm::AsmDialect(AsmDialect));
1722 case bitc::CST_CODE_BLOCKADDRESS:{
1723 if (Record.size() < 3)
1724 return Error(BitcodeError::InvalidRecord);
1725 Type *FnTy = getTypeByID(Record[0]);
1727 return Error(BitcodeError::InvalidRecord);
1729 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1731 return Error(BitcodeError::InvalidRecord);
1733 // Don't let Fn get dematerialized.
1734 BlockAddressesTaken.insert(Fn);
1736 // If the function is already parsed we can insert the block address right
1739 unsigned BBID = Record[2];
1741 // Invalid reference to entry block.
1742 return Error(BitcodeError::InvalidID);
1744 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1745 for (size_t I = 0, E = BBID; I != E; ++I) {
1747 return Error(BitcodeError::InvalidID);
1752 // Otherwise insert a placeholder and remember it so it can be inserted
1753 // when the function is parsed.
1754 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1756 BasicBlockFwdRefQueue.push_back(Fn);
1757 if (FwdBBs.size() < BBID + 1)
1758 FwdBBs.resize(BBID + 1);
1760 FwdBBs[BBID] = BasicBlock::Create(Context);
1763 V = BlockAddress::get(Fn, BB);
1768 ValueList.AssignValue(V, NextCstNo);
1773 std::error_code BitcodeReader::ParseUseLists() {
1774 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1775 return Error(BitcodeError::InvalidRecord);
1777 // Read all the records.
1778 SmallVector<uint64_t, 64> Record;
1780 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1782 switch (Entry.Kind) {
1783 case BitstreamEntry::SubBlock: // Handled for us already.
1784 case BitstreamEntry::Error:
1785 return Error(BitcodeError::MalformedBlock);
1786 case BitstreamEntry::EndBlock:
1787 return std::error_code();
1788 case BitstreamEntry::Record:
1789 // The interesting case.
1793 // Read a use list record.
1796 switch (Stream.readRecord(Entry.ID, Record)) {
1797 default: // Default behavior: unknown type.
1799 case bitc::USELIST_CODE_BB:
1802 case bitc::USELIST_CODE_DEFAULT: {
1803 unsigned RecordLength = Record.size();
1804 if (RecordLength < 3)
1805 // Records should have at least an ID and two indexes.
1806 return Error(BitcodeError::InvalidRecord);
1807 unsigned ID = Record.back();
1812 assert(ID < FunctionBBs.size() && "Basic block not found");
1813 V = FunctionBBs[ID];
1816 unsigned NumUses = 0;
1817 SmallDenseMap<const Use *, unsigned, 16> Order;
1818 for (const Use &U : V->uses()) {
1819 if (++NumUses > Record.size())
1821 Order[&U] = Record[NumUses - 1];
1823 if (Order.size() != Record.size() || NumUses > Record.size())
1824 // Mismatches can happen if the functions are being materialized lazily
1825 // (out-of-order), or a value has been upgraded.
1828 V->sortUseList([&](const Use &L, const Use &R) {
1829 return Order.lookup(&L) < Order.lookup(&R);
1837 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1838 /// remember where it is and then skip it. This lets us lazily deserialize the
1840 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1841 // Get the function we are talking about.
1842 if (FunctionsWithBodies.empty())
1843 return Error(BitcodeError::InsufficientFunctionProtos);
1845 Function *Fn = FunctionsWithBodies.back();
1846 FunctionsWithBodies.pop_back();
1848 // Save the current stream state.
1849 uint64_t CurBit = Stream.GetCurrentBitNo();
1850 DeferredFunctionInfo[Fn] = CurBit;
1852 // Skip over the function block for now.
1853 if (Stream.SkipBlock())
1854 return Error(BitcodeError::InvalidRecord);
1855 return std::error_code();
1858 std::error_code BitcodeReader::GlobalCleanup() {
1859 // Patch the initializers for globals and aliases up.
1860 ResolveGlobalAndAliasInits();
1861 if (!GlobalInits.empty() || !AliasInits.empty())
1862 return Error(BitcodeError::MalformedGlobalInitializerSet);
1864 // Look for intrinsic functions which need to be upgraded at some point
1865 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1868 if (UpgradeIntrinsicFunction(FI, NewFn))
1869 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1872 // Look for global variables which need to be renamed.
1873 for (Module::global_iterator
1874 GI = TheModule->global_begin(), GE = TheModule->global_end();
1876 GlobalVariable *GV = GI++;
1877 UpgradeGlobalVariable(GV);
1880 // Force deallocation of memory for these vectors to favor the client that
1881 // want lazy deserialization.
1882 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1883 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1884 return std::error_code();
1887 std::error_code BitcodeReader::ParseModule(bool Resume) {
1889 Stream.JumpToBit(NextUnreadBit);
1890 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1891 return Error(BitcodeError::InvalidRecord);
1893 SmallVector<uint64_t, 64> Record;
1894 std::vector<std::string> SectionTable;
1895 std::vector<std::string> GCTable;
1897 // Read all the records for this module.
1899 BitstreamEntry Entry = Stream.advance();
1901 switch (Entry.Kind) {
1902 case BitstreamEntry::Error:
1903 return Error(BitcodeError::MalformedBlock);
1904 case BitstreamEntry::EndBlock:
1905 return GlobalCleanup();
1907 case BitstreamEntry::SubBlock:
1909 default: // Skip unknown content.
1910 if (Stream.SkipBlock())
1911 return Error(BitcodeError::InvalidRecord);
1913 case bitc::BLOCKINFO_BLOCK_ID:
1914 if (Stream.ReadBlockInfoBlock())
1915 return Error(BitcodeError::MalformedBlock);
1917 case bitc::PARAMATTR_BLOCK_ID:
1918 if (std::error_code EC = ParseAttributeBlock())
1921 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1922 if (std::error_code EC = ParseAttributeGroupBlock())
1925 case bitc::TYPE_BLOCK_ID_NEW:
1926 if (std::error_code EC = ParseTypeTable())
1929 case bitc::VALUE_SYMTAB_BLOCK_ID:
1930 if (std::error_code EC = ParseValueSymbolTable())
1932 SeenValueSymbolTable = true;
1934 case bitc::CONSTANTS_BLOCK_ID:
1935 if (std::error_code EC = ParseConstants())
1937 if (std::error_code EC = ResolveGlobalAndAliasInits())
1940 case bitc::METADATA_BLOCK_ID:
1941 if (std::error_code EC = ParseMetadata())
1944 case bitc::FUNCTION_BLOCK_ID:
1945 // If this is the first function body we've seen, reverse the
1946 // FunctionsWithBodies list.
1947 if (!SeenFirstFunctionBody) {
1948 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1949 if (std::error_code EC = GlobalCleanup())
1951 SeenFirstFunctionBody = true;
1954 if (std::error_code EC = RememberAndSkipFunctionBody())
1956 // For streaming bitcode, suspend parsing when we reach the function
1957 // bodies. Subsequent materialization calls will resume it when
1958 // necessary. For streaming, the function bodies must be at the end of
1959 // the bitcode. If the bitcode file is old, the symbol table will be
1960 // at the end instead and will not have been seen yet. In this case,
1961 // just finish the parse now.
1962 if (LazyStreamer && SeenValueSymbolTable) {
1963 NextUnreadBit = Stream.GetCurrentBitNo();
1964 return std::error_code();
1967 case bitc::USELIST_BLOCK_ID:
1968 if (std::error_code EC = ParseUseLists())
1974 case BitstreamEntry::Record:
1975 // The interesting case.
1981 switch (Stream.readRecord(Entry.ID, Record)) {
1982 default: break; // Default behavior, ignore unknown content.
1983 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1984 if (Record.size() < 1)
1985 return Error(BitcodeError::InvalidRecord);
1986 // Only version #0 and #1 are supported so far.
1987 unsigned module_version = Record[0];
1988 switch (module_version) {
1990 return Error(BitcodeError::InvalidValue);
1992 UseRelativeIDs = false;
1995 UseRelativeIDs = true;
2000 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2002 if (ConvertToString(Record, 0, S))
2003 return Error(BitcodeError::InvalidRecord);
2004 TheModule->setTargetTriple(S);
2007 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2009 if (ConvertToString(Record, 0, S))
2010 return Error(BitcodeError::InvalidRecord);
2011 TheModule->setDataLayout(S);
2014 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2016 if (ConvertToString(Record, 0, S))
2017 return Error(BitcodeError::InvalidRecord);
2018 TheModule->setModuleInlineAsm(S);
2021 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2022 // FIXME: Remove in 4.0.
2024 if (ConvertToString(Record, 0, S))
2025 return Error(BitcodeError::InvalidRecord);
2029 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2031 if (ConvertToString(Record, 0, S))
2032 return Error(BitcodeError::InvalidRecord);
2033 SectionTable.push_back(S);
2036 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2038 if (ConvertToString(Record, 0, S))
2039 return Error(BitcodeError::InvalidRecord);
2040 GCTable.push_back(S);
2043 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2044 if (Record.size() < 2)
2045 return Error(BitcodeError::InvalidRecord);
2046 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2047 unsigned ComdatNameSize = Record[1];
2048 std::string ComdatName;
2049 ComdatName.reserve(ComdatNameSize);
2050 for (unsigned i = 0; i != ComdatNameSize; ++i)
2051 ComdatName += (char)Record[2 + i];
2052 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2053 C->setSelectionKind(SK);
2054 ComdatList.push_back(C);
2057 // GLOBALVAR: [pointer type, isconst, initid,
2058 // linkage, alignment, section, visibility, threadlocal,
2059 // unnamed_addr, dllstorageclass]
2060 case bitc::MODULE_CODE_GLOBALVAR: {
2061 if (Record.size() < 6)
2062 return Error(BitcodeError::InvalidRecord);
2063 Type *Ty = getTypeByID(Record[0]);
2065 return Error(BitcodeError::InvalidRecord);
2066 if (!Ty->isPointerTy())
2067 return Error(BitcodeError::InvalidTypeForValue);
2068 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2069 Ty = cast<PointerType>(Ty)->getElementType();
2071 bool isConstant = Record[1];
2072 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Record[3]);
2073 unsigned Alignment = (1 << Record[4]) >> 1;
2074 std::string Section;
2076 if (Record[5]-1 >= SectionTable.size())
2077 return Error(BitcodeError::InvalidID);
2078 Section = SectionTable[Record[5]-1];
2080 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2081 // Local linkage must have default visibility.
2082 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2083 // FIXME: Change to an error if non-default in 4.0.
2084 Visibility = GetDecodedVisibility(Record[6]);
2086 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2087 if (Record.size() > 7)
2088 TLM = GetDecodedThreadLocalMode(Record[7]);
2090 bool UnnamedAddr = false;
2091 if (Record.size() > 8)
2092 UnnamedAddr = Record[8];
2094 bool ExternallyInitialized = false;
2095 if (Record.size() > 9)
2096 ExternallyInitialized = Record[9];
2098 GlobalVariable *NewGV =
2099 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2100 TLM, AddressSpace, ExternallyInitialized);
2101 NewGV->setAlignment(Alignment);
2102 if (!Section.empty())
2103 NewGV->setSection(Section);
2104 NewGV->setVisibility(Visibility);
2105 NewGV->setUnnamedAddr(UnnamedAddr);
2107 if (Record.size() > 10)
2108 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2110 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2112 ValueList.push_back(NewGV);
2114 // Remember which value to use for the global initializer.
2115 if (unsigned InitID = Record[2])
2116 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2118 if (Record.size() > 11)
2119 if (unsigned ComdatID = Record[11]) {
2120 assert(ComdatID <= ComdatList.size());
2121 NewGV->setComdat(ComdatList[ComdatID - 1]);
2125 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2126 // alignment, section, visibility, gc, unnamed_addr,
2127 // prologuedata, dllstorageclass, comdat, prefixdata]
2128 case bitc::MODULE_CODE_FUNCTION: {
2129 if (Record.size() < 8)
2130 return Error(BitcodeError::InvalidRecord);
2131 Type *Ty = getTypeByID(Record[0]);
2133 return Error(BitcodeError::InvalidRecord);
2134 if (!Ty->isPointerTy())
2135 return Error(BitcodeError::InvalidTypeForValue);
2137 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2139 return Error(BitcodeError::InvalidTypeForValue);
2141 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2144 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2145 bool isProto = Record[2];
2146 Func->setLinkage(getDecodedLinkage(Record[3]));
2147 Func->setAttributes(getAttributes(Record[4]));
2149 Func->setAlignment((1 << Record[5]) >> 1);
2151 if (Record[6]-1 >= SectionTable.size())
2152 return Error(BitcodeError::InvalidID);
2153 Func->setSection(SectionTable[Record[6]-1]);
2155 // Local linkage must have default visibility.
2156 if (!Func->hasLocalLinkage())
2157 // FIXME: Change to an error if non-default in 4.0.
2158 Func->setVisibility(GetDecodedVisibility(Record[7]));
2159 if (Record.size() > 8 && Record[8]) {
2160 if (Record[8]-1 > GCTable.size())
2161 return Error(BitcodeError::InvalidID);
2162 Func->setGC(GCTable[Record[8]-1].c_str());
2164 bool UnnamedAddr = false;
2165 if (Record.size() > 9)
2166 UnnamedAddr = Record[9];
2167 Func->setUnnamedAddr(UnnamedAddr);
2168 if (Record.size() > 10 && Record[10] != 0)
2169 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2171 if (Record.size() > 11)
2172 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2174 UpgradeDLLImportExportLinkage(Func, Record[3]);
2176 if (Record.size() > 12)
2177 if (unsigned ComdatID = Record[12]) {
2178 assert(ComdatID <= ComdatList.size());
2179 Func->setComdat(ComdatList[ComdatID - 1]);
2182 if (Record.size() > 13 && Record[13] != 0)
2183 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2185 ValueList.push_back(Func);
2187 // If this is a function with a body, remember the prototype we are
2188 // creating now, so that we can match up the body with them later.
2190 Func->setIsMaterializable(true);
2191 FunctionsWithBodies.push_back(Func);
2193 DeferredFunctionInfo[Func] = 0;
2197 // ALIAS: [alias type, aliasee val#, linkage]
2198 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2199 case bitc::MODULE_CODE_ALIAS: {
2200 if (Record.size() < 3)
2201 return Error(BitcodeError::InvalidRecord);
2202 Type *Ty = getTypeByID(Record[0]);
2204 return Error(BitcodeError::InvalidRecord);
2205 auto *PTy = dyn_cast<PointerType>(Ty);
2207 return Error(BitcodeError::InvalidTypeForValue);
2210 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2211 getDecodedLinkage(Record[2]), "", TheModule);
2212 // Old bitcode files didn't have visibility field.
2213 // Local linkage must have default visibility.
2214 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2215 // FIXME: Change to an error if non-default in 4.0.
2216 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2217 if (Record.size() > 4)
2218 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2220 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2221 if (Record.size() > 5)
2222 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2223 if (Record.size() > 6)
2224 NewGA->setUnnamedAddr(Record[6]);
2225 ValueList.push_back(NewGA);
2226 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2229 /// MODULE_CODE_PURGEVALS: [numvals]
2230 case bitc::MODULE_CODE_PURGEVALS:
2231 // Trim down the value list to the specified size.
2232 if (Record.size() < 1 || Record[0] > ValueList.size())
2233 return Error(BitcodeError::InvalidRecord);
2234 ValueList.shrinkTo(Record[0]);
2241 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2242 TheModule = nullptr;
2244 if (std::error_code EC = InitStream())
2247 // Sniff for the signature.
2248 if (Stream.Read(8) != 'B' ||
2249 Stream.Read(8) != 'C' ||
2250 Stream.Read(4) != 0x0 ||
2251 Stream.Read(4) != 0xC ||
2252 Stream.Read(4) != 0xE ||
2253 Stream.Read(4) != 0xD)
2254 return Error(BitcodeError::InvalidBitcodeSignature);
2256 // We expect a number of well-defined blocks, though we don't necessarily
2257 // need to understand them all.
2259 if (Stream.AtEndOfStream())
2260 return std::error_code();
2262 BitstreamEntry Entry =
2263 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2265 switch (Entry.Kind) {
2266 case BitstreamEntry::Error:
2267 return Error(BitcodeError::MalformedBlock);
2268 case BitstreamEntry::EndBlock:
2269 return std::error_code();
2271 case BitstreamEntry::SubBlock:
2273 case bitc::BLOCKINFO_BLOCK_ID:
2274 if (Stream.ReadBlockInfoBlock())
2275 return Error(BitcodeError::MalformedBlock);
2277 case bitc::MODULE_BLOCK_ID:
2278 // Reject multiple MODULE_BLOCK's in a single bitstream.
2280 return Error(BitcodeError::InvalidMultipleBlocks);
2282 if (std::error_code EC = ParseModule(false))
2285 return std::error_code();
2288 if (Stream.SkipBlock())
2289 return Error(BitcodeError::InvalidRecord);
2293 case BitstreamEntry::Record:
2294 // There should be no records in the top-level of blocks.
2296 // The ranlib in Xcode 4 will align archive members by appending newlines
2297 // to the end of them. If this file size is a multiple of 4 but not 8, we
2298 // have to read and ignore these final 4 bytes :-(
2299 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2300 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2301 Stream.AtEndOfStream())
2302 return std::error_code();
2304 return Error(BitcodeError::InvalidRecord);
2309 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2310 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2311 return Error(BitcodeError::InvalidRecord);
2313 SmallVector<uint64_t, 64> Record;
2316 // Read all the records for this module.
2318 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2320 switch (Entry.Kind) {
2321 case BitstreamEntry::SubBlock: // Handled for us already.
2322 case BitstreamEntry::Error:
2323 return Error(BitcodeError::MalformedBlock);
2324 case BitstreamEntry::EndBlock:
2326 case BitstreamEntry::Record:
2327 // The interesting case.
2332 switch (Stream.readRecord(Entry.ID, Record)) {
2333 default: break; // Default behavior, ignore unknown content.
2334 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2336 if (ConvertToString(Record, 0, S))
2337 return Error(BitcodeError::InvalidRecord);
2344 llvm_unreachable("Exit infinite loop");
2347 ErrorOr<std::string> BitcodeReader::parseTriple() {
2348 if (std::error_code EC = InitStream())
2351 // Sniff for the signature.
2352 if (Stream.Read(8) != 'B' ||
2353 Stream.Read(8) != 'C' ||
2354 Stream.Read(4) != 0x0 ||
2355 Stream.Read(4) != 0xC ||
2356 Stream.Read(4) != 0xE ||
2357 Stream.Read(4) != 0xD)
2358 return Error(BitcodeError::InvalidBitcodeSignature);
2360 // We expect a number of well-defined blocks, though we don't necessarily
2361 // need to understand them all.
2363 BitstreamEntry Entry = Stream.advance();
2365 switch (Entry.Kind) {
2366 case BitstreamEntry::Error:
2367 return Error(BitcodeError::MalformedBlock);
2368 case BitstreamEntry::EndBlock:
2369 return std::error_code();
2371 case BitstreamEntry::SubBlock:
2372 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2373 return parseModuleTriple();
2375 // Ignore other sub-blocks.
2376 if (Stream.SkipBlock())
2377 return Error(BitcodeError::MalformedBlock);
2380 case BitstreamEntry::Record:
2381 Stream.skipRecord(Entry.ID);
2387 /// ParseMetadataAttachment - Parse metadata attachments.
2388 std::error_code BitcodeReader::ParseMetadataAttachment() {
2389 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2390 return Error(BitcodeError::InvalidRecord);
2392 SmallVector<uint64_t, 64> Record;
2394 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2396 switch (Entry.Kind) {
2397 case BitstreamEntry::SubBlock: // Handled for us already.
2398 case BitstreamEntry::Error:
2399 return Error(BitcodeError::MalformedBlock);
2400 case BitstreamEntry::EndBlock:
2401 return std::error_code();
2402 case BitstreamEntry::Record:
2403 // The interesting case.
2407 // Read a metadata attachment record.
2409 switch (Stream.readRecord(Entry.ID, Record)) {
2410 default: // Default behavior: ignore.
2412 case bitc::METADATA_ATTACHMENT: {
2413 unsigned RecordLength = Record.size();
2414 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2415 return Error(BitcodeError::InvalidRecord);
2416 Instruction *Inst = InstructionList[Record[0]];
2417 for (unsigned i = 1; i != RecordLength; i = i+2) {
2418 unsigned Kind = Record[i];
2419 DenseMap<unsigned, unsigned>::iterator I =
2420 MDKindMap.find(Kind);
2421 if (I == MDKindMap.end())
2422 return Error(BitcodeError::InvalidID);
2423 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2424 if (isa<LocalAsMetadata>(Node))
2425 // Drop the attachment. This used to be legal, but there's no
2428 Inst->setMetadata(I->second, cast<MDNode>(Node));
2429 if (I->second == LLVMContext::MD_tbaa)
2430 InstsWithTBAATag.push_back(Inst);
2438 /// ParseFunctionBody - Lazily parse the specified function body block.
2439 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2440 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2441 return Error(BitcodeError::InvalidRecord);
2443 InstructionList.clear();
2444 unsigned ModuleValueListSize = ValueList.size();
2445 unsigned ModuleMDValueListSize = MDValueList.size();
2447 // Add all the function arguments to the value table.
2448 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2449 ValueList.push_back(I);
2451 unsigned NextValueNo = ValueList.size();
2452 BasicBlock *CurBB = nullptr;
2453 unsigned CurBBNo = 0;
2456 auto getLastInstruction = [&]() -> Instruction * {
2457 if (CurBB && !CurBB->empty())
2458 return &CurBB->back();
2459 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2460 !FunctionBBs[CurBBNo - 1]->empty())
2461 return &FunctionBBs[CurBBNo - 1]->back();
2465 // Read all the records.
2466 SmallVector<uint64_t, 64> Record;
2468 BitstreamEntry Entry = Stream.advance();
2470 switch (Entry.Kind) {
2471 case BitstreamEntry::Error:
2472 return Error(BitcodeError::MalformedBlock);
2473 case BitstreamEntry::EndBlock:
2474 goto OutOfRecordLoop;
2476 case BitstreamEntry::SubBlock:
2478 default: // Skip unknown content.
2479 if (Stream.SkipBlock())
2480 return Error(BitcodeError::InvalidRecord);
2482 case bitc::CONSTANTS_BLOCK_ID:
2483 if (std::error_code EC = ParseConstants())
2485 NextValueNo = ValueList.size();
2487 case bitc::VALUE_SYMTAB_BLOCK_ID:
2488 if (std::error_code EC = ParseValueSymbolTable())
2491 case bitc::METADATA_ATTACHMENT_ID:
2492 if (std::error_code EC = ParseMetadataAttachment())
2495 case bitc::METADATA_BLOCK_ID:
2496 if (std::error_code EC = ParseMetadata())
2499 case bitc::USELIST_BLOCK_ID:
2500 if (std::error_code EC = ParseUseLists())
2506 case BitstreamEntry::Record:
2507 // The interesting case.
2513 Instruction *I = nullptr;
2514 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2516 default: // Default behavior: reject
2517 return Error(BitcodeError::InvalidValue);
2518 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2519 if (Record.size() < 1 || Record[0] == 0)
2520 return Error(BitcodeError::InvalidRecord);
2521 // Create all the basic blocks for the function.
2522 FunctionBBs.resize(Record[0]);
2524 // See if anything took the address of blocks in this function.
2525 auto BBFRI = BasicBlockFwdRefs.find(F);
2526 if (BBFRI == BasicBlockFwdRefs.end()) {
2527 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2528 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2530 auto &BBRefs = BBFRI->second;
2531 // Check for invalid basic block references.
2532 if (BBRefs.size() > FunctionBBs.size())
2533 return Error(BitcodeError::InvalidID);
2534 assert(!BBRefs.empty() && "Unexpected empty array");
2535 assert(!BBRefs.front() && "Invalid reference to entry block");
2536 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2538 if (I < RE && BBRefs[I]) {
2539 BBRefs[I]->insertInto(F);
2540 FunctionBBs[I] = BBRefs[I];
2542 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2545 // Erase from the table.
2546 BasicBlockFwdRefs.erase(BBFRI);
2549 CurBB = FunctionBBs[0];
2553 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2554 // This record indicates that the last instruction is at the same
2555 // location as the previous instruction with a location.
2556 I = getLastInstruction();
2559 return Error(BitcodeError::InvalidRecord);
2560 I->setDebugLoc(LastLoc);
2564 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2565 I = getLastInstruction();
2566 if (!I || Record.size() < 4)
2567 return Error(BitcodeError::InvalidRecord);
2569 unsigned Line = Record[0], Col = Record[1];
2570 unsigned ScopeID = Record[2], IAID = Record[3];
2572 MDNode *Scope = nullptr, *IA = nullptr;
2573 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2574 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2575 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2576 I->setDebugLoc(LastLoc);
2581 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2584 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2585 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2586 OpNum+1 > Record.size())
2587 return Error(BitcodeError::InvalidRecord);
2589 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2591 return Error(BitcodeError::InvalidRecord);
2592 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2593 InstructionList.push_back(I);
2594 if (OpNum < Record.size()) {
2595 if (Opc == Instruction::Add ||
2596 Opc == Instruction::Sub ||
2597 Opc == Instruction::Mul ||
2598 Opc == Instruction::Shl) {
2599 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2600 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2601 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2602 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2603 } else if (Opc == Instruction::SDiv ||
2604 Opc == Instruction::UDiv ||
2605 Opc == Instruction::LShr ||
2606 Opc == Instruction::AShr) {
2607 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2608 cast<BinaryOperator>(I)->setIsExact(true);
2609 } else if (isa<FPMathOperator>(I)) {
2611 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2612 FMF.setUnsafeAlgebra();
2613 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2615 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2617 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2618 FMF.setNoSignedZeros();
2619 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2620 FMF.setAllowReciprocal();
2622 I->setFastMathFlags(FMF);
2628 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2631 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2632 OpNum+2 != Record.size())
2633 return Error(BitcodeError::InvalidRecord);
2635 Type *ResTy = getTypeByID(Record[OpNum]);
2636 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2637 if (Opc == -1 || !ResTy)
2638 return Error(BitcodeError::InvalidRecord);
2639 Instruction *Temp = nullptr;
2640 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2642 InstructionList.push_back(Temp);
2643 CurBB->getInstList().push_back(Temp);
2646 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2648 InstructionList.push_back(I);
2651 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2652 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2655 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2656 return Error(BitcodeError::InvalidRecord);
2658 SmallVector<Value*, 16> GEPIdx;
2659 while (OpNum != Record.size()) {
2661 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2662 return Error(BitcodeError::InvalidRecord);
2663 GEPIdx.push_back(Op);
2666 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2667 InstructionList.push_back(I);
2668 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2669 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2673 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2674 // EXTRACTVAL: [opty, opval, n x indices]
2677 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2678 return Error(BitcodeError::InvalidRecord);
2680 SmallVector<unsigned, 4> EXTRACTVALIdx;
2681 for (unsigned RecSize = Record.size();
2682 OpNum != RecSize; ++OpNum) {
2683 uint64_t Index = Record[OpNum];
2684 if ((unsigned)Index != Index)
2685 return Error(BitcodeError::InvalidValue);
2686 EXTRACTVALIdx.push_back((unsigned)Index);
2689 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2690 InstructionList.push_back(I);
2694 case bitc::FUNC_CODE_INST_INSERTVAL: {
2695 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2698 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2699 return Error(BitcodeError::InvalidRecord);
2701 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2702 return Error(BitcodeError::InvalidRecord);
2704 SmallVector<unsigned, 4> INSERTVALIdx;
2705 for (unsigned RecSize = Record.size();
2706 OpNum != RecSize; ++OpNum) {
2707 uint64_t Index = Record[OpNum];
2708 if ((unsigned)Index != Index)
2709 return Error(BitcodeError::InvalidValue);
2710 INSERTVALIdx.push_back((unsigned)Index);
2713 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2714 InstructionList.push_back(I);
2718 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2719 // obsolete form of select
2720 // handles select i1 ... in old bitcode
2722 Value *TrueVal, *FalseVal, *Cond;
2723 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2724 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2725 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2726 return Error(BitcodeError::InvalidRecord);
2728 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2729 InstructionList.push_back(I);
2733 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2734 // new form of select
2735 // handles select i1 or select [N x i1]
2737 Value *TrueVal, *FalseVal, *Cond;
2738 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2739 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2740 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2741 return Error(BitcodeError::InvalidRecord);
2743 // select condition can be either i1 or [N x i1]
2744 if (VectorType* vector_type =
2745 dyn_cast<VectorType>(Cond->getType())) {
2747 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2748 return Error(BitcodeError::InvalidTypeForValue);
2751 if (Cond->getType() != Type::getInt1Ty(Context))
2752 return Error(BitcodeError::InvalidTypeForValue);
2755 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2756 InstructionList.push_back(I);
2760 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2763 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2764 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2765 return Error(BitcodeError::InvalidRecord);
2766 I = ExtractElementInst::Create(Vec, Idx);
2767 InstructionList.push_back(I);
2771 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2773 Value *Vec, *Elt, *Idx;
2774 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2775 popValue(Record, OpNum, NextValueNo,
2776 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2777 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2778 return Error(BitcodeError::InvalidRecord);
2779 I = InsertElementInst::Create(Vec, Elt, Idx);
2780 InstructionList.push_back(I);
2784 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2786 Value *Vec1, *Vec2, *Mask;
2787 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2788 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2789 return Error(BitcodeError::InvalidRecord);
2791 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2792 return Error(BitcodeError::InvalidRecord);
2793 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2794 InstructionList.push_back(I);
2798 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2799 // Old form of ICmp/FCmp returning bool
2800 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2801 // both legal on vectors but had different behaviour.
2802 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2803 // FCmp/ICmp returning bool or vector of bool
2807 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2808 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2809 OpNum+1 != Record.size())
2810 return Error(BitcodeError::InvalidRecord);
2812 if (LHS->getType()->isFPOrFPVectorTy())
2813 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2815 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2816 InstructionList.push_back(I);
2820 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2822 unsigned Size = Record.size();
2824 I = ReturnInst::Create(Context);
2825 InstructionList.push_back(I);
2830 Value *Op = nullptr;
2831 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2832 return Error(BitcodeError::InvalidRecord);
2833 if (OpNum != Record.size())
2834 return Error(BitcodeError::InvalidRecord);
2836 I = ReturnInst::Create(Context, Op);
2837 InstructionList.push_back(I);
2840 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2841 if (Record.size() != 1 && Record.size() != 3)
2842 return Error(BitcodeError::InvalidRecord);
2843 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2845 return Error(BitcodeError::InvalidRecord);
2847 if (Record.size() == 1) {
2848 I = BranchInst::Create(TrueDest);
2849 InstructionList.push_back(I);
2852 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2853 Value *Cond = getValue(Record, 2, NextValueNo,
2854 Type::getInt1Ty(Context));
2855 if (!FalseDest || !Cond)
2856 return Error(BitcodeError::InvalidRecord);
2857 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2858 InstructionList.push_back(I);
2862 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2864 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2865 // "New" SwitchInst format with case ranges. The changes to write this
2866 // format were reverted but we still recognize bitcode that uses it.
2867 // Hopefully someday we will have support for case ranges and can use
2868 // this format again.
2870 Type *OpTy = getTypeByID(Record[1]);
2871 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2873 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2874 BasicBlock *Default = getBasicBlock(Record[3]);
2875 if (!OpTy || !Cond || !Default)
2876 return Error(BitcodeError::InvalidRecord);
2878 unsigned NumCases = Record[4];
2880 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2881 InstructionList.push_back(SI);
2883 unsigned CurIdx = 5;
2884 for (unsigned i = 0; i != NumCases; ++i) {
2885 SmallVector<ConstantInt*, 1> CaseVals;
2886 unsigned NumItems = Record[CurIdx++];
2887 for (unsigned ci = 0; ci != NumItems; ++ci) {
2888 bool isSingleNumber = Record[CurIdx++];
2891 unsigned ActiveWords = 1;
2892 if (ValueBitWidth > 64)
2893 ActiveWords = Record[CurIdx++];
2894 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2896 CurIdx += ActiveWords;
2898 if (!isSingleNumber) {
2900 if (ValueBitWidth > 64)
2901 ActiveWords = Record[CurIdx++];
2903 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2905 CurIdx += ActiveWords;
2907 // FIXME: It is not clear whether values in the range should be
2908 // compared as signed or unsigned values. The partially
2909 // implemented changes that used this format in the past used
2910 // unsigned comparisons.
2911 for ( ; Low.ule(High); ++Low)
2912 CaseVals.push_back(ConstantInt::get(Context, Low));
2914 CaseVals.push_back(ConstantInt::get(Context, Low));
2916 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2917 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2918 cve = CaseVals.end(); cvi != cve; ++cvi)
2919 SI->addCase(*cvi, DestBB);
2925 // Old SwitchInst format without case ranges.
2927 if (Record.size() < 3 || (Record.size() & 1) == 0)
2928 return Error(BitcodeError::InvalidRecord);
2929 Type *OpTy = getTypeByID(Record[0]);
2930 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2931 BasicBlock *Default = getBasicBlock(Record[2]);
2932 if (!OpTy || !Cond || !Default)
2933 return Error(BitcodeError::InvalidRecord);
2934 unsigned NumCases = (Record.size()-3)/2;
2935 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2936 InstructionList.push_back(SI);
2937 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2938 ConstantInt *CaseVal =
2939 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2940 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2941 if (!CaseVal || !DestBB) {
2943 return Error(BitcodeError::InvalidRecord);
2945 SI->addCase(CaseVal, DestBB);
2950 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2951 if (Record.size() < 2)
2952 return Error(BitcodeError::InvalidRecord);
2953 Type *OpTy = getTypeByID(Record[0]);
2954 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2955 if (!OpTy || !Address)
2956 return Error(BitcodeError::InvalidRecord);
2957 unsigned NumDests = Record.size()-2;
2958 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2959 InstructionList.push_back(IBI);
2960 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2961 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2962 IBI->addDestination(DestBB);
2965 return Error(BitcodeError::InvalidRecord);
2972 case bitc::FUNC_CODE_INST_INVOKE: {
2973 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2974 if (Record.size() < 4)
2975 return Error(BitcodeError::InvalidRecord);
2976 AttributeSet PAL = getAttributes(Record[0]);
2977 unsigned CCInfo = Record[1];
2978 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2979 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2983 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2984 return Error(BitcodeError::InvalidRecord);
2986 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2987 FunctionType *FTy = !CalleeTy ? nullptr :
2988 dyn_cast<FunctionType>(CalleeTy->getElementType());
2990 // Check that the right number of fixed parameters are here.
2991 if (!FTy || !NormalBB || !UnwindBB ||
2992 Record.size() < OpNum+FTy->getNumParams())
2993 return Error(BitcodeError::InvalidRecord);
2995 SmallVector<Value*, 16> Ops;
2996 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2997 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2998 FTy->getParamType(i)));
3000 return Error(BitcodeError::InvalidRecord);
3003 if (!FTy->isVarArg()) {
3004 if (Record.size() != OpNum)
3005 return Error(BitcodeError::InvalidRecord);
3007 // Read type/value pairs for varargs params.
3008 while (OpNum != Record.size()) {
3010 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3011 return Error(BitcodeError::InvalidRecord);
3016 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3017 InstructionList.push_back(I);
3018 cast<InvokeInst>(I)->setCallingConv(
3019 static_cast<CallingConv::ID>(CCInfo));
3020 cast<InvokeInst>(I)->setAttributes(PAL);
3023 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3025 Value *Val = nullptr;
3026 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3027 return Error(BitcodeError::InvalidRecord);
3028 I = ResumeInst::Create(Val);
3029 InstructionList.push_back(I);
3032 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3033 I = new UnreachableInst(Context);
3034 InstructionList.push_back(I);
3036 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3037 if (Record.size() < 1 || ((Record.size()-1)&1))
3038 return Error(BitcodeError::InvalidRecord);
3039 Type *Ty = getTypeByID(Record[0]);
3041 return Error(BitcodeError::InvalidRecord);
3043 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3044 InstructionList.push_back(PN);
3046 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3048 // With the new function encoding, it is possible that operands have
3049 // negative IDs (for forward references). Use a signed VBR
3050 // representation to keep the encoding small.
3052 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3054 V = getValue(Record, 1+i, NextValueNo, Ty);
3055 BasicBlock *BB = getBasicBlock(Record[2+i]);
3057 return Error(BitcodeError::InvalidRecord);
3058 PN->addIncoming(V, BB);
3064 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3065 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3067 if (Record.size() < 4)
3068 return Error(BitcodeError::InvalidRecord);
3069 Type *Ty = getTypeByID(Record[Idx++]);
3071 return Error(BitcodeError::InvalidRecord);
3072 Value *PersFn = nullptr;
3073 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3074 return Error(BitcodeError::InvalidRecord);
3076 bool IsCleanup = !!Record[Idx++];
3077 unsigned NumClauses = Record[Idx++];
3078 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3079 LP->setCleanup(IsCleanup);
3080 for (unsigned J = 0; J != NumClauses; ++J) {
3081 LandingPadInst::ClauseType CT =
3082 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3085 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3087 return Error(BitcodeError::InvalidRecord);
3090 assert((CT != LandingPadInst::Catch ||
3091 !isa<ArrayType>(Val->getType())) &&
3092 "Catch clause has a invalid type!");
3093 assert((CT != LandingPadInst::Filter ||
3094 isa<ArrayType>(Val->getType())) &&
3095 "Filter clause has invalid type!");
3096 LP->addClause(cast<Constant>(Val));
3100 InstructionList.push_back(I);
3104 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3105 if (Record.size() != 4)
3106 return Error(BitcodeError::InvalidRecord);
3108 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3109 Type *OpTy = getTypeByID(Record[1]);
3110 Value *Size = getFnValueByID(Record[2], OpTy);
3111 unsigned AlignRecord = Record[3];
3112 bool InAlloca = AlignRecord & (1 << 5);
3113 unsigned Align = AlignRecord & ((1 << 5) - 1);
3115 return Error(BitcodeError::InvalidRecord);
3116 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3117 AI->setUsedWithInAlloca(InAlloca);
3119 InstructionList.push_back(I);
3122 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3125 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3126 OpNum+2 != Record.size())
3127 return Error(BitcodeError::InvalidRecord);
3129 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3130 InstructionList.push_back(I);
3133 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3134 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3137 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3138 OpNum+4 != Record.size())
3139 return Error(BitcodeError::InvalidRecord);
3141 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3142 if (Ordering == NotAtomic || Ordering == Release ||
3143 Ordering == AcquireRelease)
3144 return Error(BitcodeError::InvalidRecord);
3145 if (Ordering != NotAtomic && Record[OpNum] == 0)
3146 return Error(BitcodeError::InvalidRecord);
3147 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3149 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3150 Ordering, SynchScope);
3151 InstructionList.push_back(I);
3154 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3157 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3158 popValue(Record, OpNum, NextValueNo,
3159 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3160 OpNum+2 != Record.size())
3161 return Error(BitcodeError::InvalidRecord);
3163 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3164 InstructionList.push_back(I);
3167 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3168 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3171 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3172 popValue(Record, OpNum, NextValueNo,
3173 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3174 OpNum+4 != Record.size())
3175 return Error(BitcodeError::InvalidRecord);
3177 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3178 if (Ordering == NotAtomic || Ordering == Acquire ||
3179 Ordering == AcquireRelease)
3180 return Error(BitcodeError::InvalidRecord);
3181 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3182 if (Ordering != NotAtomic && Record[OpNum] == 0)
3183 return Error(BitcodeError::InvalidRecord);
3185 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3186 Ordering, SynchScope);
3187 InstructionList.push_back(I);
3190 case bitc::FUNC_CODE_INST_CMPXCHG: {
3191 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3192 // failureordering?, isweak?]
3194 Value *Ptr, *Cmp, *New;
3195 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3196 popValue(Record, OpNum, NextValueNo,
3197 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3198 popValue(Record, OpNum, NextValueNo,
3199 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3200 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3201 return Error(BitcodeError::InvalidRecord);
3202 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3203 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3204 return Error(BitcodeError::InvalidRecord);
3205 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3207 AtomicOrdering FailureOrdering;
3208 if (Record.size() < 7)
3210 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3212 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3214 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3216 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3218 if (Record.size() < 8) {
3219 // Before weak cmpxchgs existed, the instruction simply returned the
3220 // value loaded from memory, so bitcode files from that era will be
3221 // expecting the first component of a modern cmpxchg.
3222 CurBB->getInstList().push_back(I);
3223 I = ExtractValueInst::Create(I, 0);
3225 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3228 InstructionList.push_back(I);
3231 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3232 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3235 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3236 popValue(Record, OpNum, NextValueNo,
3237 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3238 OpNum+4 != Record.size())
3239 return Error(BitcodeError::InvalidRecord);
3240 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3241 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3242 Operation > AtomicRMWInst::LAST_BINOP)
3243 return Error(BitcodeError::InvalidRecord);
3244 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3245 if (Ordering == NotAtomic || Ordering == Unordered)
3246 return Error(BitcodeError::InvalidRecord);
3247 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3248 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3249 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3250 InstructionList.push_back(I);
3253 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3254 if (2 != Record.size())
3255 return Error(BitcodeError::InvalidRecord);
3256 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3257 if (Ordering == NotAtomic || Ordering == Unordered ||
3258 Ordering == Monotonic)
3259 return Error(BitcodeError::InvalidRecord);
3260 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3261 I = new FenceInst(Context, Ordering, SynchScope);
3262 InstructionList.push_back(I);
3265 case bitc::FUNC_CODE_INST_CALL: {
3266 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3267 if (Record.size() < 3)
3268 return Error(BitcodeError::InvalidRecord);
3270 AttributeSet PAL = getAttributes(Record[0]);
3271 unsigned CCInfo = Record[1];
3275 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3276 return Error(BitcodeError::InvalidRecord);
3278 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3279 FunctionType *FTy = nullptr;
3280 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3281 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3282 return Error(BitcodeError::InvalidRecord);
3284 SmallVector<Value*, 16> Args;
3285 // Read the fixed params.
3286 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3287 if (FTy->getParamType(i)->isLabelTy())
3288 Args.push_back(getBasicBlock(Record[OpNum]));
3290 Args.push_back(getValue(Record, OpNum, NextValueNo,
3291 FTy->getParamType(i)));
3293 return Error(BitcodeError::InvalidRecord);
3296 // Read type/value pairs for varargs params.
3297 if (!FTy->isVarArg()) {
3298 if (OpNum != Record.size())
3299 return Error(BitcodeError::InvalidRecord);
3301 while (OpNum != Record.size()) {
3303 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3304 return Error(BitcodeError::InvalidRecord);
3309 I = CallInst::Create(Callee, Args);
3310 InstructionList.push_back(I);
3311 cast<CallInst>(I)->setCallingConv(
3312 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3313 CallInst::TailCallKind TCK = CallInst::TCK_None;
3315 TCK = CallInst::TCK_Tail;
3316 if (CCInfo & (1 << 14))
3317 TCK = CallInst::TCK_MustTail;
3318 cast<CallInst>(I)->setTailCallKind(TCK);
3319 cast<CallInst>(I)->setAttributes(PAL);
3322 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3323 if (Record.size() < 3)
3324 return Error(BitcodeError::InvalidRecord);
3325 Type *OpTy = getTypeByID(Record[0]);
3326 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3327 Type *ResTy = getTypeByID(Record[2]);
3328 if (!OpTy || !Op || !ResTy)
3329 return Error(BitcodeError::InvalidRecord);
3330 I = new VAArgInst(Op, ResTy);
3331 InstructionList.push_back(I);
3336 // Add instruction to end of current BB. If there is no current BB, reject
3340 return Error(BitcodeError::InvalidInstructionWithNoBB);
3342 CurBB->getInstList().push_back(I);
3344 // If this was a terminator instruction, move to the next block.
3345 if (isa<TerminatorInst>(I)) {
3347 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3350 // Non-void values get registered in the value table for future use.
3351 if (I && !I->getType()->isVoidTy())
3352 ValueList.AssignValue(I, NextValueNo++);
3357 // Check the function list for unresolved values.
3358 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3359 if (!A->getParent()) {
3360 // We found at least one unresolved value. Nuke them all to avoid leaks.
3361 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3362 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3363 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3367 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3371 // FIXME: Check for unresolved forward-declared metadata references
3372 // and clean up leaks.
3374 // Trim the value list down to the size it was before we parsed this function.
3375 ValueList.shrinkTo(ModuleValueListSize);
3376 MDValueList.shrinkTo(ModuleMDValueListSize);
3377 std::vector<BasicBlock*>().swap(FunctionBBs);
3378 return std::error_code();
3381 /// Find the function body in the bitcode stream
3382 std::error_code BitcodeReader::FindFunctionInStream(
3384 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3385 while (DeferredFunctionInfoIterator->second == 0) {
3386 if (Stream.AtEndOfStream())
3387 return Error(BitcodeError::CouldNotFindFunctionInStream);
3388 // ParseModule will parse the next body in the stream and set its
3389 // position in the DeferredFunctionInfo map.
3390 if (std::error_code EC = ParseModule(true))
3393 return std::error_code();
3396 //===----------------------------------------------------------------------===//
3397 // GVMaterializer implementation
3398 //===----------------------------------------------------------------------===//
3400 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3402 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3403 Function *F = dyn_cast<Function>(GV);
3404 // If it's not a function or is already material, ignore the request.
3405 if (!F || !F->isMaterializable())
3406 return std::error_code();
3408 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3409 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3410 // If its position is recorded as 0, its body is somewhere in the stream
3411 // but we haven't seen it yet.
3412 if (DFII->second == 0 && LazyStreamer)
3413 if (std::error_code EC = FindFunctionInStream(F, DFII))
3416 // Move the bit stream to the saved position of the deferred function body.
3417 Stream.JumpToBit(DFII->second);
3419 if (std::error_code EC = ParseFunctionBody(F))
3421 F->setIsMaterializable(false);
3423 // Upgrade any old intrinsic calls in the function.
3424 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3425 E = UpgradedIntrinsics.end(); I != E; ++I) {
3426 if (I->first != I->second) {
3427 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3429 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3430 UpgradeIntrinsicCall(CI, I->second);
3435 // Bring in any functions that this function forward-referenced via
3437 return materializeForwardReferencedFunctions();
3440 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3441 const Function *F = dyn_cast<Function>(GV);
3442 if (!F || F->isDeclaration())
3445 // Dematerializing F would leave dangling references that wouldn't be
3446 // reconnected on re-materialization.
3447 if (BlockAddressesTaken.count(F))
3450 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3453 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3454 Function *F = dyn_cast<Function>(GV);
3455 // If this function isn't dematerializable, this is a noop.
3456 if (!F || !isDematerializable(F))
3459 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3461 // Just forget the function body, we can remat it later.
3462 F->dropAllReferences();
3463 F->setIsMaterializable(true);
3466 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3467 assert(M == TheModule &&
3468 "Can only Materialize the Module this BitcodeReader is attached to.");
3470 // Promise to materialize all forward references.
3471 WillMaterializeAllForwardRefs = true;
3473 // Iterate over the module, deserializing any functions that are still on
3475 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3477 if (std::error_code EC = materialize(F))
3480 // At this point, if there are any function bodies, the current bit is
3481 // pointing to the END_BLOCK record after them. Now make sure the rest
3482 // of the bits in the module have been read.
3486 // Check that all block address forward references got resolved (as we
3488 if (!BasicBlockFwdRefs.empty())
3489 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3491 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3492 // delete the old functions to clean up. We can't do this unless the entire
3493 // module is materialized because there could always be another function body
3494 // with calls to the old function.
3495 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3496 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3497 if (I->first != I->second) {
3498 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3500 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3501 UpgradeIntrinsicCall(CI, I->second);
3503 if (!I->first->use_empty())
3504 I->first->replaceAllUsesWith(I->second);
3505 I->first->eraseFromParent();
3508 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3510 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3511 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3513 UpgradeDebugInfo(*M);
3514 return std::error_code();
3517 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3518 return IdentifiedStructTypes;
3521 std::error_code BitcodeReader::InitStream() {
3523 return InitLazyStream();
3524 return InitStreamFromBuffer();
3527 std::error_code BitcodeReader::InitStreamFromBuffer() {
3528 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3529 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3531 if (Buffer->getBufferSize() & 3)
3532 return Error(BitcodeError::InvalidBitcodeSignature);
3534 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3535 // The magic number is 0x0B17C0DE stored in little endian.
3536 if (isBitcodeWrapper(BufPtr, BufEnd))
3537 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3538 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3540 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3541 Stream.init(&*StreamFile);
3543 return std::error_code();
3546 std::error_code BitcodeReader::InitLazyStream() {
3547 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3549 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3550 StreamingMemoryObject &Bytes = *OwnedBytes;
3551 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3552 Stream.init(&*StreamFile);
3554 unsigned char buf[16];
3555 if (Bytes.readBytes(buf, 16, 0) != 16)
3556 return Error(BitcodeError::InvalidBitcodeSignature);
3558 if (!isBitcode(buf, buf + 16))
3559 return Error(BitcodeError::InvalidBitcodeSignature);
3561 if (isBitcodeWrapper(buf, buf + 4)) {
3562 const unsigned char *bitcodeStart = buf;
3563 const unsigned char *bitcodeEnd = buf + 16;
3564 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3565 Bytes.dropLeadingBytes(bitcodeStart - buf);
3566 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3568 return std::error_code();
3572 class BitcodeErrorCategoryType : public std::error_category {
3573 const char *name() const LLVM_NOEXCEPT override {
3574 return "llvm.bitcode";
3576 std::string message(int IE) const override {
3577 BitcodeError E = static_cast<BitcodeError>(IE);
3579 case BitcodeError::ConflictingMETADATA_KINDRecords:
3580 return "Conflicting METADATA_KIND records";
3581 case BitcodeError::CouldNotFindFunctionInStream:
3582 return "Could not find function in stream";
3583 case BitcodeError::ExpectedConstant:
3584 return "Expected a constant";
3585 case BitcodeError::InsufficientFunctionProtos:
3586 return "Insufficient function protos";
3587 case BitcodeError::InvalidBitcodeSignature:
3588 return "Invalid bitcode signature";
3589 case BitcodeError::InvalidBitcodeWrapperHeader:
3590 return "Invalid bitcode wrapper header";
3591 case BitcodeError::InvalidConstantReference:
3592 return "Invalid ronstant reference";
3593 case BitcodeError::InvalidID:
3594 return "Invalid ID";
3595 case BitcodeError::InvalidInstructionWithNoBB:
3596 return "Invalid instruction with no BB";
3597 case BitcodeError::InvalidRecord:
3598 return "Invalid record";
3599 case BitcodeError::InvalidTypeForValue:
3600 return "Invalid type for value";
3601 case BitcodeError::InvalidTYPETable:
3602 return "Invalid TYPE table";
3603 case BitcodeError::InvalidType:
3604 return "Invalid type";
3605 case BitcodeError::MalformedBlock:
3606 return "Malformed block";
3607 case BitcodeError::MalformedGlobalInitializerSet:
3608 return "Malformed global initializer set";
3609 case BitcodeError::InvalidMultipleBlocks:
3610 return "Invalid multiple blocks";
3611 case BitcodeError::NeverResolvedValueFoundInFunction:
3612 return "Never resolved value found in function";
3613 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3614 return "Never resolved function from blockaddress";
3615 case BitcodeError::InvalidValue:
3616 return "Invalid value";
3618 llvm_unreachable("Unknown error type!");
3623 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3625 const std::error_category &llvm::BitcodeErrorCategory() {
3626 return *ErrorCategory;
3629 //===----------------------------------------------------------------------===//
3630 // External interface
3631 //===----------------------------------------------------------------------===//
3633 /// \brief Get a lazy one-at-time loading module from bitcode.
3635 /// This isn't always used in a lazy context. In particular, it's also used by
3636 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3637 /// in forward-referenced functions from block address references.
3639 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3640 /// materialize everything -- in particular, if this isn't truly lazy.
3641 static ErrorOr<Module *>
3642 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3643 LLVMContext &Context, bool WillMaterializeAll) {
3644 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3645 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3646 M->setMaterializer(R);
3648 auto cleanupOnError = [&](std::error_code EC) {
3649 R->releaseBuffer(); // Never take ownership on error.
3650 delete M; // Also deletes R.
3654 if (std::error_code EC = R->ParseBitcodeInto(M))
3655 return cleanupOnError(EC);
3657 if (!WillMaterializeAll)
3658 // Resolve forward references from blockaddresses.
3659 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3660 return cleanupOnError(EC);
3662 Buffer.release(); // The BitcodeReader owns it now.
3667 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3668 LLVMContext &Context) {
3669 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3672 ErrorOr<std::unique_ptr<Module>>
3673 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3674 LLVMContext &Context) {
3675 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3676 BitcodeReader *R = new BitcodeReader(Streamer, Context);
3677 M->setMaterializer(R);
3678 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3680 return std::move(M);
3683 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3684 LLVMContext &Context) {
3685 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3686 ErrorOr<Module *> ModuleOrErr =
3687 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3690 Module *M = ModuleOrErr.get();
3691 // Read in the entire module, and destroy the BitcodeReader.
3692 if (std::error_code EC = M->materializeAllPermanently()) {
3697 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3698 // written. We must defer until the Module has been fully materialized.
3703 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3704 LLVMContext &Context) {
3705 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3706 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3707 ErrorOr<std::string> Triple = R->parseTriple();
3708 if (Triple.getError())
3710 return Triple.get();