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);
1110 default: // Default behavior: ignore.
1112 case bitc::METADATA_NAME: {
1113 // Read name of the named metadata.
1114 SmallString<8> Name(Record.begin(), Record.end());
1116 Code = Stream.ReadCode();
1118 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1119 unsigned NextBitCode = Stream.readRecord(Code, Record);
1120 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1122 // Read named metadata elements.
1123 unsigned Size = Record.size();
1124 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1125 for (unsigned i = 0; i != Size; ++i) {
1126 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1128 return Error(BitcodeError::InvalidRecord);
1129 NMD->addOperand(MD);
1133 case bitc::METADATA_OLD_FN_NODE: {
1134 // FIXME: Remove in 4.0.
1135 // This is a LocalAsMetadata record, the only type of function-local
1137 if (Record.size() % 2 == 1)
1138 return Error(BitcodeError::InvalidRecord);
1140 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1141 // to be legal, but there's no upgrade path.
1142 auto dropRecord = [&] {
1143 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1145 if (Record.size() != 2) {
1150 Type *Ty = getTypeByID(Record[0]);
1151 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1156 MDValueList.AssignValue(
1157 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1161 case bitc::METADATA_OLD_NODE: {
1162 // FIXME: Remove in 4.0.
1163 if (Record.size() % 2 == 1)
1164 return Error(BitcodeError::InvalidRecord);
1166 unsigned Size = Record.size();
1167 SmallVector<Metadata *, 8> Elts;
1168 for (unsigned i = 0; i != Size; i += 2) {
1169 Type *Ty = getTypeByID(Record[i]);
1171 return Error(BitcodeError::InvalidRecord);
1172 if (Ty->isMetadataTy())
1173 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1174 else if (!Ty->isVoidTy()) {
1176 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1177 assert(isa<ConstantAsMetadata>(MD) &&
1178 "Expected non-function-local metadata");
1181 Elts.push_back(nullptr);
1183 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1186 case bitc::METADATA_VALUE: {
1187 if (Record.size() != 2)
1188 return Error(BitcodeError::InvalidRecord);
1190 Type *Ty = getTypeByID(Record[0]);
1191 if (Ty->isMetadataTy() || Ty->isVoidTy())
1192 return Error(BitcodeError::InvalidRecord);
1194 MDValueList.AssignValue(
1195 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1199 case bitc::METADATA_NODE: {
1200 SmallVector<Metadata *, 8> Elts;
1201 Elts.reserve(Record.size());
1202 for (unsigned ID : Record)
1203 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1204 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1207 case bitc::METADATA_STRING: {
1208 std::string String(Record.begin(), Record.end());
1209 llvm::UpgradeMDStringConstant(String);
1210 Metadata *MD = MDString::get(Context, String);
1211 MDValueList.AssignValue(MD, NextMDValueNo++);
1214 case bitc::METADATA_KIND: {
1215 if (Record.size() < 2)
1216 return Error(BitcodeError::InvalidRecord);
1218 unsigned Kind = Record[0];
1219 SmallString<8> Name(Record.begin()+1, Record.end());
1221 unsigned NewKind = TheModule->getMDKindID(Name.str());
1222 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1223 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1230 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1231 /// the LSB for dense VBR encoding.
1232 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1237 // There is no such thing as -0 with integers. "-0" really means MININT.
1241 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1242 /// values and aliases that we can.
1243 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1244 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1245 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1246 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1247 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1249 GlobalInitWorklist.swap(GlobalInits);
1250 AliasInitWorklist.swap(AliasInits);
1251 FunctionPrefixWorklist.swap(FunctionPrefixes);
1252 FunctionPrologueWorklist.swap(FunctionPrologues);
1254 while (!GlobalInitWorklist.empty()) {
1255 unsigned ValID = GlobalInitWorklist.back().second;
1256 if (ValID >= ValueList.size()) {
1257 // Not ready to resolve this yet, it requires something later in the file.
1258 GlobalInits.push_back(GlobalInitWorklist.back());
1260 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1261 GlobalInitWorklist.back().first->setInitializer(C);
1263 return Error(BitcodeError::ExpectedConstant);
1265 GlobalInitWorklist.pop_back();
1268 while (!AliasInitWorklist.empty()) {
1269 unsigned ValID = AliasInitWorklist.back().second;
1270 if (ValID >= ValueList.size()) {
1271 AliasInits.push_back(AliasInitWorklist.back());
1273 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1274 AliasInitWorklist.back().first->setAliasee(C);
1276 return Error(BitcodeError::ExpectedConstant);
1278 AliasInitWorklist.pop_back();
1281 while (!FunctionPrefixWorklist.empty()) {
1282 unsigned ValID = FunctionPrefixWorklist.back().second;
1283 if (ValID >= ValueList.size()) {
1284 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1286 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1287 FunctionPrefixWorklist.back().first->setPrefixData(C);
1289 return Error(BitcodeError::ExpectedConstant);
1291 FunctionPrefixWorklist.pop_back();
1294 while (!FunctionPrologueWorklist.empty()) {
1295 unsigned ValID = FunctionPrologueWorklist.back().second;
1296 if (ValID >= ValueList.size()) {
1297 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1299 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1300 FunctionPrologueWorklist.back().first->setPrologueData(C);
1302 return Error(BitcodeError::ExpectedConstant);
1304 FunctionPrologueWorklist.pop_back();
1307 return std::error_code();
1310 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1311 SmallVector<uint64_t, 8> Words(Vals.size());
1312 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1313 BitcodeReader::decodeSignRotatedValue);
1315 return APInt(TypeBits, Words);
1318 std::error_code BitcodeReader::ParseConstants() {
1319 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1320 return Error(BitcodeError::InvalidRecord);
1322 SmallVector<uint64_t, 64> Record;
1324 // Read all the records for this value table.
1325 Type *CurTy = Type::getInt32Ty(Context);
1326 unsigned NextCstNo = ValueList.size();
1328 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1330 switch (Entry.Kind) {
1331 case BitstreamEntry::SubBlock: // Handled for us already.
1332 case BitstreamEntry::Error:
1333 return Error(BitcodeError::MalformedBlock);
1334 case BitstreamEntry::EndBlock:
1335 if (NextCstNo != ValueList.size())
1336 return Error(BitcodeError::InvalidConstantReference);
1338 // Once all the constants have been read, go through and resolve forward
1340 ValueList.ResolveConstantForwardRefs();
1341 return std::error_code();
1342 case BitstreamEntry::Record:
1343 // The interesting case.
1350 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1352 default: // Default behavior: unknown constant
1353 case bitc::CST_CODE_UNDEF: // UNDEF
1354 V = UndefValue::get(CurTy);
1356 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1358 return Error(BitcodeError::InvalidRecord);
1359 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1360 return Error(BitcodeError::InvalidRecord);
1361 CurTy = TypeList[Record[0]];
1362 continue; // Skip the ValueList manipulation.
1363 case bitc::CST_CODE_NULL: // NULL
1364 V = Constant::getNullValue(CurTy);
1366 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1367 if (!CurTy->isIntegerTy() || Record.empty())
1368 return Error(BitcodeError::InvalidRecord);
1369 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1371 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1372 if (!CurTy->isIntegerTy() || Record.empty())
1373 return Error(BitcodeError::InvalidRecord);
1375 APInt VInt = ReadWideAPInt(Record,
1376 cast<IntegerType>(CurTy)->getBitWidth());
1377 V = ConstantInt::get(Context, VInt);
1381 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1383 return Error(BitcodeError::InvalidRecord);
1384 if (CurTy->isHalfTy())
1385 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1386 APInt(16, (uint16_t)Record[0])));
1387 else if (CurTy->isFloatTy())
1388 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1389 APInt(32, (uint32_t)Record[0])));
1390 else if (CurTy->isDoubleTy())
1391 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1392 APInt(64, Record[0])));
1393 else if (CurTy->isX86_FP80Ty()) {
1394 // Bits are not stored the same way as a normal i80 APInt, compensate.
1395 uint64_t Rearrange[2];
1396 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1397 Rearrange[1] = Record[0] >> 48;
1398 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1399 APInt(80, Rearrange)));
1400 } else if (CurTy->isFP128Ty())
1401 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1402 APInt(128, Record)));
1403 else if (CurTy->isPPC_FP128Ty())
1404 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1405 APInt(128, Record)));
1407 V = UndefValue::get(CurTy);
1411 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1413 return Error(BitcodeError::InvalidRecord);
1415 unsigned Size = Record.size();
1416 SmallVector<Constant*, 16> Elts;
1418 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1419 for (unsigned i = 0; i != Size; ++i)
1420 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1421 STy->getElementType(i)));
1422 V = ConstantStruct::get(STy, Elts);
1423 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1424 Type *EltTy = ATy->getElementType();
1425 for (unsigned i = 0; i != Size; ++i)
1426 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1427 V = ConstantArray::get(ATy, Elts);
1428 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1429 Type *EltTy = VTy->getElementType();
1430 for (unsigned i = 0; i != Size; ++i)
1431 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1432 V = ConstantVector::get(Elts);
1434 V = UndefValue::get(CurTy);
1438 case bitc::CST_CODE_STRING: // STRING: [values]
1439 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1441 return Error(BitcodeError::InvalidRecord);
1443 SmallString<16> Elts(Record.begin(), Record.end());
1444 V = ConstantDataArray::getString(Context, Elts,
1445 BitCode == bitc::CST_CODE_CSTRING);
1448 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1450 return Error(BitcodeError::InvalidRecord);
1452 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1453 unsigned Size = Record.size();
1455 if (EltTy->isIntegerTy(8)) {
1456 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1457 if (isa<VectorType>(CurTy))
1458 V = ConstantDataVector::get(Context, Elts);
1460 V = ConstantDataArray::get(Context, Elts);
1461 } else if (EltTy->isIntegerTy(16)) {
1462 SmallVector<uint16_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(32)) {
1468 SmallVector<uint32_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(64)) {
1474 SmallVector<uint64_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->isFloatTy()) {
1480 SmallVector<float, 16> Elts(Size);
1481 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1482 if (isa<VectorType>(CurTy))
1483 V = ConstantDataVector::get(Context, Elts);
1485 V = ConstantDataArray::get(Context, Elts);
1486 } else if (EltTy->isDoubleTy()) {
1487 SmallVector<double, 16> Elts(Size);
1488 std::transform(Record.begin(), Record.end(), Elts.begin(),
1490 if (isa<VectorType>(CurTy))
1491 V = ConstantDataVector::get(Context, Elts);
1493 V = ConstantDataArray::get(Context, Elts);
1495 return Error(BitcodeError::InvalidTypeForValue);
1500 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1501 if (Record.size() < 3)
1502 return Error(BitcodeError::InvalidRecord);
1503 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1505 V = UndefValue::get(CurTy); // Unknown binop.
1507 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1508 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1510 if (Record.size() >= 4) {
1511 if (Opc == Instruction::Add ||
1512 Opc == Instruction::Sub ||
1513 Opc == Instruction::Mul ||
1514 Opc == Instruction::Shl) {
1515 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1516 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1517 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1518 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1519 } else if (Opc == Instruction::SDiv ||
1520 Opc == Instruction::UDiv ||
1521 Opc == Instruction::LShr ||
1522 Opc == Instruction::AShr) {
1523 if (Record[3] & (1 << bitc::PEO_EXACT))
1524 Flags |= SDivOperator::IsExact;
1527 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1531 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1532 if (Record.size() < 3)
1533 return Error(BitcodeError::InvalidRecord);
1534 int Opc = GetDecodedCastOpcode(Record[0]);
1536 V = UndefValue::get(CurTy); // Unknown cast.
1538 Type *OpTy = getTypeByID(Record[1]);
1540 return Error(BitcodeError::InvalidRecord);
1541 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1542 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1543 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1547 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1548 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1549 if (Record.size() & 1)
1550 return Error(BitcodeError::InvalidRecord);
1551 SmallVector<Constant*, 16> Elts;
1552 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1553 Type *ElTy = getTypeByID(Record[i]);
1555 return Error(BitcodeError::InvalidRecord);
1556 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1558 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1559 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1561 bitc::CST_CODE_CE_INBOUNDS_GEP);
1564 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1565 if (Record.size() < 3)
1566 return Error(BitcodeError::InvalidRecord);
1568 Type *SelectorTy = Type::getInt1Ty(Context);
1570 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1571 // vector. Otherwise, it must be a single bit.
1572 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1573 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1574 VTy->getNumElements());
1576 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1578 ValueList.getConstantFwdRef(Record[1],CurTy),
1579 ValueList.getConstantFwdRef(Record[2],CurTy));
1582 case bitc::CST_CODE_CE_EXTRACTELT
1583 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1584 if (Record.size() < 3)
1585 return Error(BitcodeError::InvalidRecord);
1587 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1589 return Error(BitcodeError::InvalidRecord);
1590 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1591 Constant *Op1 = nullptr;
1592 if (Record.size() == 4) {
1593 Type *IdxTy = getTypeByID(Record[2]);
1595 return Error(BitcodeError::InvalidRecord);
1596 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1597 } else // TODO: Remove with llvm 4.0
1598 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1600 return Error(BitcodeError::InvalidRecord);
1601 V = ConstantExpr::getExtractElement(Op0, Op1);
1604 case bitc::CST_CODE_CE_INSERTELT
1605 : { // CE_INSERTELT: [opval, opval, opty, opval]
1606 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1607 if (Record.size() < 3 || !OpTy)
1608 return Error(BitcodeError::InvalidRecord);
1609 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1610 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1611 OpTy->getElementType());
1612 Constant *Op2 = nullptr;
1613 if (Record.size() == 4) {
1614 Type *IdxTy = getTypeByID(Record[2]);
1616 return Error(BitcodeError::InvalidRecord);
1617 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1618 } else // TODO: Remove with llvm 4.0
1619 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1621 return Error(BitcodeError::InvalidRecord);
1622 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1625 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1626 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1627 if (Record.size() < 3 || !OpTy)
1628 return Error(BitcodeError::InvalidRecord);
1629 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1630 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1631 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1632 OpTy->getNumElements());
1633 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1634 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1637 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1638 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1640 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1641 if (Record.size() < 4 || !RTy || !OpTy)
1642 return Error(BitcodeError::InvalidRecord);
1643 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1644 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1645 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1646 RTy->getNumElements());
1647 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1648 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1651 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1652 if (Record.size() < 4)
1653 return Error(BitcodeError::InvalidRecord);
1654 Type *OpTy = getTypeByID(Record[0]);
1656 return Error(BitcodeError::InvalidRecord);
1657 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1658 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1660 if (OpTy->isFPOrFPVectorTy())
1661 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1663 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1666 // This maintains backward compatibility, pre-asm dialect keywords.
1667 // FIXME: Remove with the 4.0 release.
1668 case bitc::CST_CODE_INLINEASM_OLD: {
1669 if (Record.size() < 2)
1670 return Error(BitcodeError::InvalidRecord);
1671 std::string AsmStr, ConstrStr;
1672 bool HasSideEffects = Record[0] & 1;
1673 bool IsAlignStack = Record[0] >> 1;
1674 unsigned AsmStrSize = Record[1];
1675 if (2+AsmStrSize >= Record.size())
1676 return Error(BitcodeError::InvalidRecord);
1677 unsigned ConstStrSize = Record[2+AsmStrSize];
1678 if (3+AsmStrSize+ConstStrSize > Record.size())
1679 return Error(BitcodeError::InvalidRecord);
1681 for (unsigned i = 0; i != AsmStrSize; ++i)
1682 AsmStr += (char)Record[2+i];
1683 for (unsigned i = 0; i != ConstStrSize; ++i)
1684 ConstrStr += (char)Record[3+AsmStrSize+i];
1685 PointerType *PTy = cast<PointerType>(CurTy);
1686 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1687 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1690 // This version adds support for the asm dialect keywords (e.g.,
1692 case bitc::CST_CODE_INLINEASM: {
1693 if (Record.size() < 2)
1694 return Error(BitcodeError::InvalidRecord);
1695 std::string AsmStr, ConstrStr;
1696 bool HasSideEffects = Record[0] & 1;
1697 bool IsAlignStack = (Record[0] >> 1) & 1;
1698 unsigned AsmDialect = Record[0] >> 2;
1699 unsigned AsmStrSize = Record[1];
1700 if (2+AsmStrSize >= Record.size())
1701 return Error(BitcodeError::InvalidRecord);
1702 unsigned ConstStrSize = Record[2+AsmStrSize];
1703 if (3+AsmStrSize+ConstStrSize > Record.size())
1704 return Error(BitcodeError::InvalidRecord);
1706 for (unsigned i = 0; i != AsmStrSize; ++i)
1707 AsmStr += (char)Record[2+i];
1708 for (unsigned i = 0; i != ConstStrSize; ++i)
1709 ConstrStr += (char)Record[3+AsmStrSize+i];
1710 PointerType *PTy = cast<PointerType>(CurTy);
1711 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1712 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1713 InlineAsm::AsmDialect(AsmDialect));
1716 case bitc::CST_CODE_BLOCKADDRESS:{
1717 if (Record.size() < 3)
1718 return Error(BitcodeError::InvalidRecord);
1719 Type *FnTy = getTypeByID(Record[0]);
1721 return Error(BitcodeError::InvalidRecord);
1723 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1725 return Error(BitcodeError::InvalidRecord);
1727 // Don't let Fn get dematerialized.
1728 BlockAddressesTaken.insert(Fn);
1730 // If the function is already parsed we can insert the block address right
1733 unsigned BBID = Record[2];
1735 // Invalid reference to entry block.
1736 return Error(BitcodeError::InvalidID);
1738 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1739 for (size_t I = 0, E = BBID; I != E; ++I) {
1741 return Error(BitcodeError::InvalidID);
1746 // Otherwise insert a placeholder and remember it so it can be inserted
1747 // when the function is parsed.
1748 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1750 BasicBlockFwdRefQueue.push_back(Fn);
1751 if (FwdBBs.size() < BBID + 1)
1752 FwdBBs.resize(BBID + 1);
1754 FwdBBs[BBID] = BasicBlock::Create(Context);
1757 V = BlockAddress::get(Fn, BB);
1762 ValueList.AssignValue(V, NextCstNo);
1767 std::error_code BitcodeReader::ParseUseLists() {
1768 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1769 return Error(BitcodeError::InvalidRecord);
1771 // Read all the records.
1772 SmallVector<uint64_t, 64> Record;
1774 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1776 switch (Entry.Kind) {
1777 case BitstreamEntry::SubBlock: // Handled for us already.
1778 case BitstreamEntry::Error:
1779 return Error(BitcodeError::MalformedBlock);
1780 case BitstreamEntry::EndBlock:
1781 return std::error_code();
1782 case BitstreamEntry::Record:
1783 // The interesting case.
1787 // Read a use list record.
1790 switch (Stream.readRecord(Entry.ID, Record)) {
1791 default: // Default behavior: unknown type.
1793 case bitc::USELIST_CODE_BB:
1796 case bitc::USELIST_CODE_DEFAULT: {
1797 unsigned RecordLength = Record.size();
1798 if (RecordLength < 3)
1799 // Records should have at least an ID and two indexes.
1800 return Error(BitcodeError::InvalidRecord);
1801 unsigned ID = Record.back();
1806 assert(ID < FunctionBBs.size() && "Basic block not found");
1807 V = FunctionBBs[ID];
1810 unsigned NumUses = 0;
1811 SmallDenseMap<const Use *, unsigned, 16> Order;
1812 for (const Use &U : V->uses()) {
1813 if (++NumUses > Record.size())
1815 Order[&U] = Record[NumUses - 1];
1817 if (Order.size() != Record.size() || NumUses > Record.size())
1818 // Mismatches can happen if the functions are being materialized lazily
1819 // (out-of-order), or a value has been upgraded.
1822 V->sortUseList([&](const Use &L, const Use &R) {
1823 return Order.lookup(&L) < Order.lookup(&R);
1831 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1832 /// remember where it is and then skip it. This lets us lazily deserialize the
1834 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1835 // Get the function we are talking about.
1836 if (FunctionsWithBodies.empty())
1837 return Error(BitcodeError::InsufficientFunctionProtos);
1839 Function *Fn = FunctionsWithBodies.back();
1840 FunctionsWithBodies.pop_back();
1842 // Save the current stream state.
1843 uint64_t CurBit = Stream.GetCurrentBitNo();
1844 DeferredFunctionInfo[Fn] = CurBit;
1846 // Skip over the function block for now.
1847 if (Stream.SkipBlock())
1848 return Error(BitcodeError::InvalidRecord);
1849 return std::error_code();
1852 std::error_code BitcodeReader::GlobalCleanup() {
1853 // Patch the initializers for globals and aliases up.
1854 ResolveGlobalAndAliasInits();
1855 if (!GlobalInits.empty() || !AliasInits.empty())
1856 return Error(BitcodeError::MalformedGlobalInitializerSet);
1858 // Look for intrinsic functions which need to be upgraded at some point
1859 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1862 if (UpgradeIntrinsicFunction(FI, NewFn))
1863 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1866 // Look for global variables which need to be renamed.
1867 for (Module::global_iterator
1868 GI = TheModule->global_begin(), GE = TheModule->global_end();
1870 GlobalVariable *GV = GI++;
1871 UpgradeGlobalVariable(GV);
1874 // Force deallocation of memory for these vectors to favor the client that
1875 // want lazy deserialization.
1876 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1877 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1878 return std::error_code();
1881 std::error_code BitcodeReader::ParseModule(bool Resume) {
1883 Stream.JumpToBit(NextUnreadBit);
1884 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1885 return Error(BitcodeError::InvalidRecord);
1887 SmallVector<uint64_t, 64> Record;
1888 std::vector<std::string> SectionTable;
1889 std::vector<std::string> GCTable;
1891 // Read all the records for this module.
1893 BitstreamEntry Entry = Stream.advance();
1895 switch (Entry.Kind) {
1896 case BitstreamEntry::Error:
1897 return Error(BitcodeError::MalformedBlock);
1898 case BitstreamEntry::EndBlock:
1899 return GlobalCleanup();
1901 case BitstreamEntry::SubBlock:
1903 default: // Skip unknown content.
1904 if (Stream.SkipBlock())
1905 return Error(BitcodeError::InvalidRecord);
1907 case bitc::BLOCKINFO_BLOCK_ID:
1908 if (Stream.ReadBlockInfoBlock())
1909 return Error(BitcodeError::MalformedBlock);
1911 case bitc::PARAMATTR_BLOCK_ID:
1912 if (std::error_code EC = ParseAttributeBlock())
1915 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1916 if (std::error_code EC = ParseAttributeGroupBlock())
1919 case bitc::TYPE_BLOCK_ID_NEW:
1920 if (std::error_code EC = ParseTypeTable())
1923 case bitc::VALUE_SYMTAB_BLOCK_ID:
1924 if (std::error_code EC = ParseValueSymbolTable())
1926 SeenValueSymbolTable = true;
1928 case bitc::CONSTANTS_BLOCK_ID:
1929 if (std::error_code EC = ParseConstants())
1931 if (std::error_code EC = ResolveGlobalAndAliasInits())
1934 case bitc::METADATA_BLOCK_ID:
1935 if (std::error_code EC = ParseMetadata())
1938 case bitc::FUNCTION_BLOCK_ID:
1939 // If this is the first function body we've seen, reverse the
1940 // FunctionsWithBodies list.
1941 if (!SeenFirstFunctionBody) {
1942 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1943 if (std::error_code EC = GlobalCleanup())
1945 SeenFirstFunctionBody = true;
1948 if (std::error_code EC = RememberAndSkipFunctionBody())
1950 // For streaming bitcode, suspend parsing when we reach the function
1951 // bodies. Subsequent materialization calls will resume it when
1952 // necessary. For streaming, the function bodies must be at the end of
1953 // the bitcode. If the bitcode file is old, the symbol table will be
1954 // at the end instead and will not have been seen yet. In this case,
1955 // just finish the parse now.
1956 if (LazyStreamer && SeenValueSymbolTable) {
1957 NextUnreadBit = Stream.GetCurrentBitNo();
1958 return std::error_code();
1961 case bitc::USELIST_BLOCK_ID:
1962 if (std::error_code EC = ParseUseLists())
1968 case BitstreamEntry::Record:
1969 // The interesting case.
1975 switch (Stream.readRecord(Entry.ID, Record)) {
1976 default: break; // Default behavior, ignore unknown content.
1977 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1978 if (Record.size() < 1)
1979 return Error(BitcodeError::InvalidRecord);
1980 // Only version #0 and #1 are supported so far.
1981 unsigned module_version = Record[0];
1982 switch (module_version) {
1984 return Error(BitcodeError::InvalidValue);
1986 UseRelativeIDs = false;
1989 UseRelativeIDs = true;
1994 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1996 if (ConvertToString(Record, 0, S))
1997 return Error(BitcodeError::InvalidRecord);
1998 TheModule->setTargetTriple(S);
2001 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2003 if (ConvertToString(Record, 0, S))
2004 return Error(BitcodeError::InvalidRecord);
2005 TheModule->setDataLayout(S);
2008 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2010 if (ConvertToString(Record, 0, S))
2011 return Error(BitcodeError::InvalidRecord);
2012 TheModule->setModuleInlineAsm(S);
2015 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2016 // FIXME: Remove in 4.0.
2018 if (ConvertToString(Record, 0, S))
2019 return Error(BitcodeError::InvalidRecord);
2023 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2025 if (ConvertToString(Record, 0, S))
2026 return Error(BitcodeError::InvalidRecord);
2027 SectionTable.push_back(S);
2030 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2032 if (ConvertToString(Record, 0, S))
2033 return Error(BitcodeError::InvalidRecord);
2034 GCTable.push_back(S);
2037 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2038 if (Record.size() < 2)
2039 return Error(BitcodeError::InvalidRecord);
2040 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2041 unsigned ComdatNameSize = Record[1];
2042 std::string ComdatName;
2043 ComdatName.reserve(ComdatNameSize);
2044 for (unsigned i = 0; i != ComdatNameSize; ++i)
2045 ComdatName += (char)Record[2 + i];
2046 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2047 C->setSelectionKind(SK);
2048 ComdatList.push_back(C);
2051 // GLOBALVAR: [pointer type, isconst, initid,
2052 // linkage, alignment, section, visibility, threadlocal,
2053 // unnamed_addr, dllstorageclass]
2054 case bitc::MODULE_CODE_GLOBALVAR: {
2055 if (Record.size() < 6)
2056 return Error(BitcodeError::InvalidRecord);
2057 Type *Ty = getTypeByID(Record[0]);
2059 return Error(BitcodeError::InvalidRecord);
2060 if (!Ty->isPointerTy())
2061 return Error(BitcodeError::InvalidTypeForValue);
2062 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2063 Ty = cast<PointerType>(Ty)->getElementType();
2065 bool isConstant = Record[1];
2066 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Record[3]);
2067 unsigned Alignment = (1 << Record[4]) >> 1;
2068 std::string Section;
2070 if (Record[5]-1 >= SectionTable.size())
2071 return Error(BitcodeError::InvalidID);
2072 Section = SectionTable[Record[5]-1];
2074 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2075 // Local linkage must have default visibility.
2076 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2077 // FIXME: Change to an error if non-default in 4.0.
2078 Visibility = GetDecodedVisibility(Record[6]);
2080 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2081 if (Record.size() > 7)
2082 TLM = GetDecodedThreadLocalMode(Record[7]);
2084 bool UnnamedAddr = false;
2085 if (Record.size() > 8)
2086 UnnamedAddr = Record[8];
2088 bool ExternallyInitialized = false;
2089 if (Record.size() > 9)
2090 ExternallyInitialized = Record[9];
2092 GlobalVariable *NewGV =
2093 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2094 TLM, AddressSpace, ExternallyInitialized);
2095 NewGV->setAlignment(Alignment);
2096 if (!Section.empty())
2097 NewGV->setSection(Section);
2098 NewGV->setVisibility(Visibility);
2099 NewGV->setUnnamedAddr(UnnamedAddr);
2101 if (Record.size() > 10)
2102 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2104 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2106 ValueList.push_back(NewGV);
2108 // Remember which value to use for the global initializer.
2109 if (unsigned InitID = Record[2])
2110 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2112 if (Record.size() > 11)
2113 if (unsigned ComdatID = Record[11]) {
2114 assert(ComdatID <= ComdatList.size());
2115 NewGV->setComdat(ComdatList[ComdatID - 1]);
2119 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2120 // alignment, section, visibility, gc, unnamed_addr,
2121 // prologuedata, dllstorageclass, comdat, prefixdata]
2122 case bitc::MODULE_CODE_FUNCTION: {
2123 if (Record.size() < 8)
2124 return Error(BitcodeError::InvalidRecord);
2125 Type *Ty = getTypeByID(Record[0]);
2127 return Error(BitcodeError::InvalidRecord);
2128 if (!Ty->isPointerTy())
2129 return Error(BitcodeError::InvalidTypeForValue);
2131 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2133 return Error(BitcodeError::InvalidTypeForValue);
2135 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2138 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2139 bool isProto = Record[2];
2140 Func->setLinkage(getDecodedLinkage(Record[3]));
2141 Func->setAttributes(getAttributes(Record[4]));
2143 Func->setAlignment((1 << Record[5]) >> 1);
2145 if (Record[6]-1 >= SectionTable.size())
2146 return Error(BitcodeError::InvalidID);
2147 Func->setSection(SectionTable[Record[6]-1]);
2149 // Local linkage must have default visibility.
2150 if (!Func->hasLocalLinkage())
2151 // FIXME: Change to an error if non-default in 4.0.
2152 Func->setVisibility(GetDecodedVisibility(Record[7]));
2153 if (Record.size() > 8 && Record[8]) {
2154 if (Record[8]-1 > GCTable.size())
2155 return Error(BitcodeError::InvalidID);
2156 Func->setGC(GCTable[Record[8]-1].c_str());
2158 bool UnnamedAddr = false;
2159 if (Record.size() > 9)
2160 UnnamedAddr = Record[9];
2161 Func->setUnnamedAddr(UnnamedAddr);
2162 if (Record.size() > 10 && Record[10] != 0)
2163 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2165 if (Record.size() > 11)
2166 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2168 UpgradeDLLImportExportLinkage(Func, Record[3]);
2170 if (Record.size() > 12)
2171 if (unsigned ComdatID = Record[12]) {
2172 assert(ComdatID <= ComdatList.size());
2173 Func->setComdat(ComdatList[ComdatID - 1]);
2176 if (Record.size() > 13 && Record[13] != 0)
2177 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2179 ValueList.push_back(Func);
2181 // If this is a function with a body, remember the prototype we are
2182 // creating now, so that we can match up the body with them later.
2184 Func->setIsMaterializable(true);
2185 FunctionsWithBodies.push_back(Func);
2187 DeferredFunctionInfo[Func] = 0;
2191 // ALIAS: [alias type, aliasee val#, linkage]
2192 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2193 case bitc::MODULE_CODE_ALIAS: {
2194 if (Record.size() < 3)
2195 return Error(BitcodeError::InvalidRecord);
2196 Type *Ty = getTypeByID(Record[0]);
2198 return Error(BitcodeError::InvalidRecord);
2199 auto *PTy = dyn_cast<PointerType>(Ty);
2201 return Error(BitcodeError::InvalidTypeForValue);
2204 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2205 getDecodedLinkage(Record[2]), "", TheModule);
2206 // Old bitcode files didn't have visibility field.
2207 // Local linkage must have default visibility.
2208 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2209 // FIXME: Change to an error if non-default in 4.0.
2210 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2211 if (Record.size() > 4)
2212 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2214 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2215 if (Record.size() > 5)
2216 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2217 if (Record.size() > 6)
2218 NewGA->setUnnamedAddr(Record[6]);
2219 ValueList.push_back(NewGA);
2220 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2223 /// MODULE_CODE_PURGEVALS: [numvals]
2224 case bitc::MODULE_CODE_PURGEVALS:
2225 // Trim down the value list to the specified size.
2226 if (Record.size() < 1 || Record[0] > ValueList.size())
2227 return Error(BitcodeError::InvalidRecord);
2228 ValueList.shrinkTo(Record[0]);
2235 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2236 TheModule = nullptr;
2238 if (std::error_code EC = InitStream())
2241 // Sniff for the signature.
2242 if (Stream.Read(8) != 'B' ||
2243 Stream.Read(8) != 'C' ||
2244 Stream.Read(4) != 0x0 ||
2245 Stream.Read(4) != 0xC ||
2246 Stream.Read(4) != 0xE ||
2247 Stream.Read(4) != 0xD)
2248 return Error(BitcodeError::InvalidBitcodeSignature);
2250 // We expect a number of well-defined blocks, though we don't necessarily
2251 // need to understand them all.
2253 if (Stream.AtEndOfStream())
2254 return std::error_code();
2256 BitstreamEntry Entry =
2257 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2259 switch (Entry.Kind) {
2260 case BitstreamEntry::Error:
2261 return Error(BitcodeError::MalformedBlock);
2262 case BitstreamEntry::EndBlock:
2263 return std::error_code();
2265 case BitstreamEntry::SubBlock:
2267 case bitc::BLOCKINFO_BLOCK_ID:
2268 if (Stream.ReadBlockInfoBlock())
2269 return Error(BitcodeError::MalformedBlock);
2271 case bitc::MODULE_BLOCK_ID:
2272 // Reject multiple MODULE_BLOCK's in a single bitstream.
2274 return Error(BitcodeError::InvalidMultipleBlocks);
2276 if (std::error_code EC = ParseModule(false))
2279 return std::error_code();
2282 if (Stream.SkipBlock())
2283 return Error(BitcodeError::InvalidRecord);
2287 case BitstreamEntry::Record:
2288 // There should be no records in the top-level of blocks.
2290 // The ranlib in Xcode 4 will align archive members by appending newlines
2291 // to the end of them. If this file size is a multiple of 4 but not 8, we
2292 // have to read and ignore these final 4 bytes :-(
2293 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2294 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2295 Stream.AtEndOfStream())
2296 return std::error_code();
2298 return Error(BitcodeError::InvalidRecord);
2303 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2304 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2305 return Error(BitcodeError::InvalidRecord);
2307 SmallVector<uint64_t, 64> Record;
2310 // Read all the records for this module.
2312 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2314 switch (Entry.Kind) {
2315 case BitstreamEntry::SubBlock: // Handled for us already.
2316 case BitstreamEntry::Error:
2317 return Error(BitcodeError::MalformedBlock);
2318 case BitstreamEntry::EndBlock:
2320 case BitstreamEntry::Record:
2321 // The interesting case.
2326 switch (Stream.readRecord(Entry.ID, Record)) {
2327 default: break; // Default behavior, ignore unknown content.
2328 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2330 if (ConvertToString(Record, 0, S))
2331 return Error(BitcodeError::InvalidRecord);
2338 llvm_unreachable("Exit infinite loop");
2341 ErrorOr<std::string> BitcodeReader::parseTriple() {
2342 if (std::error_code EC = InitStream())
2345 // Sniff for the signature.
2346 if (Stream.Read(8) != 'B' ||
2347 Stream.Read(8) != 'C' ||
2348 Stream.Read(4) != 0x0 ||
2349 Stream.Read(4) != 0xC ||
2350 Stream.Read(4) != 0xE ||
2351 Stream.Read(4) != 0xD)
2352 return Error(BitcodeError::InvalidBitcodeSignature);
2354 // We expect a number of well-defined blocks, though we don't necessarily
2355 // need to understand them all.
2357 BitstreamEntry Entry = Stream.advance();
2359 switch (Entry.Kind) {
2360 case BitstreamEntry::Error:
2361 return Error(BitcodeError::MalformedBlock);
2362 case BitstreamEntry::EndBlock:
2363 return std::error_code();
2365 case BitstreamEntry::SubBlock:
2366 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2367 return parseModuleTriple();
2369 // Ignore other sub-blocks.
2370 if (Stream.SkipBlock())
2371 return Error(BitcodeError::MalformedBlock);
2374 case BitstreamEntry::Record:
2375 Stream.skipRecord(Entry.ID);
2381 /// ParseMetadataAttachment - Parse metadata attachments.
2382 std::error_code BitcodeReader::ParseMetadataAttachment() {
2383 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2384 return Error(BitcodeError::InvalidRecord);
2386 SmallVector<uint64_t, 64> Record;
2388 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2390 switch (Entry.Kind) {
2391 case BitstreamEntry::SubBlock: // Handled for us already.
2392 case BitstreamEntry::Error:
2393 return Error(BitcodeError::MalformedBlock);
2394 case BitstreamEntry::EndBlock:
2395 return std::error_code();
2396 case BitstreamEntry::Record:
2397 // The interesting case.
2401 // Read a metadata attachment record.
2403 switch (Stream.readRecord(Entry.ID, Record)) {
2404 default: // Default behavior: ignore.
2406 case bitc::METADATA_ATTACHMENT: {
2407 unsigned RecordLength = Record.size();
2408 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2409 return Error(BitcodeError::InvalidRecord);
2410 Instruction *Inst = InstructionList[Record[0]];
2411 for (unsigned i = 1; i != RecordLength; i = i+2) {
2412 unsigned Kind = Record[i];
2413 DenseMap<unsigned, unsigned>::iterator I =
2414 MDKindMap.find(Kind);
2415 if (I == MDKindMap.end())
2416 return Error(BitcodeError::InvalidID);
2417 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2418 if (isa<LocalAsMetadata>(Node))
2419 // Drop the attachment. This used to be legal, but there's no
2422 Inst->setMetadata(I->second, cast<MDNode>(Node));
2423 if (I->second == LLVMContext::MD_tbaa)
2424 InstsWithTBAATag.push_back(Inst);
2432 /// ParseFunctionBody - Lazily parse the specified function body block.
2433 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2434 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2435 return Error(BitcodeError::InvalidRecord);
2437 InstructionList.clear();
2438 unsigned ModuleValueListSize = ValueList.size();
2439 unsigned ModuleMDValueListSize = MDValueList.size();
2441 // Add all the function arguments to the value table.
2442 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2443 ValueList.push_back(I);
2445 unsigned NextValueNo = ValueList.size();
2446 BasicBlock *CurBB = nullptr;
2447 unsigned CurBBNo = 0;
2451 // Read all the records.
2452 SmallVector<uint64_t, 64> Record;
2454 BitstreamEntry Entry = Stream.advance();
2456 switch (Entry.Kind) {
2457 case BitstreamEntry::Error:
2458 return Error(BitcodeError::MalformedBlock);
2459 case BitstreamEntry::EndBlock:
2460 goto OutOfRecordLoop;
2462 case BitstreamEntry::SubBlock:
2464 default: // Skip unknown content.
2465 if (Stream.SkipBlock())
2466 return Error(BitcodeError::InvalidRecord);
2468 case bitc::CONSTANTS_BLOCK_ID:
2469 if (std::error_code EC = ParseConstants())
2471 NextValueNo = ValueList.size();
2473 case bitc::VALUE_SYMTAB_BLOCK_ID:
2474 if (std::error_code EC = ParseValueSymbolTable())
2477 case bitc::METADATA_ATTACHMENT_ID:
2478 if (std::error_code EC = ParseMetadataAttachment())
2481 case bitc::METADATA_BLOCK_ID:
2482 if (std::error_code EC = ParseMetadata())
2485 case bitc::USELIST_BLOCK_ID:
2486 if (std::error_code EC = ParseUseLists())
2492 case BitstreamEntry::Record:
2493 // The interesting case.
2499 Instruction *I = nullptr;
2500 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2502 default: // Default behavior: reject
2503 return Error(BitcodeError::InvalidValue);
2504 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2505 if (Record.size() < 1 || Record[0] == 0)
2506 return Error(BitcodeError::InvalidRecord);
2507 // Create all the basic blocks for the function.
2508 FunctionBBs.resize(Record[0]);
2510 // See if anything took the address of blocks in this function.
2511 auto BBFRI = BasicBlockFwdRefs.find(F);
2512 if (BBFRI == BasicBlockFwdRefs.end()) {
2513 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2514 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2516 auto &BBRefs = BBFRI->second;
2517 // Check for invalid basic block references.
2518 if (BBRefs.size() > FunctionBBs.size())
2519 return Error(BitcodeError::InvalidID);
2520 assert(!BBRefs.empty() && "Unexpected empty array");
2521 assert(!BBRefs.front() && "Invalid reference to entry block");
2522 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2524 if (I < RE && BBRefs[I]) {
2525 BBRefs[I]->insertInto(F);
2526 FunctionBBs[I] = BBRefs[I];
2528 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2531 // Erase from the table.
2532 BasicBlockFwdRefs.erase(BBFRI);
2535 CurBB = FunctionBBs[0];
2539 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2540 // This record indicates that the last instruction is at the same
2541 // location as the previous instruction with a location.
2544 // Get the last instruction emitted.
2545 if (CurBB && !CurBB->empty())
2547 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2548 !FunctionBBs[CurBBNo-1]->empty())
2549 I = &FunctionBBs[CurBBNo-1]->back();
2552 return Error(BitcodeError::InvalidRecord);
2553 I->setDebugLoc(LastLoc);
2557 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2558 I = nullptr; // Get the last instruction emitted.
2559 if (CurBB && !CurBB->empty())
2561 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2562 !FunctionBBs[CurBBNo-1]->empty())
2563 I = &FunctionBBs[CurBBNo-1]->back();
2564 if (!I || Record.size() < 4)
2565 return Error(BitcodeError::InvalidRecord);
2567 unsigned Line = Record[0], Col = Record[1];
2568 unsigned ScopeID = Record[2], IAID = Record[3];
2570 MDNode *Scope = nullptr, *IA = nullptr;
2571 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2572 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2573 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2574 I->setDebugLoc(LastLoc);
2579 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2582 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2583 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2584 OpNum+1 > Record.size())
2585 return Error(BitcodeError::InvalidRecord);
2587 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2589 return Error(BitcodeError::InvalidRecord);
2590 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2591 InstructionList.push_back(I);
2592 if (OpNum < Record.size()) {
2593 if (Opc == Instruction::Add ||
2594 Opc == Instruction::Sub ||
2595 Opc == Instruction::Mul ||
2596 Opc == Instruction::Shl) {
2597 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2598 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2599 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2600 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2601 } else if (Opc == Instruction::SDiv ||
2602 Opc == Instruction::UDiv ||
2603 Opc == Instruction::LShr ||
2604 Opc == Instruction::AShr) {
2605 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2606 cast<BinaryOperator>(I)->setIsExact(true);
2607 } else if (isa<FPMathOperator>(I)) {
2609 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2610 FMF.setUnsafeAlgebra();
2611 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2613 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2615 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2616 FMF.setNoSignedZeros();
2617 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2618 FMF.setAllowReciprocal();
2620 I->setFastMathFlags(FMF);
2626 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2629 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2630 OpNum+2 != Record.size())
2631 return Error(BitcodeError::InvalidRecord);
2633 Type *ResTy = getTypeByID(Record[OpNum]);
2634 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2635 if (Opc == -1 || !ResTy)
2636 return Error(BitcodeError::InvalidRecord);
2637 Instruction *Temp = nullptr;
2638 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2640 InstructionList.push_back(Temp);
2641 CurBB->getInstList().push_back(Temp);
2644 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2646 InstructionList.push_back(I);
2649 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2650 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2653 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2654 return Error(BitcodeError::InvalidRecord);
2656 SmallVector<Value*, 16> GEPIdx;
2657 while (OpNum != Record.size()) {
2659 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2660 return Error(BitcodeError::InvalidRecord);
2661 GEPIdx.push_back(Op);
2664 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2665 InstructionList.push_back(I);
2666 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2667 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2671 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2672 // EXTRACTVAL: [opty, opval, n x indices]
2675 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2676 return Error(BitcodeError::InvalidRecord);
2678 SmallVector<unsigned, 4> EXTRACTVALIdx;
2679 for (unsigned RecSize = Record.size();
2680 OpNum != RecSize; ++OpNum) {
2681 uint64_t Index = Record[OpNum];
2682 if ((unsigned)Index != Index)
2683 return Error(BitcodeError::InvalidValue);
2684 EXTRACTVALIdx.push_back((unsigned)Index);
2687 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2688 InstructionList.push_back(I);
2692 case bitc::FUNC_CODE_INST_INSERTVAL: {
2693 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2696 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2697 return Error(BitcodeError::InvalidRecord);
2699 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2700 return Error(BitcodeError::InvalidRecord);
2702 SmallVector<unsigned, 4> INSERTVALIdx;
2703 for (unsigned RecSize = Record.size();
2704 OpNum != RecSize; ++OpNum) {
2705 uint64_t Index = Record[OpNum];
2706 if ((unsigned)Index != Index)
2707 return Error(BitcodeError::InvalidValue);
2708 INSERTVALIdx.push_back((unsigned)Index);
2711 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2712 InstructionList.push_back(I);
2716 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2717 // obsolete form of select
2718 // handles select i1 ... in old bitcode
2720 Value *TrueVal, *FalseVal, *Cond;
2721 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2722 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2723 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2724 return Error(BitcodeError::InvalidRecord);
2726 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2727 InstructionList.push_back(I);
2731 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2732 // new form of select
2733 // handles select i1 or select [N x i1]
2735 Value *TrueVal, *FalseVal, *Cond;
2736 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2737 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2738 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2739 return Error(BitcodeError::InvalidRecord);
2741 // select condition can be either i1 or [N x i1]
2742 if (VectorType* vector_type =
2743 dyn_cast<VectorType>(Cond->getType())) {
2745 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2746 return Error(BitcodeError::InvalidTypeForValue);
2749 if (Cond->getType() != Type::getInt1Ty(Context))
2750 return Error(BitcodeError::InvalidTypeForValue);
2753 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2754 InstructionList.push_back(I);
2758 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2761 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2762 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2763 return Error(BitcodeError::InvalidRecord);
2764 I = ExtractElementInst::Create(Vec, Idx);
2765 InstructionList.push_back(I);
2769 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2771 Value *Vec, *Elt, *Idx;
2772 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2773 popValue(Record, OpNum, NextValueNo,
2774 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2775 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2776 return Error(BitcodeError::InvalidRecord);
2777 I = InsertElementInst::Create(Vec, Elt, Idx);
2778 InstructionList.push_back(I);
2782 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2784 Value *Vec1, *Vec2, *Mask;
2785 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2786 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2787 return Error(BitcodeError::InvalidRecord);
2789 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2790 return Error(BitcodeError::InvalidRecord);
2791 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2792 InstructionList.push_back(I);
2796 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2797 // Old form of ICmp/FCmp returning bool
2798 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2799 // both legal on vectors but had different behaviour.
2800 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2801 // FCmp/ICmp returning bool or vector of bool
2805 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2806 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2807 OpNum+1 != Record.size())
2808 return Error(BitcodeError::InvalidRecord);
2810 if (LHS->getType()->isFPOrFPVectorTy())
2811 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2813 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2814 InstructionList.push_back(I);
2818 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2820 unsigned Size = Record.size();
2822 I = ReturnInst::Create(Context);
2823 InstructionList.push_back(I);
2828 Value *Op = nullptr;
2829 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2830 return Error(BitcodeError::InvalidRecord);
2831 if (OpNum != Record.size())
2832 return Error(BitcodeError::InvalidRecord);
2834 I = ReturnInst::Create(Context, Op);
2835 InstructionList.push_back(I);
2838 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2839 if (Record.size() != 1 && Record.size() != 3)
2840 return Error(BitcodeError::InvalidRecord);
2841 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2843 return Error(BitcodeError::InvalidRecord);
2845 if (Record.size() == 1) {
2846 I = BranchInst::Create(TrueDest);
2847 InstructionList.push_back(I);
2850 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2851 Value *Cond = getValue(Record, 2, NextValueNo,
2852 Type::getInt1Ty(Context));
2853 if (!FalseDest || !Cond)
2854 return Error(BitcodeError::InvalidRecord);
2855 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2856 InstructionList.push_back(I);
2860 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2862 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2863 // "New" SwitchInst format with case ranges. The changes to write this
2864 // format were reverted but we still recognize bitcode that uses it.
2865 // Hopefully someday we will have support for case ranges and can use
2866 // this format again.
2868 Type *OpTy = getTypeByID(Record[1]);
2869 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2871 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2872 BasicBlock *Default = getBasicBlock(Record[3]);
2873 if (!OpTy || !Cond || !Default)
2874 return Error(BitcodeError::InvalidRecord);
2876 unsigned NumCases = Record[4];
2878 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2879 InstructionList.push_back(SI);
2881 unsigned CurIdx = 5;
2882 for (unsigned i = 0; i != NumCases; ++i) {
2883 SmallVector<ConstantInt*, 1> CaseVals;
2884 unsigned NumItems = Record[CurIdx++];
2885 for (unsigned ci = 0; ci != NumItems; ++ci) {
2886 bool isSingleNumber = Record[CurIdx++];
2889 unsigned ActiveWords = 1;
2890 if (ValueBitWidth > 64)
2891 ActiveWords = Record[CurIdx++];
2892 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2894 CurIdx += ActiveWords;
2896 if (!isSingleNumber) {
2898 if (ValueBitWidth > 64)
2899 ActiveWords = Record[CurIdx++];
2901 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2903 CurIdx += ActiveWords;
2905 // FIXME: It is not clear whether values in the range should be
2906 // compared as signed or unsigned values. The partially
2907 // implemented changes that used this format in the past used
2908 // unsigned comparisons.
2909 for ( ; Low.ule(High); ++Low)
2910 CaseVals.push_back(ConstantInt::get(Context, Low));
2912 CaseVals.push_back(ConstantInt::get(Context, Low));
2914 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2915 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2916 cve = CaseVals.end(); cvi != cve; ++cvi)
2917 SI->addCase(*cvi, DestBB);
2923 // Old SwitchInst format without case ranges.
2925 if (Record.size() < 3 || (Record.size() & 1) == 0)
2926 return Error(BitcodeError::InvalidRecord);
2927 Type *OpTy = getTypeByID(Record[0]);
2928 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2929 BasicBlock *Default = getBasicBlock(Record[2]);
2930 if (!OpTy || !Cond || !Default)
2931 return Error(BitcodeError::InvalidRecord);
2932 unsigned NumCases = (Record.size()-3)/2;
2933 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2934 InstructionList.push_back(SI);
2935 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2936 ConstantInt *CaseVal =
2937 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2938 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2939 if (!CaseVal || !DestBB) {
2941 return Error(BitcodeError::InvalidRecord);
2943 SI->addCase(CaseVal, DestBB);
2948 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2949 if (Record.size() < 2)
2950 return Error(BitcodeError::InvalidRecord);
2951 Type *OpTy = getTypeByID(Record[0]);
2952 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2953 if (!OpTy || !Address)
2954 return Error(BitcodeError::InvalidRecord);
2955 unsigned NumDests = Record.size()-2;
2956 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2957 InstructionList.push_back(IBI);
2958 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2959 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2960 IBI->addDestination(DestBB);
2963 return Error(BitcodeError::InvalidRecord);
2970 case bitc::FUNC_CODE_INST_INVOKE: {
2971 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2972 if (Record.size() < 4)
2973 return Error(BitcodeError::InvalidRecord);
2974 AttributeSet PAL = getAttributes(Record[0]);
2975 unsigned CCInfo = Record[1];
2976 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2977 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2981 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2982 return Error(BitcodeError::InvalidRecord);
2984 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2985 FunctionType *FTy = !CalleeTy ? nullptr :
2986 dyn_cast<FunctionType>(CalleeTy->getElementType());
2988 // Check that the right number of fixed parameters are here.
2989 if (!FTy || !NormalBB || !UnwindBB ||
2990 Record.size() < OpNum+FTy->getNumParams())
2991 return Error(BitcodeError::InvalidRecord);
2993 SmallVector<Value*, 16> Ops;
2994 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2995 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2996 FTy->getParamType(i)));
2998 return Error(BitcodeError::InvalidRecord);
3001 if (!FTy->isVarArg()) {
3002 if (Record.size() != OpNum)
3003 return Error(BitcodeError::InvalidRecord);
3005 // Read type/value pairs for varargs params.
3006 while (OpNum != Record.size()) {
3008 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3009 return Error(BitcodeError::InvalidRecord);
3014 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3015 InstructionList.push_back(I);
3016 cast<InvokeInst>(I)->setCallingConv(
3017 static_cast<CallingConv::ID>(CCInfo));
3018 cast<InvokeInst>(I)->setAttributes(PAL);
3021 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3023 Value *Val = nullptr;
3024 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3025 return Error(BitcodeError::InvalidRecord);
3026 I = ResumeInst::Create(Val);
3027 InstructionList.push_back(I);
3030 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3031 I = new UnreachableInst(Context);
3032 InstructionList.push_back(I);
3034 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3035 if (Record.size() < 1 || ((Record.size()-1)&1))
3036 return Error(BitcodeError::InvalidRecord);
3037 Type *Ty = getTypeByID(Record[0]);
3039 return Error(BitcodeError::InvalidRecord);
3041 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3042 InstructionList.push_back(PN);
3044 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3046 // With the new function encoding, it is possible that operands have
3047 // negative IDs (for forward references). Use a signed VBR
3048 // representation to keep the encoding small.
3050 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3052 V = getValue(Record, 1+i, NextValueNo, Ty);
3053 BasicBlock *BB = getBasicBlock(Record[2+i]);
3055 return Error(BitcodeError::InvalidRecord);
3056 PN->addIncoming(V, BB);
3062 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3063 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3065 if (Record.size() < 4)
3066 return Error(BitcodeError::InvalidRecord);
3067 Type *Ty = getTypeByID(Record[Idx++]);
3069 return Error(BitcodeError::InvalidRecord);
3070 Value *PersFn = nullptr;
3071 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3072 return Error(BitcodeError::InvalidRecord);
3074 bool IsCleanup = !!Record[Idx++];
3075 unsigned NumClauses = Record[Idx++];
3076 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3077 LP->setCleanup(IsCleanup);
3078 for (unsigned J = 0; J != NumClauses; ++J) {
3079 LandingPadInst::ClauseType CT =
3080 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3083 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3085 return Error(BitcodeError::InvalidRecord);
3088 assert((CT != LandingPadInst::Catch ||
3089 !isa<ArrayType>(Val->getType())) &&
3090 "Catch clause has a invalid type!");
3091 assert((CT != LandingPadInst::Filter ||
3092 isa<ArrayType>(Val->getType())) &&
3093 "Filter clause has invalid type!");
3094 LP->addClause(cast<Constant>(Val));
3098 InstructionList.push_back(I);
3102 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3103 if (Record.size() != 4)
3104 return Error(BitcodeError::InvalidRecord);
3106 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3107 Type *OpTy = getTypeByID(Record[1]);
3108 Value *Size = getFnValueByID(Record[2], OpTy);
3109 unsigned AlignRecord = Record[3];
3110 bool InAlloca = AlignRecord & (1 << 5);
3111 unsigned Align = AlignRecord & ((1 << 5) - 1);
3113 return Error(BitcodeError::InvalidRecord);
3114 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3115 AI->setUsedWithInAlloca(InAlloca);
3117 InstructionList.push_back(I);
3120 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3123 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3124 OpNum+2 != Record.size())
3125 return Error(BitcodeError::InvalidRecord);
3127 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3128 InstructionList.push_back(I);
3131 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3132 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3135 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3136 OpNum+4 != Record.size())
3137 return Error(BitcodeError::InvalidRecord);
3139 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3140 if (Ordering == NotAtomic || Ordering == Release ||
3141 Ordering == AcquireRelease)
3142 return Error(BitcodeError::InvalidRecord);
3143 if (Ordering != NotAtomic && Record[OpNum] == 0)
3144 return Error(BitcodeError::InvalidRecord);
3145 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3147 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3148 Ordering, SynchScope);
3149 InstructionList.push_back(I);
3152 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3155 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3156 popValue(Record, OpNum, NextValueNo,
3157 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3158 OpNum+2 != Record.size())
3159 return Error(BitcodeError::InvalidRecord);
3161 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3162 InstructionList.push_back(I);
3165 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3166 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3169 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3170 popValue(Record, OpNum, NextValueNo,
3171 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3172 OpNum+4 != Record.size())
3173 return Error(BitcodeError::InvalidRecord);
3175 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3176 if (Ordering == NotAtomic || Ordering == Acquire ||
3177 Ordering == AcquireRelease)
3178 return Error(BitcodeError::InvalidRecord);
3179 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3180 if (Ordering != NotAtomic && Record[OpNum] == 0)
3181 return Error(BitcodeError::InvalidRecord);
3183 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3184 Ordering, SynchScope);
3185 InstructionList.push_back(I);
3188 case bitc::FUNC_CODE_INST_CMPXCHG: {
3189 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3190 // failureordering?, isweak?]
3192 Value *Ptr, *Cmp, *New;
3193 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3194 popValue(Record, OpNum, NextValueNo,
3195 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3196 popValue(Record, OpNum, NextValueNo,
3197 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3198 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3199 return Error(BitcodeError::InvalidRecord);
3200 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3201 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3202 return Error(BitcodeError::InvalidRecord);
3203 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3205 AtomicOrdering FailureOrdering;
3206 if (Record.size() < 7)
3208 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3210 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3212 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3214 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3216 if (Record.size() < 8) {
3217 // Before weak cmpxchgs existed, the instruction simply returned the
3218 // value loaded from memory, so bitcode files from that era will be
3219 // expecting the first component of a modern cmpxchg.
3220 CurBB->getInstList().push_back(I);
3221 I = ExtractValueInst::Create(I, 0);
3223 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3226 InstructionList.push_back(I);
3229 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3230 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3233 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3234 popValue(Record, OpNum, NextValueNo,
3235 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3236 OpNum+4 != Record.size())
3237 return Error(BitcodeError::InvalidRecord);
3238 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3239 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3240 Operation > AtomicRMWInst::LAST_BINOP)
3241 return Error(BitcodeError::InvalidRecord);
3242 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3243 if (Ordering == NotAtomic || Ordering == Unordered)
3244 return Error(BitcodeError::InvalidRecord);
3245 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3246 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3247 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3248 InstructionList.push_back(I);
3251 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3252 if (2 != Record.size())
3253 return Error(BitcodeError::InvalidRecord);
3254 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3255 if (Ordering == NotAtomic || Ordering == Unordered ||
3256 Ordering == Monotonic)
3257 return Error(BitcodeError::InvalidRecord);
3258 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3259 I = new FenceInst(Context, Ordering, SynchScope);
3260 InstructionList.push_back(I);
3263 case bitc::FUNC_CODE_INST_CALL: {
3264 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3265 if (Record.size() < 3)
3266 return Error(BitcodeError::InvalidRecord);
3268 AttributeSet PAL = getAttributes(Record[0]);
3269 unsigned CCInfo = Record[1];
3273 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3274 return Error(BitcodeError::InvalidRecord);
3276 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3277 FunctionType *FTy = nullptr;
3278 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3279 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3280 return Error(BitcodeError::InvalidRecord);
3282 SmallVector<Value*, 16> Args;
3283 // Read the fixed params.
3284 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3285 if (FTy->getParamType(i)->isLabelTy())
3286 Args.push_back(getBasicBlock(Record[OpNum]));
3288 Args.push_back(getValue(Record, OpNum, NextValueNo,
3289 FTy->getParamType(i)));
3291 return Error(BitcodeError::InvalidRecord);
3294 // Read type/value pairs for varargs params.
3295 if (!FTy->isVarArg()) {
3296 if (OpNum != Record.size())
3297 return Error(BitcodeError::InvalidRecord);
3299 while (OpNum != Record.size()) {
3301 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3302 return Error(BitcodeError::InvalidRecord);
3307 I = CallInst::Create(Callee, Args);
3308 InstructionList.push_back(I);
3309 cast<CallInst>(I)->setCallingConv(
3310 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3311 CallInst::TailCallKind TCK = CallInst::TCK_None;
3313 TCK = CallInst::TCK_Tail;
3314 if (CCInfo & (1 << 14))
3315 TCK = CallInst::TCK_MustTail;
3316 cast<CallInst>(I)->setTailCallKind(TCK);
3317 cast<CallInst>(I)->setAttributes(PAL);
3320 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3321 if (Record.size() < 3)
3322 return Error(BitcodeError::InvalidRecord);
3323 Type *OpTy = getTypeByID(Record[0]);
3324 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3325 Type *ResTy = getTypeByID(Record[2]);
3326 if (!OpTy || !Op || !ResTy)
3327 return Error(BitcodeError::InvalidRecord);
3328 I = new VAArgInst(Op, ResTy);
3329 InstructionList.push_back(I);
3334 // Add instruction to end of current BB. If there is no current BB, reject
3338 return Error(BitcodeError::InvalidInstructionWithNoBB);
3340 CurBB->getInstList().push_back(I);
3342 // If this was a terminator instruction, move to the next block.
3343 if (isa<TerminatorInst>(I)) {
3345 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3348 // Non-void values get registered in the value table for future use.
3349 if (I && !I->getType()->isVoidTy())
3350 ValueList.AssignValue(I, NextValueNo++);
3355 // Check the function list for unresolved values.
3356 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3357 if (!A->getParent()) {
3358 // We found at least one unresolved value. Nuke them all to avoid leaks.
3359 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3360 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3361 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3365 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3369 // FIXME: Check for unresolved forward-declared metadata references
3370 // and clean up leaks.
3372 // Trim the value list down to the size it was before we parsed this function.
3373 ValueList.shrinkTo(ModuleValueListSize);
3374 MDValueList.shrinkTo(ModuleMDValueListSize);
3375 std::vector<BasicBlock*>().swap(FunctionBBs);
3376 return std::error_code();
3379 /// Find the function body in the bitcode stream
3380 std::error_code BitcodeReader::FindFunctionInStream(
3382 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3383 while (DeferredFunctionInfoIterator->second == 0) {
3384 if (Stream.AtEndOfStream())
3385 return Error(BitcodeError::CouldNotFindFunctionInStream);
3386 // ParseModule will parse the next body in the stream and set its
3387 // position in the DeferredFunctionInfo map.
3388 if (std::error_code EC = ParseModule(true))
3391 return std::error_code();
3394 //===----------------------------------------------------------------------===//
3395 // GVMaterializer implementation
3396 //===----------------------------------------------------------------------===//
3398 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3400 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3401 Function *F = dyn_cast<Function>(GV);
3402 // If it's not a function or is already material, ignore the request.
3403 if (!F || !F->isMaterializable())
3404 return std::error_code();
3406 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3407 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3408 // If its position is recorded as 0, its body is somewhere in the stream
3409 // but we haven't seen it yet.
3410 if (DFII->second == 0 && LazyStreamer)
3411 if (std::error_code EC = FindFunctionInStream(F, DFII))
3414 // Move the bit stream to the saved position of the deferred function body.
3415 Stream.JumpToBit(DFII->second);
3417 if (std::error_code EC = ParseFunctionBody(F))
3419 F->setIsMaterializable(false);
3421 // Upgrade any old intrinsic calls in the function.
3422 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3423 E = UpgradedIntrinsics.end(); I != E; ++I) {
3424 if (I->first != I->second) {
3425 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3427 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3428 UpgradeIntrinsicCall(CI, I->second);
3433 // Bring in any functions that this function forward-referenced via
3435 return materializeForwardReferencedFunctions();
3438 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3439 const Function *F = dyn_cast<Function>(GV);
3440 if (!F || F->isDeclaration())
3443 // Dematerializing F would leave dangling references that wouldn't be
3444 // reconnected on re-materialization.
3445 if (BlockAddressesTaken.count(F))
3448 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3451 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3452 Function *F = dyn_cast<Function>(GV);
3453 // If this function isn't dematerializable, this is a noop.
3454 if (!F || !isDematerializable(F))
3457 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3459 // Just forget the function body, we can remat it later.
3460 F->dropAllReferences();
3461 F->setIsMaterializable(true);
3464 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3465 assert(M == TheModule &&
3466 "Can only Materialize the Module this BitcodeReader is attached to.");
3468 // Promise to materialize all forward references.
3469 WillMaterializeAllForwardRefs = true;
3471 // Iterate over the module, deserializing any functions that are still on
3473 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3475 if (std::error_code EC = materialize(F))
3478 // At this point, if there are any function bodies, the current bit is
3479 // pointing to the END_BLOCK record after them. Now make sure the rest
3480 // of the bits in the module have been read.
3484 // Check that all block address forward references got resolved (as we
3486 if (!BasicBlockFwdRefs.empty())
3487 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3489 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3490 // delete the old functions to clean up. We can't do this unless the entire
3491 // module is materialized because there could always be another function body
3492 // with calls to the old function.
3493 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3494 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3495 if (I->first != I->second) {
3496 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3498 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3499 UpgradeIntrinsicCall(CI, I->second);
3501 if (!I->first->use_empty())
3502 I->first->replaceAllUsesWith(I->second);
3503 I->first->eraseFromParent();
3506 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3508 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3509 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3511 UpgradeDebugInfo(*M);
3512 return std::error_code();
3515 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3516 return IdentifiedStructTypes;
3519 std::error_code BitcodeReader::InitStream() {
3521 return InitLazyStream();
3522 return InitStreamFromBuffer();
3525 std::error_code BitcodeReader::InitStreamFromBuffer() {
3526 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3527 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3529 if (Buffer->getBufferSize() & 3)
3530 return Error(BitcodeError::InvalidBitcodeSignature);
3532 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3533 // The magic number is 0x0B17C0DE stored in little endian.
3534 if (isBitcodeWrapper(BufPtr, BufEnd))
3535 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3536 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3538 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3539 Stream.init(&*StreamFile);
3541 return std::error_code();
3544 std::error_code BitcodeReader::InitLazyStream() {
3545 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3547 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3548 StreamingMemoryObject &Bytes = *OwnedBytes;
3549 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3550 Stream.init(&*StreamFile);
3552 unsigned char buf[16];
3553 if (Bytes.readBytes(buf, 16, 0) != 16)
3554 return Error(BitcodeError::InvalidBitcodeSignature);
3556 if (!isBitcode(buf, buf + 16))
3557 return Error(BitcodeError::InvalidBitcodeSignature);
3559 if (isBitcodeWrapper(buf, buf + 4)) {
3560 const unsigned char *bitcodeStart = buf;
3561 const unsigned char *bitcodeEnd = buf + 16;
3562 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3563 Bytes.dropLeadingBytes(bitcodeStart - buf);
3564 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3566 return std::error_code();
3570 class BitcodeErrorCategoryType : public std::error_category {
3571 const char *name() const LLVM_NOEXCEPT override {
3572 return "llvm.bitcode";
3574 std::string message(int IE) const override {
3575 BitcodeError E = static_cast<BitcodeError>(IE);
3577 case BitcodeError::ConflictingMETADATA_KINDRecords:
3578 return "Conflicting METADATA_KIND records";
3579 case BitcodeError::CouldNotFindFunctionInStream:
3580 return "Could not find function in stream";
3581 case BitcodeError::ExpectedConstant:
3582 return "Expected a constant";
3583 case BitcodeError::InsufficientFunctionProtos:
3584 return "Insufficient function protos";
3585 case BitcodeError::InvalidBitcodeSignature:
3586 return "Invalid bitcode signature";
3587 case BitcodeError::InvalidBitcodeWrapperHeader:
3588 return "Invalid bitcode wrapper header";
3589 case BitcodeError::InvalidConstantReference:
3590 return "Invalid ronstant reference";
3591 case BitcodeError::InvalidID:
3592 return "Invalid ID";
3593 case BitcodeError::InvalidInstructionWithNoBB:
3594 return "Invalid instruction with no BB";
3595 case BitcodeError::InvalidRecord:
3596 return "Invalid record";
3597 case BitcodeError::InvalidTypeForValue:
3598 return "Invalid type for value";
3599 case BitcodeError::InvalidTYPETable:
3600 return "Invalid TYPE table";
3601 case BitcodeError::InvalidType:
3602 return "Invalid type";
3603 case BitcodeError::MalformedBlock:
3604 return "Malformed block";
3605 case BitcodeError::MalformedGlobalInitializerSet:
3606 return "Malformed global initializer set";
3607 case BitcodeError::InvalidMultipleBlocks:
3608 return "Invalid multiple blocks";
3609 case BitcodeError::NeverResolvedValueFoundInFunction:
3610 return "Never resolved value found in function";
3611 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3612 return "Never resolved function from blockaddress";
3613 case BitcodeError::InvalidValue:
3614 return "Invalid value";
3616 llvm_unreachable("Unknown error type!");
3621 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3623 const std::error_category &llvm::BitcodeErrorCategory() {
3624 return *ErrorCategory;
3627 //===----------------------------------------------------------------------===//
3628 // External interface
3629 //===----------------------------------------------------------------------===//
3631 /// \brief Get a lazy one-at-time loading module from bitcode.
3633 /// This isn't always used in a lazy context. In particular, it's also used by
3634 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3635 /// in forward-referenced functions from block address references.
3637 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3638 /// materialize everything -- in particular, if this isn't truly lazy.
3639 static ErrorOr<Module *>
3640 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3641 LLVMContext &Context, bool WillMaterializeAll) {
3642 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3643 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3644 M->setMaterializer(R);
3646 auto cleanupOnError = [&](std::error_code EC) {
3647 R->releaseBuffer(); // Never take ownership on error.
3648 delete M; // Also deletes R.
3652 if (std::error_code EC = R->ParseBitcodeInto(M))
3653 return cleanupOnError(EC);
3655 if (!WillMaterializeAll)
3656 // Resolve forward references from blockaddresses.
3657 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3658 return cleanupOnError(EC);
3660 Buffer.release(); // The BitcodeReader owns it now.
3665 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3666 LLVMContext &Context) {
3667 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3670 ErrorOr<std::unique_ptr<Module>>
3671 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3672 LLVMContext &Context) {
3673 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3674 BitcodeReader *R = new BitcodeReader(Streamer, Context);
3675 M->setMaterializer(R);
3676 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3678 return std::move(M);
3681 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3682 LLVMContext &Context) {
3683 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3684 ErrorOr<Module *> ModuleOrErr =
3685 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3688 Module *M = ModuleOrErr.get();
3689 // Read in the entire module, and destroy the BitcodeReader.
3690 if (std::error_code EC = M->materializeAllPermanently()) {
3695 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3696 // written. We must defer until the Module has been fully materialized.
3701 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3702 LLVMContext &Context) {
3703 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3704 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3705 ErrorOr<std::string> Triple = R->parseTriple();
3706 if (Triple.getError())
3708 return Triple.get();