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
106 case 0: return GlobalValue::ExternalLinkage;
107 case 1: return GlobalValue::WeakAnyLinkage;
108 case 2: return GlobalValue::AppendingLinkage;
109 case 3: return GlobalValue::InternalLinkage;
110 case 4: return GlobalValue::LinkOnceAnyLinkage;
111 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
112 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
113 case 7: return GlobalValue::ExternalWeakLinkage;
114 case 8: return GlobalValue::CommonLinkage;
115 case 9: return GlobalValue::PrivateLinkage;
116 case 10: return GlobalValue::WeakODRLinkage;
117 case 11: return GlobalValue::LinkOnceODRLinkage;
118 case 12: return GlobalValue::AvailableExternallyLinkage;
120 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
122 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
126 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
128 default: // Map unknown visibilities to default.
129 case 0: return GlobalValue::DefaultVisibility;
130 case 1: return GlobalValue::HiddenVisibility;
131 case 2: return GlobalValue::ProtectedVisibility;
135 static GlobalValue::DLLStorageClassTypes
136 GetDecodedDLLStorageClass(unsigned Val) {
138 default: // Map unknown values to default.
139 case 0: return GlobalValue::DefaultStorageClass;
140 case 1: return GlobalValue::DLLImportStorageClass;
141 case 2: return GlobalValue::DLLExportStorageClass;
145 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
147 case 0: return GlobalVariable::NotThreadLocal;
148 default: // Map unknown non-zero value to general dynamic.
149 case 1: return GlobalVariable::GeneralDynamicTLSModel;
150 case 2: return GlobalVariable::LocalDynamicTLSModel;
151 case 3: return GlobalVariable::InitialExecTLSModel;
152 case 4: return GlobalVariable::LocalExecTLSModel;
156 static int GetDecodedCastOpcode(unsigned Val) {
159 case bitc::CAST_TRUNC : return Instruction::Trunc;
160 case bitc::CAST_ZEXT : return Instruction::ZExt;
161 case bitc::CAST_SEXT : return Instruction::SExt;
162 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
163 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
164 case bitc::CAST_UITOFP : return Instruction::UIToFP;
165 case bitc::CAST_SITOFP : return Instruction::SIToFP;
166 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
167 case bitc::CAST_FPEXT : return Instruction::FPExt;
168 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
169 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
170 case bitc::CAST_BITCAST : return Instruction::BitCast;
171 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
174 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
177 case bitc::BINOP_ADD:
178 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
179 case bitc::BINOP_SUB:
180 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
181 case bitc::BINOP_MUL:
182 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
183 case bitc::BINOP_UDIV: return Instruction::UDiv;
184 case bitc::BINOP_SDIV:
185 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
186 case bitc::BINOP_UREM: return Instruction::URem;
187 case bitc::BINOP_SREM:
188 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
189 case bitc::BINOP_SHL: return Instruction::Shl;
190 case bitc::BINOP_LSHR: return Instruction::LShr;
191 case bitc::BINOP_ASHR: return Instruction::AShr;
192 case bitc::BINOP_AND: return Instruction::And;
193 case bitc::BINOP_OR: return Instruction::Or;
194 case bitc::BINOP_XOR: return Instruction::Xor;
198 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
200 default: return AtomicRMWInst::BAD_BINOP;
201 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
202 case bitc::RMW_ADD: return AtomicRMWInst::Add;
203 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
204 case bitc::RMW_AND: return AtomicRMWInst::And;
205 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
206 case bitc::RMW_OR: return AtomicRMWInst::Or;
207 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
208 case bitc::RMW_MAX: return AtomicRMWInst::Max;
209 case bitc::RMW_MIN: return AtomicRMWInst::Min;
210 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
211 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
215 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
217 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
218 case bitc::ORDERING_UNORDERED: return Unordered;
219 case bitc::ORDERING_MONOTONIC: return Monotonic;
220 case bitc::ORDERING_ACQUIRE: return Acquire;
221 case bitc::ORDERING_RELEASE: return Release;
222 case bitc::ORDERING_ACQREL: return AcquireRelease;
223 default: // Map unknown orderings to sequentially-consistent.
224 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
228 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
230 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
231 default: // Map unknown scopes to cross-thread.
232 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
236 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
238 default: // Map unknown selection kinds to any.
239 case bitc::COMDAT_SELECTION_KIND_ANY:
241 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
242 return Comdat::ExactMatch;
243 case bitc::COMDAT_SELECTION_KIND_LARGEST:
244 return Comdat::Largest;
245 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
246 return Comdat::NoDuplicates;
247 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
248 return Comdat::SameSize;
252 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
254 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
255 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
261 /// @brief A class for maintaining the slot number definition
262 /// as a placeholder for the actual definition for forward constants defs.
263 class ConstantPlaceHolder : public ConstantExpr {
264 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
266 // allocate space for exactly one operand
267 void *operator new(size_t s) {
268 return User::operator new(s, 1);
270 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
271 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
272 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
275 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
276 static bool classof(const Value *V) {
277 return isa<ConstantExpr>(V) &&
278 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
282 /// Provide fast operand accessors
283 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
287 // FIXME: can we inherit this from ConstantExpr?
289 struct OperandTraits<ConstantPlaceHolder> :
290 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
292 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
296 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
305 WeakVH &OldV = ValuePtrs[Idx];
311 // Handle constants and non-constants (e.g. instrs) differently for
313 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
314 ResolveConstants.push_back(std::make_pair(PHC, Idx));
317 // If there was a forward reference to this value, replace it.
318 Value *PrevVal = OldV;
319 OldV->replaceAllUsesWith(V);
325 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
330 if (Value *V = ValuePtrs[Idx]) {
331 assert(Ty == V->getType() && "Type mismatch in constant table!");
332 return cast<Constant>(V);
335 // Create and return a placeholder, which will later be RAUW'd.
336 Constant *C = new ConstantPlaceHolder(Ty, Context);
341 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
345 if (Value *V = ValuePtrs[Idx]) {
346 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
350 // No type specified, must be invalid reference.
351 if (!Ty) return nullptr;
353 // Create and return a placeholder, which will later be RAUW'd.
354 Value *V = new Argument(Ty);
359 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
360 /// resolves any forward references. The idea behind this is that we sometimes
361 /// get constants (such as large arrays) which reference *many* forward ref
362 /// constants. Replacing each of these causes a lot of thrashing when
363 /// building/reuniquing the constant. Instead of doing this, we look at all the
364 /// uses and rewrite all the place holders at once for any constant that uses
366 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
367 // Sort the values by-pointer so that they are efficient to look up with a
369 std::sort(ResolveConstants.begin(), ResolveConstants.end());
371 SmallVector<Constant*, 64> NewOps;
373 while (!ResolveConstants.empty()) {
374 Value *RealVal = operator[](ResolveConstants.back().second);
375 Constant *Placeholder = ResolveConstants.back().first;
376 ResolveConstants.pop_back();
378 // Loop over all users of the placeholder, updating them to reference the
379 // new value. If they reference more than one placeholder, update them all
381 while (!Placeholder->use_empty()) {
382 auto UI = Placeholder->user_begin();
385 // If the using object isn't uniqued, just update the operands. This
386 // handles instructions and initializers for global variables.
387 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
388 UI.getUse().set(RealVal);
392 // Otherwise, we have a constant that uses the placeholder. Replace that
393 // constant with a new constant that has *all* placeholder uses updated.
394 Constant *UserC = cast<Constant>(U);
395 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
398 if (!isa<ConstantPlaceHolder>(*I)) {
399 // Not a placeholder reference.
401 } else if (*I == Placeholder) {
402 // Common case is that it just references this one placeholder.
405 // Otherwise, look up the placeholder in ResolveConstants.
406 ResolveConstantsTy::iterator It =
407 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
408 std::pair<Constant*, unsigned>(cast<Constant>(*I),
410 assert(It != ResolveConstants.end() && It->first == *I);
411 NewOp = operator[](It->second);
414 NewOps.push_back(cast<Constant>(NewOp));
417 // Make the new constant.
419 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
420 NewC = ConstantArray::get(UserCA->getType(), NewOps);
421 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
422 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
423 } else if (isa<ConstantVector>(UserC)) {
424 NewC = ConstantVector::get(NewOps);
426 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
427 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
430 UserC->replaceAllUsesWith(NewC);
431 UserC->destroyConstant();
435 // Update all ValueHandles, they should be the only users at this point.
436 Placeholder->replaceAllUsesWith(RealVal);
441 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
450 TrackingMDRef &OldMD = MDValuePtrs[Idx];
456 // If there was a forward reference to this value, replace it.
457 MDNodeFwdDecl *PrevMD = cast<MDNodeFwdDecl>(OldMD.get());
458 PrevMD->replaceAllUsesWith(MD);
459 MDNode::deleteTemporary(PrevMD);
463 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
467 if (Metadata *MD = MDValuePtrs[Idx])
470 // Create and return a placeholder, which will later be RAUW'd.
473 Metadata *MD = MDNode::getTemporary(Context, None);
474 MDValuePtrs[Idx].reset(MD);
478 void BitcodeReaderMDValueList::tryToResolveCycles() {
484 // Still forward references... can't resolve cycles.
487 // Resolve any cycles.
488 for (auto &MD : MDValuePtrs) {
489 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Unexpected forward reference");
490 if (auto *G = dyn_cast_or_null<GenericMDNode>(MD))
495 Type *BitcodeReader::getTypeByID(unsigned ID) {
496 // The type table size is always specified correctly.
497 if (ID >= TypeList.size())
500 if (Type *Ty = TypeList[ID])
503 // If we have a forward reference, the only possible case is when it is to a
504 // named struct. Just create a placeholder for now.
505 return TypeList[ID] = createIdentifiedStructType(Context);
508 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
510 auto *Ret = StructType::create(Context, Name);
511 IdentifiedStructTypes.push_back(Ret);
515 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
516 auto *Ret = StructType::create(Context);
517 IdentifiedStructTypes.push_back(Ret);
522 //===----------------------------------------------------------------------===//
523 // Functions for parsing blocks from the bitcode file
524 //===----------------------------------------------------------------------===//
527 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
528 /// been decoded from the given integer. This function must stay in sync with
529 /// 'encodeLLVMAttributesForBitcode'.
530 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
531 uint64_t EncodedAttrs) {
532 // FIXME: Remove in 4.0.
534 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
535 // the bits above 31 down by 11 bits.
536 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
537 assert((!Alignment || isPowerOf2_32(Alignment)) &&
538 "Alignment must be a power of two.");
541 B.addAlignmentAttr(Alignment);
542 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
543 (EncodedAttrs & 0xffff));
546 std::error_code BitcodeReader::ParseAttributeBlock() {
547 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
548 return Error(BitcodeError::InvalidRecord);
550 if (!MAttributes.empty())
551 return Error(BitcodeError::InvalidMultipleBlocks);
553 SmallVector<uint64_t, 64> Record;
555 SmallVector<AttributeSet, 8> Attrs;
557 // Read all the records.
559 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
561 switch (Entry.Kind) {
562 case BitstreamEntry::SubBlock: // Handled for us already.
563 case BitstreamEntry::Error:
564 return Error(BitcodeError::MalformedBlock);
565 case BitstreamEntry::EndBlock:
566 return std::error_code();
567 case BitstreamEntry::Record:
568 // The interesting case.
574 switch (Stream.readRecord(Entry.ID, Record)) {
575 default: // Default behavior: ignore.
577 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
578 // FIXME: Remove in 4.0.
579 if (Record.size() & 1)
580 return Error(BitcodeError::InvalidRecord);
582 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
584 decodeLLVMAttributesForBitcode(B, Record[i+1]);
585 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
588 MAttributes.push_back(AttributeSet::get(Context, Attrs));
592 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
593 for (unsigned i = 0, e = Record.size(); i != e; ++i)
594 Attrs.push_back(MAttributeGroups[Record[i]]);
596 MAttributes.push_back(AttributeSet::get(Context, Attrs));
604 // Returns Attribute::None on unrecognized codes.
605 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
608 return Attribute::None;
609 case bitc::ATTR_KIND_ALIGNMENT:
610 return Attribute::Alignment;
611 case bitc::ATTR_KIND_ALWAYS_INLINE:
612 return Attribute::AlwaysInline;
613 case bitc::ATTR_KIND_BUILTIN:
614 return Attribute::Builtin;
615 case bitc::ATTR_KIND_BY_VAL:
616 return Attribute::ByVal;
617 case bitc::ATTR_KIND_IN_ALLOCA:
618 return Attribute::InAlloca;
619 case bitc::ATTR_KIND_COLD:
620 return Attribute::Cold;
621 case bitc::ATTR_KIND_INLINE_HINT:
622 return Attribute::InlineHint;
623 case bitc::ATTR_KIND_IN_REG:
624 return Attribute::InReg;
625 case bitc::ATTR_KIND_JUMP_TABLE:
626 return Attribute::JumpTable;
627 case bitc::ATTR_KIND_MIN_SIZE:
628 return Attribute::MinSize;
629 case bitc::ATTR_KIND_NAKED:
630 return Attribute::Naked;
631 case bitc::ATTR_KIND_NEST:
632 return Attribute::Nest;
633 case bitc::ATTR_KIND_NO_ALIAS:
634 return Attribute::NoAlias;
635 case bitc::ATTR_KIND_NO_BUILTIN:
636 return Attribute::NoBuiltin;
637 case bitc::ATTR_KIND_NO_CAPTURE:
638 return Attribute::NoCapture;
639 case bitc::ATTR_KIND_NO_DUPLICATE:
640 return Attribute::NoDuplicate;
641 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
642 return Attribute::NoImplicitFloat;
643 case bitc::ATTR_KIND_NO_INLINE:
644 return Attribute::NoInline;
645 case bitc::ATTR_KIND_NON_LAZY_BIND:
646 return Attribute::NonLazyBind;
647 case bitc::ATTR_KIND_NON_NULL:
648 return Attribute::NonNull;
649 case bitc::ATTR_KIND_DEREFERENCEABLE:
650 return Attribute::Dereferenceable;
651 case bitc::ATTR_KIND_NO_RED_ZONE:
652 return Attribute::NoRedZone;
653 case bitc::ATTR_KIND_NO_RETURN:
654 return Attribute::NoReturn;
655 case bitc::ATTR_KIND_NO_UNWIND:
656 return Attribute::NoUnwind;
657 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
658 return Attribute::OptimizeForSize;
659 case bitc::ATTR_KIND_OPTIMIZE_NONE:
660 return Attribute::OptimizeNone;
661 case bitc::ATTR_KIND_READ_NONE:
662 return Attribute::ReadNone;
663 case bitc::ATTR_KIND_READ_ONLY:
664 return Attribute::ReadOnly;
665 case bitc::ATTR_KIND_RETURNED:
666 return Attribute::Returned;
667 case bitc::ATTR_KIND_RETURNS_TWICE:
668 return Attribute::ReturnsTwice;
669 case bitc::ATTR_KIND_S_EXT:
670 return Attribute::SExt;
671 case bitc::ATTR_KIND_STACK_ALIGNMENT:
672 return Attribute::StackAlignment;
673 case bitc::ATTR_KIND_STACK_PROTECT:
674 return Attribute::StackProtect;
675 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
676 return Attribute::StackProtectReq;
677 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
678 return Attribute::StackProtectStrong;
679 case bitc::ATTR_KIND_STRUCT_RET:
680 return Attribute::StructRet;
681 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
682 return Attribute::SanitizeAddress;
683 case bitc::ATTR_KIND_SANITIZE_THREAD:
684 return Attribute::SanitizeThread;
685 case bitc::ATTR_KIND_SANITIZE_MEMORY:
686 return Attribute::SanitizeMemory;
687 case bitc::ATTR_KIND_UW_TABLE:
688 return Attribute::UWTable;
689 case bitc::ATTR_KIND_Z_EXT:
690 return Attribute::ZExt;
694 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
695 Attribute::AttrKind *Kind) {
696 *Kind = GetAttrFromCode(Code);
697 if (*Kind == Attribute::None)
698 return Error(BitcodeError::InvalidValue);
699 return std::error_code();
702 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
703 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
704 return Error(BitcodeError::InvalidRecord);
706 if (!MAttributeGroups.empty())
707 return Error(BitcodeError::InvalidMultipleBlocks);
709 SmallVector<uint64_t, 64> Record;
711 // Read all the records.
713 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
715 switch (Entry.Kind) {
716 case BitstreamEntry::SubBlock: // Handled for us already.
717 case BitstreamEntry::Error:
718 return Error(BitcodeError::MalformedBlock);
719 case BitstreamEntry::EndBlock:
720 return std::error_code();
721 case BitstreamEntry::Record:
722 // The interesting case.
728 switch (Stream.readRecord(Entry.ID, Record)) {
729 default: // Default behavior: ignore.
731 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
732 if (Record.size() < 3)
733 return Error(BitcodeError::InvalidRecord);
735 uint64_t GrpID = Record[0];
736 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
739 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
740 if (Record[i] == 0) { // Enum attribute
741 Attribute::AttrKind Kind;
742 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
745 B.addAttribute(Kind);
746 } else if (Record[i] == 1) { // Integer attribute
747 Attribute::AttrKind Kind;
748 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
750 if (Kind == Attribute::Alignment)
751 B.addAlignmentAttr(Record[++i]);
752 else if (Kind == Attribute::StackAlignment)
753 B.addStackAlignmentAttr(Record[++i]);
754 else if (Kind == Attribute::Dereferenceable)
755 B.addDereferenceableAttr(Record[++i]);
756 } else { // String attribute
757 assert((Record[i] == 3 || Record[i] == 4) &&
758 "Invalid attribute group entry");
759 bool HasValue = (Record[i++] == 4);
760 SmallString<64> KindStr;
761 SmallString<64> ValStr;
763 while (Record[i] != 0 && i != e)
764 KindStr += Record[i++];
765 assert(Record[i] == 0 && "Kind string not null terminated");
768 // Has a value associated with it.
769 ++i; // Skip the '0' that terminates the "kind" string.
770 while (Record[i] != 0 && i != e)
771 ValStr += Record[i++];
772 assert(Record[i] == 0 && "Value string not null terminated");
775 B.addAttribute(KindStr.str(), ValStr.str());
779 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
786 std::error_code BitcodeReader::ParseTypeTable() {
787 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
788 return Error(BitcodeError::InvalidRecord);
790 return ParseTypeTableBody();
793 std::error_code BitcodeReader::ParseTypeTableBody() {
794 if (!TypeList.empty())
795 return Error(BitcodeError::InvalidMultipleBlocks);
797 SmallVector<uint64_t, 64> Record;
798 unsigned NumRecords = 0;
800 SmallString<64> TypeName;
802 // Read all the records for this type table.
804 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
806 switch (Entry.Kind) {
807 case BitstreamEntry::SubBlock: // Handled for us already.
808 case BitstreamEntry::Error:
809 return Error(BitcodeError::MalformedBlock);
810 case BitstreamEntry::EndBlock:
811 if (NumRecords != TypeList.size())
812 return Error(BitcodeError::MalformedBlock);
813 return std::error_code();
814 case BitstreamEntry::Record:
815 // The interesting case.
821 Type *ResultTy = nullptr;
822 switch (Stream.readRecord(Entry.ID, Record)) {
824 return Error(BitcodeError::InvalidValue);
825 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
826 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
827 // type list. This allows us to reserve space.
828 if (Record.size() < 1)
829 return Error(BitcodeError::InvalidRecord);
830 TypeList.resize(Record[0]);
832 case bitc::TYPE_CODE_VOID: // VOID
833 ResultTy = Type::getVoidTy(Context);
835 case bitc::TYPE_CODE_HALF: // HALF
836 ResultTy = Type::getHalfTy(Context);
838 case bitc::TYPE_CODE_FLOAT: // FLOAT
839 ResultTy = Type::getFloatTy(Context);
841 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
842 ResultTy = Type::getDoubleTy(Context);
844 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
845 ResultTy = Type::getX86_FP80Ty(Context);
847 case bitc::TYPE_CODE_FP128: // FP128
848 ResultTy = Type::getFP128Ty(Context);
850 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
851 ResultTy = Type::getPPC_FP128Ty(Context);
853 case bitc::TYPE_CODE_LABEL: // LABEL
854 ResultTy = Type::getLabelTy(Context);
856 case bitc::TYPE_CODE_METADATA: // METADATA
857 ResultTy = Type::getMetadataTy(Context);
859 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
860 ResultTy = Type::getX86_MMXTy(Context);
862 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
863 if (Record.size() < 1)
864 return Error(BitcodeError::InvalidRecord);
866 ResultTy = IntegerType::get(Context, Record[0]);
868 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
869 // [pointee type, address space]
870 if (Record.size() < 1)
871 return Error(BitcodeError::InvalidRecord);
872 unsigned AddressSpace = 0;
873 if (Record.size() == 2)
874 AddressSpace = Record[1];
875 ResultTy = getTypeByID(Record[0]);
877 return Error(BitcodeError::InvalidType);
878 ResultTy = PointerType::get(ResultTy, AddressSpace);
881 case bitc::TYPE_CODE_FUNCTION_OLD: {
882 // FIXME: attrid is dead, remove it in LLVM 4.0
883 // FUNCTION: [vararg, attrid, retty, paramty x N]
884 if (Record.size() < 3)
885 return Error(BitcodeError::InvalidRecord);
886 SmallVector<Type*, 8> ArgTys;
887 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
888 if (Type *T = getTypeByID(Record[i]))
894 ResultTy = getTypeByID(Record[2]);
895 if (!ResultTy || ArgTys.size() < Record.size()-3)
896 return Error(BitcodeError::InvalidType);
898 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
901 case bitc::TYPE_CODE_FUNCTION: {
902 // FUNCTION: [vararg, retty, paramty x N]
903 if (Record.size() < 2)
904 return Error(BitcodeError::InvalidRecord);
905 SmallVector<Type*, 8> ArgTys;
906 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
907 if (Type *T = getTypeByID(Record[i]))
913 ResultTy = getTypeByID(Record[1]);
914 if (!ResultTy || ArgTys.size() < Record.size()-2)
915 return Error(BitcodeError::InvalidType);
917 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
920 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
921 if (Record.size() < 1)
922 return Error(BitcodeError::InvalidRecord);
923 SmallVector<Type*, 8> EltTys;
924 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
925 if (Type *T = getTypeByID(Record[i]))
930 if (EltTys.size() != Record.size()-1)
931 return Error(BitcodeError::InvalidType);
932 ResultTy = StructType::get(Context, EltTys, Record[0]);
935 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
936 if (ConvertToString(Record, 0, TypeName))
937 return Error(BitcodeError::InvalidRecord);
940 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
941 if (Record.size() < 1)
942 return Error(BitcodeError::InvalidRecord);
944 if (NumRecords >= TypeList.size())
945 return Error(BitcodeError::InvalidTYPETable);
947 // Check to see if this was forward referenced, if so fill in the temp.
948 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
950 Res->setName(TypeName);
951 TypeList[NumRecords] = nullptr;
952 } else // Otherwise, create a new struct.
953 Res = createIdentifiedStructType(Context, TypeName);
956 SmallVector<Type*, 8> EltTys;
957 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
958 if (Type *T = getTypeByID(Record[i]))
963 if (EltTys.size() != Record.size()-1)
964 return Error(BitcodeError::InvalidRecord);
965 Res->setBody(EltTys, Record[0]);
969 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
970 if (Record.size() != 1)
971 return Error(BitcodeError::InvalidRecord);
973 if (NumRecords >= TypeList.size())
974 return Error(BitcodeError::InvalidTYPETable);
976 // Check to see if this was forward referenced, if so fill in the temp.
977 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
979 Res->setName(TypeName);
980 TypeList[NumRecords] = nullptr;
981 } else // Otherwise, create a new struct with no body.
982 Res = createIdentifiedStructType(Context, TypeName);
987 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
988 if (Record.size() < 2)
989 return Error(BitcodeError::InvalidRecord);
990 if ((ResultTy = getTypeByID(Record[1])))
991 ResultTy = ArrayType::get(ResultTy, Record[0]);
993 return Error(BitcodeError::InvalidType);
995 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
996 if (Record.size() < 2)
997 return Error(BitcodeError::InvalidRecord);
998 if ((ResultTy = getTypeByID(Record[1])))
999 ResultTy = VectorType::get(ResultTy, Record[0]);
1001 return Error(BitcodeError::InvalidType);
1005 if (NumRecords >= TypeList.size())
1006 return Error(BitcodeError::InvalidTYPETable);
1007 assert(ResultTy && "Didn't read a type?");
1008 assert(!TypeList[NumRecords] && "Already read type?");
1009 TypeList[NumRecords++] = ResultTy;
1013 std::error_code BitcodeReader::ParseValueSymbolTable() {
1014 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1015 return Error(BitcodeError::InvalidRecord);
1017 SmallVector<uint64_t, 64> Record;
1019 // Read all the records for this value table.
1020 SmallString<128> ValueName;
1022 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1024 switch (Entry.Kind) {
1025 case BitstreamEntry::SubBlock: // Handled for us already.
1026 case BitstreamEntry::Error:
1027 return Error(BitcodeError::MalformedBlock);
1028 case BitstreamEntry::EndBlock:
1029 return std::error_code();
1030 case BitstreamEntry::Record:
1031 // The interesting case.
1037 switch (Stream.readRecord(Entry.ID, Record)) {
1038 default: // Default behavior: unknown type.
1040 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1041 if (ConvertToString(Record, 1, ValueName))
1042 return Error(BitcodeError::InvalidRecord);
1043 unsigned ValueID = Record[0];
1044 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1045 return Error(BitcodeError::InvalidRecord);
1046 Value *V = ValueList[ValueID];
1048 V->setName(StringRef(ValueName.data(), ValueName.size()));
1052 case bitc::VST_CODE_BBENTRY: {
1053 if (ConvertToString(Record, 1, ValueName))
1054 return Error(BitcodeError::InvalidRecord);
1055 BasicBlock *BB = getBasicBlock(Record[0]);
1057 return Error(BitcodeError::InvalidRecord);
1059 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1067 std::error_code BitcodeReader::ParseMetadata() {
1068 unsigned NextMDValueNo = MDValueList.size();
1070 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1071 return Error(BitcodeError::InvalidRecord);
1073 SmallVector<uint64_t, 64> Record;
1075 // Read all the records.
1077 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1079 switch (Entry.Kind) {
1080 case BitstreamEntry::SubBlock: // Handled for us already.
1081 case BitstreamEntry::Error:
1082 return Error(BitcodeError::MalformedBlock);
1083 case BitstreamEntry::EndBlock:
1084 MDValueList.tryToResolveCycles();
1085 return std::error_code();
1086 case BitstreamEntry::Record:
1087 // The interesting case.
1093 unsigned Code = Stream.readRecord(Entry.ID, Record);
1095 default: // Default behavior: ignore.
1097 case bitc::METADATA_NAME: {
1098 // Read name of the named metadata.
1099 SmallString<8> Name(Record.begin(), Record.end());
1101 Code = Stream.ReadCode();
1103 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1104 unsigned NextBitCode = Stream.readRecord(Code, Record);
1105 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1107 // Read named metadata elements.
1108 unsigned Size = Record.size();
1109 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1110 for (unsigned i = 0; i != Size; ++i) {
1111 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1113 return Error(BitcodeError::InvalidRecord);
1114 NMD->addOperand(MD);
1118 case bitc::METADATA_OLD_FN_NODE: {
1119 // This is a LocalAsMetadata record, the only type of function-local
1121 if (Record.size() % 2 == 1)
1122 return Error(BitcodeError::InvalidRecord);
1124 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1125 // to be legal, but there's no upgrade path.
1126 auto dropRecord = [&] {
1127 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1129 if (Record.size() != 2) {
1134 Type *Ty = getTypeByID(Record[0]);
1135 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1140 MDValueList.AssignValue(
1141 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1145 case bitc::METADATA_OLD_NODE: {
1146 if (Record.size() % 2 == 1)
1147 return Error(BitcodeError::InvalidRecord);
1149 unsigned Size = Record.size();
1150 SmallVector<Metadata *, 8> Elts;
1151 for (unsigned i = 0; i != Size; i += 2) {
1152 Type *Ty = getTypeByID(Record[i]);
1154 return Error(BitcodeError::InvalidRecord);
1155 if (Ty->isMetadataTy())
1156 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1157 else if (!Ty->isVoidTy()) {
1159 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1160 assert(isa<ConstantAsMetadata>(MD) &&
1161 "Expected non-function-local metadata");
1164 Elts.push_back(nullptr);
1166 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1169 case bitc::METADATA_VALUE: {
1170 if (Record.size() != 2)
1171 return Error(BitcodeError::InvalidRecord);
1173 Type *Ty = getTypeByID(Record[0]);
1174 if (Ty->isMetadataTy() || Ty->isVoidTy())
1175 return Error(BitcodeError::InvalidRecord);
1177 MDValueList.AssignValue(
1178 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1182 case bitc::METADATA_NODE: {
1183 SmallVector<Metadata *, 8> Elts;
1184 Elts.reserve(Record.size());
1185 for (unsigned ID : Record)
1186 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1187 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1190 case bitc::METADATA_STRING: {
1191 std::string String(Record.begin(), Record.end());
1192 llvm::UpgradeMDStringConstant(String);
1193 Metadata *MD = MDString::get(Context, String);
1194 MDValueList.AssignValue(MD, NextMDValueNo++);
1197 case bitc::METADATA_KIND: {
1198 if (Record.size() < 2)
1199 return Error(BitcodeError::InvalidRecord);
1201 unsigned Kind = Record[0];
1202 SmallString<8> Name(Record.begin()+1, Record.end());
1204 unsigned NewKind = TheModule->getMDKindID(Name.str());
1205 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1206 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1213 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1214 /// the LSB for dense VBR encoding.
1215 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1220 // There is no such thing as -0 with integers. "-0" really means MININT.
1224 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1225 /// values and aliases that we can.
1226 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1227 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1228 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1229 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1230 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1232 GlobalInitWorklist.swap(GlobalInits);
1233 AliasInitWorklist.swap(AliasInits);
1234 FunctionPrefixWorklist.swap(FunctionPrefixes);
1235 FunctionPrologueWorklist.swap(FunctionPrologues);
1237 while (!GlobalInitWorklist.empty()) {
1238 unsigned ValID = GlobalInitWorklist.back().second;
1239 if (ValID >= ValueList.size()) {
1240 // Not ready to resolve this yet, it requires something later in the file.
1241 GlobalInits.push_back(GlobalInitWorklist.back());
1243 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1244 GlobalInitWorklist.back().first->setInitializer(C);
1246 return Error(BitcodeError::ExpectedConstant);
1248 GlobalInitWorklist.pop_back();
1251 while (!AliasInitWorklist.empty()) {
1252 unsigned ValID = AliasInitWorklist.back().second;
1253 if (ValID >= ValueList.size()) {
1254 AliasInits.push_back(AliasInitWorklist.back());
1256 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1257 AliasInitWorklist.back().first->setAliasee(C);
1259 return Error(BitcodeError::ExpectedConstant);
1261 AliasInitWorklist.pop_back();
1264 while (!FunctionPrefixWorklist.empty()) {
1265 unsigned ValID = FunctionPrefixWorklist.back().second;
1266 if (ValID >= ValueList.size()) {
1267 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1269 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1270 FunctionPrefixWorklist.back().first->setPrefixData(C);
1272 return Error(BitcodeError::ExpectedConstant);
1274 FunctionPrefixWorklist.pop_back();
1277 while (!FunctionPrologueWorklist.empty()) {
1278 unsigned ValID = FunctionPrologueWorklist.back().second;
1279 if (ValID >= ValueList.size()) {
1280 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1282 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1283 FunctionPrologueWorklist.back().first->setPrologueData(C);
1285 return Error(BitcodeError::ExpectedConstant);
1287 FunctionPrologueWorklist.pop_back();
1290 return std::error_code();
1293 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1294 SmallVector<uint64_t, 8> Words(Vals.size());
1295 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1296 BitcodeReader::decodeSignRotatedValue);
1298 return APInt(TypeBits, Words);
1301 std::error_code BitcodeReader::ParseConstants() {
1302 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1303 return Error(BitcodeError::InvalidRecord);
1305 SmallVector<uint64_t, 64> Record;
1307 // Read all the records for this value table.
1308 Type *CurTy = Type::getInt32Ty(Context);
1309 unsigned NextCstNo = ValueList.size();
1311 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1313 switch (Entry.Kind) {
1314 case BitstreamEntry::SubBlock: // Handled for us already.
1315 case BitstreamEntry::Error:
1316 return Error(BitcodeError::MalformedBlock);
1317 case BitstreamEntry::EndBlock:
1318 if (NextCstNo != ValueList.size())
1319 return Error(BitcodeError::InvalidConstantReference);
1321 // Once all the constants have been read, go through and resolve forward
1323 ValueList.ResolveConstantForwardRefs();
1324 return std::error_code();
1325 case BitstreamEntry::Record:
1326 // The interesting case.
1333 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1335 default: // Default behavior: unknown constant
1336 case bitc::CST_CODE_UNDEF: // UNDEF
1337 V = UndefValue::get(CurTy);
1339 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1341 return Error(BitcodeError::InvalidRecord);
1342 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1343 return Error(BitcodeError::InvalidRecord);
1344 CurTy = TypeList[Record[0]];
1345 continue; // Skip the ValueList manipulation.
1346 case bitc::CST_CODE_NULL: // NULL
1347 V = Constant::getNullValue(CurTy);
1349 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1350 if (!CurTy->isIntegerTy() || Record.empty())
1351 return Error(BitcodeError::InvalidRecord);
1352 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1354 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1355 if (!CurTy->isIntegerTy() || Record.empty())
1356 return Error(BitcodeError::InvalidRecord);
1358 APInt VInt = ReadWideAPInt(Record,
1359 cast<IntegerType>(CurTy)->getBitWidth());
1360 V = ConstantInt::get(Context, VInt);
1364 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1366 return Error(BitcodeError::InvalidRecord);
1367 if (CurTy->isHalfTy())
1368 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1369 APInt(16, (uint16_t)Record[0])));
1370 else if (CurTy->isFloatTy())
1371 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1372 APInt(32, (uint32_t)Record[0])));
1373 else if (CurTy->isDoubleTy())
1374 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1375 APInt(64, Record[0])));
1376 else if (CurTy->isX86_FP80Ty()) {
1377 // Bits are not stored the same way as a normal i80 APInt, compensate.
1378 uint64_t Rearrange[2];
1379 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1380 Rearrange[1] = Record[0] >> 48;
1381 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1382 APInt(80, Rearrange)));
1383 } else if (CurTy->isFP128Ty())
1384 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1385 APInt(128, Record)));
1386 else if (CurTy->isPPC_FP128Ty())
1387 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1388 APInt(128, Record)));
1390 V = UndefValue::get(CurTy);
1394 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1396 return Error(BitcodeError::InvalidRecord);
1398 unsigned Size = Record.size();
1399 SmallVector<Constant*, 16> Elts;
1401 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1402 for (unsigned i = 0; i != Size; ++i)
1403 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1404 STy->getElementType(i)));
1405 V = ConstantStruct::get(STy, Elts);
1406 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1407 Type *EltTy = ATy->getElementType();
1408 for (unsigned i = 0; i != Size; ++i)
1409 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1410 V = ConstantArray::get(ATy, Elts);
1411 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1412 Type *EltTy = VTy->getElementType();
1413 for (unsigned i = 0; i != Size; ++i)
1414 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1415 V = ConstantVector::get(Elts);
1417 V = UndefValue::get(CurTy);
1421 case bitc::CST_CODE_STRING: // STRING: [values]
1422 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1424 return Error(BitcodeError::InvalidRecord);
1426 SmallString<16> Elts(Record.begin(), Record.end());
1427 V = ConstantDataArray::getString(Context, Elts,
1428 BitCode == bitc::CST_CODE_CSTRING);
1431 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1433 return Error(BitcodeError::InvalidRecord);
1435 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1436 unsigned Size = Record.size();
1438 if (EltTy->isIntegerTy(8)) {
1439 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1440 if (isa<VectorType>(CurTy))
1441 V = ConstantDataVector::get(Context, Elts);
1443 V = ConstantDataArray::get(Context, Elts);
1444 } else if (EltTy->isIntegerTy(16)) {
1445 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1446 if (isa<VectorType>(CurTy))
1447 V = ConstantDataVector::get(Context, Elts);
1449 V = ConstantDataArray::get(Context, Elts);
1450 } else if (EltTy->isIntegerTy(32)) {
1451 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1452 if (isa<VectorType>(CurTy))
1453 V = ConstantDataVector::get(Context, Elts);
1455 V = ConstantDataArray::get(Context, Elts);
1456 } else if (EltTy->isIntegerTy(64)) {
1457 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1458 if (isa<VectorType>(CurTy))
1459 V = ConstantDataVector::get(Context, Elts);
1461 V = ConstantDataArray::get(Context, Elts);
1462 } else if (EltTy->isFloatTy()) {
1463 SmallVector<float, 16> Elts(Size);
1464 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1465 if (isa<VectorType>(CurTy))
1466 V = ConstantDataVector::get(Context, Elts);
1468 V = ConstantDataArray::get(Context, Elts);
1469 } else if (EltTy->isDoubleTy()) {
1470 SmallVector<double, 16> Elts(Size);
1471 std::transform(Record.begin(), Record.end(), Elts.begin(),
1473 if (isa<VectorType>(CurTy))
1474 V = ConstantDataVector::get(Context, Elts);
1476 V = ConstantDataArray::get(Context, Elts);
1478 return Error(BitcodeError::InvalidTypeForValue);
1483 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1484 if (Record.size() < 3)
1485 return Error(BitcodeError::InvalidRecord);
1486 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1488 V = UndefValue::get(CurTy); // Unknown binop.
1490 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1491 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1493 if (Record.size() >= 4) {
1494 if (Opc == Instruction::Add ||
1495 Opc == Instruction::Sub ||
1496 Opc == Instruction::Mul ||
1497 Opc == Instruction::Shl) {
1498 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1499 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1500 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1501 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1502 } else if (Opc == Instruction::SDiv ||
1503 Opc == Instruction::UDiv ||
1504 Opc == Instruction::LShr ||
1505 Opc == Instruction::AShr) {
1506 if (Record[3] & (1 << bitc::PEO_EXACT))
1507 Flags |= SDivOperator::IsExact;
1510 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1514 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1515 if (Record.size() < 3)
1516 return Error(BitcodeError::InvalidRecord);
1517 int Opc = GetDecodedCastOpcode(Record[0]);
1519 V = UndefValue::get(CurTy); // Unknown cast.
1521 Type *OpTy = getTypeByID(Record[1]);
1523 return Error(BitcodeError::InvalidRecord);
1524 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1525 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1526 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1530 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1531 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1532 if (Record.size() & 1)
1533 return Error(BitcodeError::InvalidRecord);
1534 SmallVector<Constant*, 16> Elts;
1535 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1536 Type *ElTy = getTypeByID(Record[i]);
1538 return Error(BitcodeError::InvalidRecord);
1539 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1541 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1542 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1544 bitc::CST_CODE_CE_INBOUNDS_GEP);
1547 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1548 if (Record.size() < 3)
1549 return Error(BitcodeError::InvalidRecord);
1551 Type *SelectorTy = Type::getInt1Ty(Context);
1553 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1554 // vector. Otherwise, it must be a single bit.
1555 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1556 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1557 VTy->getNumElements());
1559 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1561 ValueList.getConstantFwdRef(Record[1],CurTy),
1562 ValueList.getConstantFwdRef(Record[2],CurTy));
1565 case bitc::CST_CODE_CE_EXTRACTELT
1566 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1567 if (Record.size() < 3)
1568 return Error(BitcodeError::InvalidRecord);
1570 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1572 return Error(BitcodeError::InvalidRecord);
1573 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1574 Constant *Op1 = nullptr;
1575 if (Record.size() == 4) {
1576 Type *IdxTy = getTypeByID(Record[2]);
1578 return Error(BitcodeError::InvalidRecord);
1579 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1580 } else // TODO: Remove with llvm 4.0
1581 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1583 return Error(BitcodeError::InvalidRecord);
1584 V = ConstantExpr::getExtractElement(Op0, Op1);
1587 case bitc::CST_CODE_CE_INSERTELT
1588 : { // CE_INSERTELT: [opval, opval, opty, opval]
1589 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1590 if (Record.size() < 3 || !OpTy)
1591 return Error(BitcodeError::InvalidRecord);
1592 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1593 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1594 OpTy->getElementType());
1595 Constant *Op2 = nullptr;
1596 if (Record.size() == 4) {
1597 Type *IdxTy = getTypeByID(Record[2]);
1599 return Error(BitcodeError::InvalidRecord);
1600 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1601 } else // TODO: Remove with llvm 4.0
1602 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1604 return Error(BitcodeError::InvalidRecord);
1605 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1608 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1609 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1610 if (Record.size() < 3 || !OpTy)
1611 return Error(BitcodeError::InvalidRecord);
1612 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1613 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1614 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1615 OpTy->getNumElements());
1616 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1617 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1620 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1621 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1623 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1624 if (Record.size() < 4 || !RTy || !OpTy)
1625 return Error(BitcodeError::InvalidRecord);
1626 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1627 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1628 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1629 RTy->getNumElements());
1630 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1631 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1634 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1635 if (Record.size() < 4)
1636 return Error(BitcodeError::InvalidRecord);
1637 Type *OpTy = getTypeByID(Record[0]);
1639 return Error(BitcodeError::InvalidRecord);
1640 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1641 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1643 if (OpTy->isFPOrFPVectorTy())
1644 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1646 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1649 // This maintains backward compatibility, pre-asm dialect keywords.
1650 // FIXME: Remove with the 4.0 release.
1651 case bitc::CST_CODE_INLINEASM_OLD: {
1652 if (Record.size() < 2)
1653 return Error(BitcodeError::InvalidRecord);
1654 std::string AsmStr, ConstrStr;
1655 bool HasSideEffects = Record[0] & 1;
1656 bool IsAlignStack = Record[0] >> 1;
1657 unsigned AsmStrSize = Record[1];
1658 if (2+AsmStrSize >= Record.size())
1659 return Error(BitcodeError::InvalidRecord);
1660 unsigned ConstStrSize = Record[2+AsmStrSize];
1661 if (3+AsmStrSize+ConstStrSize > Record.size())
1662 return Error(BitcodeError::InvalidRecord);
1664 for (unsigned i = 0; i != AsmStrSize; ++i)
1665 AsmStr += (char)Record[2+i];
1666 for (unsigned i = 0; i != ConstStrSize; ++i)
1667 ConstrStr += (char)Record[3+AsmStrSize+i];
1668 PointerType *PTy = cast<PointerType>(CurTy);
1669 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1670 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1673 // This version adds support for the asm dialect keywords (e.g.,
1675 case bitc::CST_CODE_INLINEASM: {
1676 if (Record.size() < 2)
1677 return Error(BitcodeError::InvalidRecord);
1678 std::string AsmStr, ConstrStr;
1679 bool HasSideEffects = Record[0] & 1;
1680 bool IsAlignStack = (Record[0] >> 1) & 1;
1681 unsigned AsmDialect = Record[0] >> 2;
1682 unsigned AsmStrSize = Record[1];
1683 if (2+AsmStrSize >= Record.size())
1684 return Error(BitcodeError::InvalidRecord);
1685 unsigned ConstStrSize = Record[2+AsmStrSize];
1686 if (3+AsmStrSize+ConstStrSize > Record.size())
1687 return Error(BitcodeError::InvalidRecord);
1689 for (unsigned i = 0; i != AsmStrSize; ++i)
1690 AsmStr += (char)Record[2+i];
1691 for (unsigned i = 0; i != ConstStrSize; ++i)
1692 ConstrStr += (char)Record[3+AsmStrSize+i];
1693 PointerType *PTy = cast<PointerType>(CurTy);
1694 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1695 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1696 InlineAsm::AsmDialect(AsmDialect));
1699 case bitc::CST_CODE_BLOCKADDRESS:{
1700 if (Record.size() < 3)
1701 return Error(BitcodeError::InvalidRecord);
1702 Type *FnTy = getTypeByID(Record[0]);
1704 return Error(BitcodeError::InvalidRecord);
1706 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1708 return Error(BitcodeError::InvalidRecord);
1710 // Don't let Fn get dematerialized.
1711 BlockAddressesTaken.insert(Fn);
1713 // If the function is already parsed we can insert the block address right
1716 unsigned BBID = Record[2];
1718 // Invalid reference to entry block.
1719 return Error(BitcodeError::InvalidID);
1721 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1722 for (size_t I = 0, E = BBID; I != E; ++I) {
1724 return Error(BitcodeError::InvalidID);
1729 // Otherwise insert a placeholder and remember it so it can be inserted
1730 // when the function is parsed.
1731 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1733 BasicBlockFwdRefQueue.push_back(Fn);
1734 if (FwdBBs.size() < BBID + 1)
1735 FwdBBs.resize(BBID + 1);
1737 FwdBBs[BBID] = BasicBlock::Create(Context);
1740 V = BlockAddress::get(Fn, BB);
1745 ValueList.AssignValue(V, NextCstNo);
1750 std::error_code BitcodeReader::ParseUseLists() {
1751 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1752 return Error(BitcodeError::InvalidRecord);
1754 // Read all the records.
1755 SmallVector<uint64_t, 64> Record;
1757 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1759 switch (Entry.Kind) {
1760 case BitstreamEntry::SubBlock: // Handled for us already.
1761 case BitstreamEntry::Error:
1762 return Error(BitcodeError::MalformedBlock);
1763 case BitstreamEntry::EndBlock:
1764 return std::error_code();
1765 case BitstreamEntry::Record:
1766 // The interesting case.
1770 // Read a use list record.
1773 switch (Stream.readRecord(Entry.ID, Record)) {
1774 default: // Default behavior: unknown type.
1776 case bitc::USELIST_CODE_BB:
1779 case bitc::USELIST_CODE_DEFAULT: {
1780 unsigned RecordLength = Record.size();
1781 if (RecordLength < 3)
1782 // Records should have at least an ID and two indexes.
1783 return Error(BitcodeError::InvalidRecord);
1784 unsigned ID = Record.back();
1789 assert(ID < FunctionBBs.size() && "Basic block not found");
1790 V = FunctionBBs[ID];
1793 unsigned NumUses = 0;
1794 SmallDenseMap<const Use *, unsigned, 16> Order;
1795 for (const Use &U : V->uses()) {
1796 if (++NumUses > Record.size())
1798 Order[&U] = Record[NumUses - 1];
1800 if (Order.size() != Record.size() || NumUses > Record.size())
1801 // Mismatches can happen if the functions are being materialized lazily
1802 // (out-of-order), or a value has been upgraded.
1805 V->sortUseList([&](const Use &L, const Use &R) {
1806 return Order.lookup(&L) < Order.lookup(&R);
1814 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1815 /// remember where it is and then skip it. This lets us lazily deserialize the
1817 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1818 // Get the function we are talking about.
1819 if (FunctionsWithBodies.empty())
1820 return Error(BitcodeError::InsufficientFunctionProtos);
1822 Function *Fn = FunctionsWithBodies.back();
1823 FunctionsWithBodies.pop_back();
1825 // Save the current stream state.
1826 uint64_t CurBit = Stream.GetCurrentBitNo();
1827 DeferredFunctionInfo[Fn] = CurBit;
1829 // Skip over the function block for now.
1830 if (Stream.SkipBlock())
1831 return Error(BitcodeError::InvalidRecord);
1832 return std::error_code();
1835 std::error_code BitcodeReader::GlobalCleanup() {
1836 // Patch the initializers for globals and aliases up.
1837 ResolveGlobalAndAliasInits();
1838 if (!GlobalInits.empty() || !AliasInits.empty())
1839 return Error(BitcodeError::MalformedGlobalInitializerSet);
1841 // Look for intrinsic functions which need to be upgraded at some point
1842 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1845 if (UpgradeIntrinsicFunction(FI, NewFn))
1846 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1849 // Look for global variables which need to be renamed.
1850 for (Module::global_iterator
1851 GI = TheModule->global_begin(), GE = TheModule->global_end();
1853 GlobalVariable *GV = GI++;
1854 UpgradeGlobalVariable(GV);
1857 // Force deallocation of memory for these vectors to favor the client that
1858 // want lazy deserialization.
1859 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1860 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1861 return std::error_code();
1864 std::error_code BitcodeReader::ParseModule(bool Resume) {
1866 Stream.JumpToBit(NextUnreadBit);
1867 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1868 return Error(BitcodeError::InvalidRecord);
1870 SmallVector<uint64_t, 64> Record;
1871 std::vector<std::string> SectionTable;
1872 std::vector<std::string> GCTable;
1874 // Read all the records for this module.
1876 BitstreamEntry Entry = Stream.advance();
1878 switch (Entry.Kind) {
1879 case BitstreamEntry::Error:
1880 return Error(BitcodeError::MalformedBlock);
1881 case BitstreamEntry::EndBlock:
1882 return GlobalCleanup();
1884 case BitstreamEntry::SubBlock:
1886 default: // Skip unknown content.
1887 if (Stream.SkipBlock())
1888 return Error(BitcodeError::InvalidRecord);
1890 case bitc::BLOCKINFO_BLOCK_ID:
1891 if (Stream.ReadBlockInfoBlock())
1892 return Error(BitcodeError::MalformedBlock);
1894 case bitc::PARAMATTR_BLOCK_ID:
1895 if (std::error_code EC = ParseAttributeBlock())
1898 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1899 if (std::error_code EC = ParseAttributeGroupBlock())
1902 case bitc::TYPE_BLOCK_ID_NEW:
1903 if (std::error_code EC = ParseTypeTable())
1906 case bitc::VALUE_SYMTAB_BLOCK_ID:
1907 if (std::error_code EC = ParseValueSymbolTable())
1909 SeenValueSymbolTable = true;
1911 case bitc::CONSTANTS_BLOCK_ID:
1912 if (std::error_code EC = ParseConstants())
1914 if (std::error_code EC = ResolveGlobalAndAliasInits())
1917 case bitc::METADATA_BLOCK_ID:
1918 if (std::error_code EC = ParseMetadata())
1921 case bitc::FUNCTION_BLOCK_ID:
1922 // If this is the first function body we've seen, reverse the
1923 // FunctionsWithBodies list.
1924 if (!SeenFirstFunctionBody) {
1925 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1926 if (std::error_code EC = GlobalCleanup())
1928 SeenFirstFunctionBody = true;
1931 if (std::error_code EC = RememberAndSkipFunctionBody())
1933 // For streaming bitcode, suspend parsing when we reach the function
1934 // bodies. Subsequent materialization calls will resume it when
1935 // necessary. For streaming, the function bodies must be at the end of
1936 // the bitcode. If the bitcode file is old, the symbol table will be
1937 // at the end instead and will not have been seen yet. In this case,
1938 // just finish the parse now.
1939 if (LazyStreamer && SeenValueSymbolTable) {
1940 NextUnreadBit = Stream.GetCurrentBitNo();
1941 return std::error_code();
1944 case bitc::USELIST_BLOCK_ID:
1945 if (std::error_code EC = ParseUseLists())
1951 case BitstreamEntry::Record:
1952 // The interesting case.
1958 switch (Stream.readRecord(Entry.ID, Record)) {
1959 default: break; // Default behavior, ignore unknown content.
1960 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1961 if (Record.size() < 1)
1962 return Error(BitcodeError::InvalidRecord);
1963 // Only version #0 and #1 are supported so far.
1964 unsigned module_version = Record[0];
1965 switch (module_version) {
1967 return Error(BitcodeError::InvalidValue);
1969 UseRelativeIDs = false;
1972 UseRelativeIDs = true;
1977 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1979 if (ConvertToString(Record, 0, S))
1980 return Error(BitcodeError::InvalidRecord);
1981 TheModule->setTargetTriple(S);
1984 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1986 if (ConvertToString(Record, 0, S))
1987 return Error(BitcodeError::InvalidRecord);
1988 TheModule->setDataLayout(S);
1991 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1993 if (ConvertToString(Record, 0, S))
1994 return Error(BitcodeError::InvalidRecord);
1995 TheModule->setModuleInlineAsm(S);
1998 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1999 // FIXME: Remove in 4.0.
2001 if (ConvertToString(Record, 0, S))
2002 return Error(BitcodeError::InvalidRecord);
2006 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2008 if (ConvertToString(Record, 0, S))
2009 return Error(BitcodeError::InvalidRecord);
2010 SectionTable.push_back(S);
2013 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2015 if (ConvertToString(Record, 0, S))
2016 return Error(BitcodeError::InvalidRecord);
2017 GCTable.push_back(S);
2020 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2021 if (Record.size() < 2)
2022 return Error(BitcodeError::InvalidRecord);
2023 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2024 unsigned ComdatNameSize = Record[1];
2025 std::string ComdatName;
2026 ComdatName.reserve(ComdatNameSize);
2027 for (unsigned i = 0; i != ComdatNameSize; ++i)
2028 ComdatName += (char)Record[2 + i];
2029 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2030 C->setSelectionKind(SK);
2031 ComdatList.push_back(C);
2034 // GLOBALVAR: [pointer type, isconst, initid,
2035 // linkage, alignment, section, visibility, threadlocal,
2036 // unnamed_addr, dllstorageclass]
2037 case bitc::MODULE_CODE_GLOBALVAR: {
2038 if (Record.size() < 6)
2039 return Error(BitcodeError::InvalidRecord);
2040 Type *Ty = getTypeByID(Record[0]);
2042 return Error(BitcodeError::InvalidRecord);
2043 if (!Ty->isPointerTy())
2044 return Error(BitcodeError::InvalidTypeForValue);
2045 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2046 Ty = cast<PointerType>(Ty)->getElementType();
2048 bool isConstant = Record[1];
2049 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
2050 unsigned Alignment = (1 << Record[4]) >> 1;
2051 std::string Section;
2053 if (Record[5]-1 >= SectionTable.size())
2054 return Error(BitcodeError::InvalidID);
2055 Section = SectionTable[Record[5]-1];
2057 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2058 // Local linkage must have default visibility.
2059 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2060 // FIXME: Change to an error if non-default in 4.0.
2061 Visibility = GetDecodedVisibility(Record[6]);
2063 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2064 if (Record.size() > 7)
2065 TLM = GetDecodedThreadLocalMode(Record[7]);
2067 bool UnnamedAddr = false;
2068 if (Record.size() > 8)
2069 UnnamedAddr = Record[8];
2071 bool ExternallyInitialized = false;
2072 if (Record.size() > 9)
2073 ExternallyInitialized = Record[9];
2075 GlobalVariable *NewGV =
2076 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2077 TLM, AddressSpace, ExternallyInitialized);
2078 NewGV->setAlignment(Alignment);
2079 if (!Section.empty())
2080 NewGV->setSection(Section);
2081 NewGV->setVisibility(Visibility);
2082 NewGV->setUnnamedAddr(UnnamedAddr);
2084 if (Record.size() > 10)
2085 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2087 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2089 ValueList.push_back(NewGV);
2091 // Remember which value to use for the global initializer.
2092 if (unsigned InitID = Record[2])
2093 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2095 if (Record.size() > 11)
2096 if (unsigned ComdatID = Record[11]) {
2097 assert(ComdatID <= ComdatList.size());
2098 NewGV->setComdat(ComdatList[ComdatID - 1]);
2102 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2103 // alignment, section, visibility, gc, unnamed_addr,
2104 // prologuedata, dllstorageclass, comdat, prefixdata]
2105 case bitc::MODULE_CODE_FUNCTION: {
2106 if (Record.size() < 8)
2107 return Error(BitcodeError::InvalidRecord);
2108 Type *Ty = getTypeByID(Record[0]);
2110 return Error(BitcodeError::InvalidRecord);
2111 if (!Ty->isPointerTy())
2112 return Error(BitcodeError::InvalidTypeForValue);
2114 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2116 return Error(BitcodeError::InvalidTypeForValue);
2118 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2121 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2122 bool isProto = Record[2];
2123 Func->setLinkage(GetDecodedLinkage(Record[3]));
2124 Func->setAttributes(getAttributes(Record[4]));
2126 Func->setAlignment((1 << Record[5]) >> 1);
2128 if (Record[6]-1 >= SectionTable.size())
2129 return Error(BitcodeError::InvalidID);
2130 Func->setSection(SectionTable[Record[6]-1]);
2132 // Local linkage must have default visibility.
2133 if (!Func->hasLocalLinkage())
2134 // FIXME: Change to an error if non-default in 4.0.
2135 Func->setVisibility(GetDecodedVisibility(Record[7]));
2136 if (Record.size() > 8 && Record[8]) {
2137 if (Record[8]-1 > GCTable.size())
2138 return Error(BitcodeError::InvalidID);
2139 Func->setGC(GCTable[Record[8]-1].c_str());
2141 bool UnnamedAddr = false;
2142 if (Record.size() > 9)
2143 UnnamedAddr = Record[9];
2144 Func->setUnnamedAddr(UnnamedAddr);
2145 if (Record.size() > 10 && Record[10] != 0)
2146 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2148 if (Record.size() > 11)
2149 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2151 UpgradeDLLImportExportLinkage(Func, Record[3]);
2153 if (Record.size() > 12)
2154 if (unsigned ComdatID = Record[12]) {
2155 assert(ComdatID <= ComdatList.size());
2156 Func->setComdat(ComdatList[ComdatID - 1]);
2159 if (Record.size() > 13 && Record[13] != 0)
2160 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2162 ValueList.push_back(Func);
2164 // If this is a function with a body, remember the prototype we are
2165 // creating now, so that we can match up the body with them later.
2167 Func->setIsMaterializable(true);
2168 FunctionsWithBodies.push_back(Func);
2170 DeferredFunctionInfo[Func] = 0;
2174 // ALIAS: [alias type, aliasee val#, linkage]
2175 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2176 case bitc::MODULE_CODE_ALIAS: {
2177 if (Record.size() < 3)
2178 return Error(BitcodeError::InvalidRecord);
2179 Type *Ty = getTypeByID(Record[0]);
2181 return Error(BitcodeError::InvalidRecord);
2182 auto *PTy = dyn_cast<PointerType>(Ty);
2184 return Error(BitcodeError::InvalidTypeForValue);
2187 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2188 GetDecodedLinkage(Record[2]), "", TheModule);
2189 // Old bitcode files didn't have visibility field.
2190 // Local linkage must have default visibility.
2191 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2192 // FIXME: Change to an error if non-default in 4.0.
2193 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2194 if (Record.size() > 4)
2195 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2197 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2198 if (Record.size() > 5)
2199 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2200 if (Record.size() > 6)
2201 NewGA->setUnnamedAddr(Record[6]);
2202 ValueList.push_back(NewGA);
2203 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2206 /// MODULE_CODE_PURGEVALS: [numvals]
2207 case bitc::MODULE_CODE_PURGEVALS:
2208 // Trim down the value list to the specified size.
2209 if (Record.size() < 1 || Record[0] > ValueList.size())
2210 return Error(BitcodeError::InvalidRecord);
2211 ValueList.shrinkTo(Record[0]);
2218 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2219 TheModule = nullptr;
2221 if (std::error_code EC = InitStream())
2224 // Sniff for the signature.
2225 if (Stream.Read(8) != 'B' ||
2226 Stream.Read(8) != 'C' ||
2227 Stream.Read(4) != 0x0 ||
2228 Stream.Read(4) != 0xC ||
2229 Stream.Read(4) != 0xE ||
2230 Stream.Read(4) != 0xD)
2231 return Error(BitcodeError::InvalidBitcodeSignature);
2233 // We expect a number of well-defined blocks, though we don't necessarily
2234 // need to understand them all.
2236 if (Stream.AtEndOfStream())
2237 return std::error_code();
2239 BitstreamEntry Entry =
2240 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2242 switch (Entry.Kind) {
2243 case BitstreamEntry::Error:
2244 return Error(BitcodeError::MalformedBlock);
2245 case BitstreamEntry::EndBlock:
2246 return std::error_code();
2248 case BitstreamEntry::SubBlock:
2250 case bitc::BLOCKINFO_BLOCK_ID:
2251 if (Stream.ReadBlockInfoBlock())
2252 return Error(BitcodeError::MalformedBlock);
2254 case bitc::MODULE_BLOCK_ID:
2255 // Reject multiple MODULE_BLOCK's in a single bitstream.
2257 return Error(BitcodeError::InvalidMultipleBlocks);
2259 if (std::error_code EC = ParseModule(false))
2262 return std::error_code();
2265 if (Stream.SkipBlock())
2266 return Error(BitcodeError::InvalidRecord);
2270 case BitstreamEntry::Record:
2271 // There should be no records in the top-level of blocks.
2273 // The ranlib in Xcode 4 will align archive members by appending newlines
2274 // to the end of them. If this file size is a multiple of 4 but not 8, we
2275 // have to read and ignore these final 4 bytes :-(
2276 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2277 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2278 Stream.AtEndOfStream())
2279 return std::error_code();
2281 return Error(BitcodeError::InvalidRecord);
2286 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2287 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2288 return Error(BitcodeError::InvalidRecord);
2290 SmallVector<uint64_t, 64> Record;
2293 // Read all the records for this module.
2295 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2297 switch (Entry.Kind) {
2298 case BitstreamEntry::SubBlock: // Handled for us already.
2299 case BitstreamEntry::Error:
2300 return Error(BitcodeError::MalformedBlock);
2301 case BitstreamEntry::EndBlock:
2303 case BitstreamEntry::Record:
2304 // The interesting case.
2309 switch (Stream.readRecord(Entry.ID, Record)) {
2310 default: break; // Default behavior, ignore unknown content.
2311 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2313 if (ConvertToString(Record, 0, S))
2314 return Error(BitcodeError::InvalidRecord);
2321 llvm_unreachable("Exit infinite loop");
2324 ErrorOr<std::string> BitcodeReader::parseTriple() {
2325 if (std::error_code EC = InitStream())
2328 // Sniff for the signature.
2329 if (Stream.Read(8) != 'B' ||
2330 Stream.Read(8) != 'C' ||
2331 Stream.Read(4) != 0x0 ||
2332 Stream.Read(4) != 0xC ||
2333 Stream.Read(4) != 0xE ||
2334 Stream.Read(4) != 0xD)
2335 return Error(BitcodeError::InvalidBitcodeSignature);
2337 // We expect a number of well-defined blocks, though we don't necessarily
2338 // need to understand them all.
2340 BitstreamEntry Entry = Stream.advance();
2342 switch (Entry.Kind) {
2343 case BitstreamEntry::Error:
2344 return Error(BitcodeError::MalformedBlock);
2345 case BitstreamEntry::EndBlock:
2346 return std::error_code();
2348 case BitstreamEntry::SubBlock:
2349 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2350 return parseModuleTriple();
2352 // Ignore other sub-blocks.
2353 if (Stream.SkipBlock())
2354 return Error(BitcodeError::MalformedBlock);
2357 case BitstreamEntry::Record:
2358 Stream.skipRecord(Entry.ID);
2364 /// ParseMetadataAttachment - Parse metadata attachments.
2365 std::error_code BitcodeReader::ParseMetadataAttachment() {
2366 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2367 return Error(BitcodeError::InvalidRecord);
2369 SmallVector<uint64_t, 64> Record;
2371 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2373 switch (Entry.Kind) {
2374 case BitstreamEntry::SubBlock: // Handled for us already.
2375 case BitstreamEntry::Error:
2376 return Error(BitcodeError::MalformedBlock);
2377 case BitstreamEntry::EndBlock:
2378 return std::error_code();
2379 case BitstreamEntry::Record:
2380 // The interesting case.
2384 // Read a metadata attachment record.
2386 switch (Stream.readRecord(Entry.ID, Record)) {
2387 default: // Default behavior: ignore.
2389 case bitc::METADATA_ATTACHMENT: {
2390 unsigned RecordLength = Record.size();
2391 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2392 return Error(BitcodeError::InvalidRecord);
2393 Instruction *Inst = InstructionList[Record[0]];
2394 for (unsigned i = 1; i != RecordLength; i = i+2) {
2395 unsigned Kind = Record[i];
2396 DenseMap<unsigned, unsigned>::iterator I =
2397 MDKindMap.find(Kind);
2398 if (I == MDKindMap.end())
2399 return Error(BitcodeError::InvalidID);
2400 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2401 if (isa<LocalAsMetadata>(Node))
2402 // Drop the attachment. This used to be legal, but there's no
2405 Inst->setMetadata(I->second, cast<MDNode>(Node));
2406 if (I->second == LLVMContext::MD_tbaa)
2407 InstsWithTBAATag.push_back(Inst);
2415 /// ParseFunctionBody - Lazily parse the specified function body block.
2416 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2417 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2418 return Error(BitcodeError::InvalidRecord);
2420 InstructionList.clear();
2421 unsigned ModuleValueListSize = ValueList.size();
2422 unsigned ModuleMDValueListSize = MDValueList.size();
2424 // Add all the function arguments to the value table.
2425 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2426 ValueList.push_back(I);
2428 unsigned NextValueNo = ValueList.size();
2429 BasicBlock *CurBB = nullptr;
2430 unsigned CurBBNo = 0;
2434 // Read all the records.
2435 SmallVector<uint64_t, 64> Record;
2437 BitstreamEntry Entry = Stream.advance();
2439 switch (Entry.Kind) {
2440 case BitstreamEntry::Error:
2441 return Error(BitcodeError::MalformedBlock);
2442 case BitstreamEntry::EndBlock:
2443 goto OutOfRecordLoop;
2445 case BitstreamEntry::SubBlock:
2447 default: // Skip unknown content.
2448 if (Stream.SkipBlock())
2449 return Error(BitcodeError::InvalidRecord);
2451 case bitc::CONSTANTS_BLOCK_ID:
2452 if (std::error_code EC = ParseConstants())
2454 NextValueNo = ValueList.size();
2456 case bitc::VALUE_SYMTAB_BLOCK_ID:
2457 if (std::error_code EC = ParseValueSymbolTable())
2460 case bitc::METADATA_ATTACHMENT_ID:
2461 if (std::error_code EC = ParseMetadataAttachment())
2464 case bitc::METADATA_BLOCK_ID:
2465 if (std::error_code EC = ParseMetadata())
2468 case bitc::USELIST_BLOCK_ID:
2469 if (std::error_code EC = ParseUseLists())
2475 case BitstreamEntry::Record:
2476 // The interesting case.
2482 Instruction *I = nullptr;
2483 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2485 default: // Default behavior: reject
2486 return Error(BitcodeError::InvalidValue);
2487 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2488 if (Record.size() < 1 || Record[0] == 0)
2489 return Error(BitcodeError::InvalidRecord);
2490 // Create all the basic blocks for the function.
2491 FunctionBBs.resize(Record[0]);
2493 // See if anything took the address of blocks in this function.
2494 auto BBFRI = BasicBlockFwdRefs.find(F);
2495 if (BBFRI == BasicBlockFwdRefs.end()) {
2496 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2497 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2499 auto &BBRefs = BBFRI->second;
2500 // Check for invalid basic block references.
2501 if (BBRefs.size() > FunctionBBs.size())
2502 return Error(BitcodeError::InvalidID);
2503 assert(!BBRefs.empty() && "Unexpected empty array");
2504 assert(!BBRefs.front() && "Invalid reference to entry block");
2505 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2507 if (I < RE && BBRefs[I]) {
2508 BBRefs[I]->insertInto(F);
2509 FunctionBBs[I] = BBRefs[I];
2511 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2514 // Erase from the table.
2515 BasicBlockFwdRefs.erase(BBFRI);
2518 CurBB = FunctionBBs[0];
2522 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2523 // This record indicates that the last instruction is at the same
2524 // location as the previous instruction with a location.
2527 // Get the last instruction emitted.
2528 if (CurBB && !CurBB->empty())
2530 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2531 !FunctionBBs[CurBBNo-1]->empty())
2532 I = &FunctionBBs[CurBBNo-1]->back();
2535 return Error(BitcodeError::InvalidRecord);
2536 I->setDebugLoc(LastLoc);
2540 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2541 I = nullptr; // Get the last instruction emitted.
2542 if (CurBB && !CurBB->empty())
2544 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2545 !FunctionBBs[CurBBNo-1]->empty())
2546 I = &FunctionBBs[CurBBNo-1]->back();
2547 if (!I || Record.size() < 4)
2548 return Error(BitcodeError::InvalidRecord);
2550 unsigned Line = Record[0], Col = Record[1];
2551 unsigned ScopeID = Record[2], IAID = Record[3];
2553 MDNode *Scope = nullptr, *IA = nullptr;
2554 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2555 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2556 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2557 I->setDebugLoc(LastLoc);
2562 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2565 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2566 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2567 OpNum+1 > Record.size())
2568 return Error(BitcodeError::InvalidRecord);
2570 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2572 return Error(BitcodeError::InvalidRecord);
2573 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2574 InstructionList.push_back(I);
2575 if (OpNum < Record.size()) {
2576 if (Opc == Instruction::Add ||
2577 Opc == Instruction::Sub ||
2578 Opc == Instruction::Mul ||
2579 Opc == Instruction::Shl) {
2580 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2581 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2582 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2583 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2584 } else if (Opc == Instruction::SDiv ||
2585 Opc == Instruction::UDiv ||
2586 Opc == Instruction::LShr ||
2587 Opc == Instruction::AShr) {
2588 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2589 cast<BinaryOperator>(I)->setIsExact(true);
2590 } else if (isa<FPMathOperator>(I)) {
2592 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2593 FMF.setUnsafeAlgebra();
2594 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2596 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2598 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2599 FMF.setNoSignedZeros();
2600 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2601 FMF.setAllowReciprocal();
2603 I->setFastMathFlags(FMF);
2609 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2612 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2613 OpNum+2 != Record.size())
2614 return Error(BitcodeError::InvalidRecord);
2616 Type *ResTy = getTypeByID(Record[OpNum]);
2617 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2618 if (Opc == -1 || !ResTy)
2619 return Error(BitcodeError::InvalidRecord);
2620 Instruction *Temp = nullptr;
2621 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2623 InstructionList.push_back(Temp);
2624 CurBB->getInstList().push_back(Temp);
2627 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2629 InstructionList.push_back(I);
2632 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2633 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2636 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2637 return Error(BitcodeError::InvalidRecord);
2639 SmallVector<Value*, 16> GEPIdx;
2640 while (OpNum != Record.size()) {
2642 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2643 return Error(BitcodeError::InvalidRecord);
2644 GEPIdx.push_back(Op);
2647 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2648 InstructionList.push_back(I);
2649 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2650 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2654 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2655 // EXTRACTVAL: [opty, opval, n x indices]
2658 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2659 return Error(BitcodeError::InvalidRecord);
2661 SmallVector<unsigned, 4> EXTRACTVALIdx;
2662 for (unsigned RecSize = Record.size();
2663 OpNum != RecSize; ++OpNum) {
2664 uint64_t Index = Record[OpNum];
2665 if ((unsigned)Index != Index)
2666 return Error(BitcodeError::InvalidValue);
2667 EXTRACTVALIdx.push_back((unsigned)Index);
2670 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2671 InstructionList.push_back(I);
2675 case bitc::FUNC_CODE_INST_INSERTVAL: {
2676 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2679 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2680 return Error(BitcodeError::InvalidRecord);
2682 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2683 return Error(BitcodeError::InvalidRecord);
2685 SmallVector<unsigned, 4> INSERTVALIdx;
2686 for (unsigned RecSize = Record.size();
2687 OpNum != RecSize; ++OpNum) {
2688 uint64_t Index = Record[OpNum];
2689 if ((unsigned)Index != Index)
2690 return Error(BitcodeError::InvalidValue);
2691 INSERTVALIdx.push_back((unsigned)Index);
2694 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2695 InstructionList.push_back(I);
2699 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2700 // obsolete form of select
2701 // handles select i1 ... in old bitcode
2703 Value *TrueVal, *FalseVal, *Cond;
2704 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2705 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2706 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2707 return Error(BitcodeError::InvalidRecord);
2709 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2710 InstructionList.push_back(I);
2714 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2715 // new form of select
2716 // handles select i1 or select [N x i1]
2718 Value *TrueVal, *FalseVal, *Cond;
2719 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2720 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2721 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2722 return Error(BitcodeError::InvalidRecord);
2724 // select condition can be either i1 or [N x i1]
2725 if (VectorType* vector_type =
2726 dyn_cast<VectorType>(Cond->getType())) {
2728 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2729 return Error(BitcodeError::InvalidTypeForValue);
2732 if (Cond->getType() != Type::getInt1Ty(Context))
2733 return Error(BitcodeError::InvalidTypeForValue);
2736 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2737 InstructionList.push_back(I);
2741 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2744 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2745 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2746 return Error(BitcodeError::InvalidRecord);
2747 I = ExtractElementInst::Create(Vec, Idx);
2748 InstructionList.push_back(I);
2752 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2754 Value *Vec, *Elt, *Idx;
2755 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2756 popValue(Record, OpNum, NextValueNo,
2757 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2758 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2759 return Error(BitcodeError::InvalidRecord);
2760 I = InsertElementInst::Create(Vec, Elt, Idx);
2761 InstructionList.push_back(I);
2765 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2767 Value *Vec1, *Vec2, *Mask;
2768 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2769 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2770 return Error(BitcodeError::InvalidRecord);
2772 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2773 return Error(BitcodeError::InvalidRecord);
2774 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2775 InstructionList.push_back(I);
2779 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2780 // Old form of ICmp/FCmp returning bool
2781 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2782 // both legal on vectors but had different behaviour.
2783 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2784 // FCmp/ICmp returning bool or vector of bool
2788 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2789 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2790 OpNum+1 != Record.size())
2791 return Error(BitcodeError::InvalidRecord);
2793 if (LHS->getType()->isFPOrFPVectorTy())
2794 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2796 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2797 InstructionList.push_back(I);
2801 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2803 unsigned Size = Record.size();
2805 I = ReturnInst::Create(Context);
2806 InstructionList.push_back(I);
2811 Value *Op = nullptr;
2812 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2813 return Error(BitcodeError::InvalidRecord);
2814 if (OpNum != Record.size())
2815 return Error(BitcodeError::InvalidRecord);
2817 I = ReturnInst::Create(Context, Op);
2818 InstructionList.push_back(I);
2821 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2822 if (Record.size() != 1 && Record.size() != 3)
2823 return Error(BitcodeError::InvalidRecord);
2824 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2826 return Error(BitcodeError::InvalidRecord);
2828 if (Record.size() == 1) {
2829 I = BranchInst::Create(TrueDest);
2830 InstructionList.push_back(I);
2833 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2834 Value *Cond = getValue(Record, 2, NextValueNo,
2835 Type::getInt1Ty(Context));
2836 if (!FalseDest || !Cond)
2837 return Error(BitcodeError::InvalidRecord);
2838 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2839 InstructionList.push_back(I);
2843 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2845 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2846 // "New" SwitchInst format with case ranges. The changes to write this
2847 // format were reverted but we still recognize bitcode that uses it.
2848 // Hopefully someday we will have support for case ranges and can use
2849 // this format again.
2851 Type *OpTy = getTypeByID(Record[1]);
2852 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2854 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2855 BasicBlock *Default = getBasicBlock(Record[3]);
2856 if (!OpTy || !Cond || !Default)
2857 return Error(BitcodeError::InvalidRecord);
2859 unsigned NumCases = Record[4];
2861 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2862 InstructionList.push_back(SI);
2864 unsigned CurIdx = 5;
2865 for (unsigned i = 0; i != NumCases; ++i) {
2866 SmallVector<ConstantInt*, 1> CaseVals;
2867 unsigned NumItems = Record[CurIdx++];
2868 for (unsigned ci = 0; ci != NumItems; ++ci) {
2869 bool isSingleNumber = Record[CurIdx++];
2872 unsigned ActiveWords = 1;
2873 if (ValueBitWidth > 64)
2874 ActiveWords = Record[CurIdx++];
2875 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2877 CurIdx += ActiveWords;
2879 if (!isSingleNumber) {
2881 if (ValueBitWidth > 64)
2882 ActiveWords = Record[CurIdx++];
2884 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2886 CurIdx += ActiveWords;
2888 // FIXME: It is not clear whether values in the range should be
2889 // compared as signed or unsigned values. The partially
2890 // implemented changes that used this format in the past used
2891 // unsigned comparisons.
2892 for ( ; Low.ule(High); ++Low)
2893 CaseVals.push_back(ConstantInt::get(Context, Low));
2895 CaseVals.push_back(ConstantInt::get(Context, Low));
2897 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2898 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2899 cve = CaseVals.end(); cvi != cve; ++cvi)
2900 SI->addCase(*cvi, DestBB);
2906 // Old SwitchInst format without case ranges.
2908 if (Record.size() < 3 || (Record.size() & 1) == 0)
2909 return Error(BitcodeError::InvalidRecord);
2910 Type *OpTy = getTypeByID(Record[0]);
2911 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2912 BasicBlock *Default = getBasicBlock(Record[2]);
2913 if (!OpTy || !Cond || !Default)
2914 return Error(BitcodeError::InvalidRecord);
2915 unsigned NumCases = (Record.size()-3)/2;
2916 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2917 InstructionList.push_back(SI);
2918 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2919 ConstantInt *CaseVal =
2920 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2921 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2922 if (!CaseVal || !DestBB) {
2924 return Error(BitcodeError::InvalidRecord);
2926 SI->addCase(CaseVal, DestBB);
2931 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2932 if (Record.size() < 2)
2933 return Error(BitcodeError::InvalidRecord);
2934 Type *OpTy = getTypeByID(Record[0]);
2935 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2936 if (!OpTy || !Address)
2937 return Error(BitcodeError::InvalidRecord);
2938 unsigned NumDests = Record.size()-2;
2939 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2940 InstructionList.push_back(IBI);
2941 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2942 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2943 IBI->addDestination(DestBB);
2946 return Error(BitcodeError::InvalidRecord);
2953 case bitc::FUNC_CODE_INST_INVOKE: {
2954 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2955 if (Record.size() < 4)
2956 return Error(BitcodeError::InvalidRecord);
2957 AttributeSet PAL = getAttributes(Record[0]);
2958 unsigned CCInfo = Record[1];
2959 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2960 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2964 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2965 return Error(BitcodeError::InvalidRecord);
2967 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2968 FunctionType *FTy = !CalleeTy ? nullptr :
2969 dyn_cast<FunctionType>(CalleeTy->getElementType());
2971 // Check that the right number of fixed parameters are here.
2972 if (!FTy || !NormalBB || !UnwindBB ||
2973 Record.size() < OpNum+FTy->getNumParams())
2974 return Error(BitcodeError::InvalidRecord);
2976 SmallVector<Value*, 16> Ops;
2977 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2978 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2979 FTy->getParamType(i)));
2981 return Error(BitcodeError::InvalidRecord);
2984 if (!FTy->isVarArg()) {
2985 if (Record.size() != OpNum)
2986 return Error(BitcodeError::InvalidRecord);
2988 // Read type/value pairs for varargs params.
2989 while (OpNum != Record.size()) {
2991 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2992 return Error(BitcodeError::InvalidRecord);
2997 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2998 InstructionList.push_back(I);
2999 cast<InvokeInst>(I)->setCallingConv(
3000 static_cast<CallingConv::ID>(CCInfo));
3001 cast<InvokeInst>(I)->setAttributes(PAL);
3004 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3006 Value *Val = nullptr;
3007 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3008 return Error(BitcodeError::InvalidRecord);
3009 I = ResumeInst::Create(Val);
3010 InstructionList.push_back(I);
3013 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3014 I = new UnreachableInst(Context);
3015 InstructionList.push_back(I);
3017 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3018 if (Record.size() < 1 || ((Record.size()-1)&1))
3019 return Error(BitcodeError::InvalidRecord);
3020 Type *Ty = getTypeByID(Record[0]);
3022 return Error(BitcodeError::InvalidRecord);
3024 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3025 InstructionList.push_back(PN);
3027 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3029 // With the new function encoding, it is possible that operands have
3030 // negative IDs (for forward references). Use a signed VBR
3031 // representation to keep the encoding small.
3033 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3035 V = getValue(Record, 1+i, NextValueNo, Ty);
3036 BasicBlock *BB = getBasicBlock(Record[2+i]);
3038 return Error(BitcodeError::InvalidRecord);
3039 PN->addIncoming(V, BB);
3045 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3046 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3048 if (Record.size() < 4)
3049 return Error(BitcodeError::InvalidRecord);
3050 Type *Ty = getTypeByID(Record[Idx++]);
3052 return Error(BitcodeError::InvalidRecord);
3053 Value *PersFn = nullptr;
3054 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3055 return Error(BitcodeError::InvalidRecord);
3057 bool IsCleanup = !!Record[Idx++];
3058 unsigned NumClauses = Record[Idx++];
3059 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3060 LP->setCleanup(IsCleanup);
3061 for (unsigned J = 0; J != NumClauses; ++J) {
3062 LandingPadInst::ClauseType CT =
3063 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3066 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3068 return Error(BitcodeError::InvalidRecord);
3071 assert((CT != LandingPadInst::Catch ||
3072 !isa<ArrayType>(Val->getType())) &&
3073 "Catch clause has a invalid type!");
3074 assert((CT != LandingPadInst::Filter ||
3075 isa<ArrayType>(Val->getType())) &&
3076 "Filter clause has invalid type!");
3077 LP->addClause(cast<Constant>(Val));
3081 InstructionList.push_back(I);
3085 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3086 if (Record.size() != 4)
3087 return Error(BitcodeError::InvalidRecord);
3089 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3090 Type *OpTy = getTypeByID(Record[1]);
3091 Value *Size = getFnValueByID(Record[2], OpTy);
3092 unsigned AlignRecord = Record[3];
3093 bool InAlloca = AlignRecord & (1 << 5);
3094 unsigned Align = AlignRecord & ((1 << 5) - 1);
3096 return Error(BitcodeError::InvalidRecord);
3097 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3098 AI->setUsedWithInAlloca(InAlloca);
3100 InstructionList.push_back(I);
3103 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3106 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3107 OpNum+2 != Record.size())
3108 return Error(BitcodeError::InvalidRecord);
3110 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3111 InstructionList.push_back(I);
3114 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3115 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3118 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3119 OpNum+4 != Record.size())
3120 return Error(BitcodeError::InvalidRecord);
3122 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3123 if (Ordering == NotAtomic || Ordering == Release ||
3124 Ordering == AcquireRelease)
3125 return Error(BitcodeError::InvalidRecord);
3126 if (Ordering != NotAtomic && Record[OpNum] == 0)
3127 return Error(BitcodeError::InvalidRecord);
3128 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3130 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3131 Ordering, SynchScope);
3132 InstructionList.push_back(I);
3135 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3138 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3139 popValue(Record, OpNum, NextValueNo,
3140 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3141 OpNum+2 != Record.size())
3142 return Error(BitcodeError::InvalidRecord);
3144 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3145 InstructionList.push_back(I);
3148 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3149 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3152 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3153 popValue(Record, OpNum, NextValueNo,
3154 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3155 OpNum+4 != Record.size())
3156 return Error(BitcodeError::InvalidRecord);
3158 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3159 if (Ordering == NotAtomic || Ordering == Acquire ||
3160 Ordering == AcquireRelease)
3161 return Error(BitcodeError::InvalidRecord);
3162 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3163 if (Ordering != NotAtomic && Record[OpNum] == 0)
3164 return Error(BitcodeError::InvalidRecord);
3166 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3167 Ordering, SynchScope);
3168 InstructionList.push_back(I);
3171 case bitc::FUNC_CODE_INST_CMPXCHG: {
3172 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3173 // failureordering?, isweak?]
3175 Value *Ptr, *Cmp, *New;
3176 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3177 popValue(Record, OpNum, NextValueNo,
3178 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3179 popValue(Record, OpNum, NextValueNo,
3180 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3181 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3182 return Error(BitcodeError::InvalidRecord);
3183 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3184 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3185 return Error(BitcodeError::InvalidRecord);
3186 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3188 AtomicOrdering FailureOrdering;
3189 if (Record.size() < 7)
3191 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3193 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3195 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3197 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3199 if (Record.size() < 8) {
3200 // Before weak cmpxchgs existed, the instruction simply returned the
3201 // value loaded from memory, so bitcode files from that era will be
3202 // expecting the first component of a modern cmpxchg.
3203 CurBB->getInstList().push_back(I);
3204 I = ExtractValueInst::Create(I, 0);
3206 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3209 InstructionList.push_back(I);
3212 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3213 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3216 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3217 popValue(Record, OpNum, NextValueNo,
3218 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3219 OpNum+4 != Record.size())
3220 return Error(BitcodeError::InvalidRecord);
3221 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3222 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3223 Operation > AtomicRMWInst::LAST_BINOP)
3224 return Error(BitcodeError::InvalidRecord);
3225 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3226 if (Ordering == NotAtomic || Ordering == Unordered)
3227 return Error(BitcodeError::InvalidRecord);
3228 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3229 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3230 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3231 InstructionList.push_back(I);
3234 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3235 if (2 != Record.size())
3236 return Error(BitcodeError::InvalidRecord);
3237 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3238 if (Ordering == NotAtomic || Ordering == Unordered ||
3239 Ordering == Monotonic)
3240 return Error(BitcodeError::InvalidRecord);
3241 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3242 I = new FenceInst(Context, Ordering, SynchScope);
3243 InstructionList.push_back(I);
3246 case bitc::FUNC_CODE_INST_CALL: {
3247 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3248 if (Record.size() < 3)
3249 return Error(BitcodeError::InvalidRecord);
3251 AttributeSet PAL = getAttributes(Record[0]);
3252 unsigned CCInfo = Record[1];
3256 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3257 return Error(BitcodeError::InvalidRecord);
3259 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3260 FunctionType *FTy = nullptr;
3261 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3262 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3263 return Error(BitcodeError::InvalidRecord);
3265 SmallVector<Value*, 16> Args;
3266 // Read the fixed params.
3267 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3268 if (FTy->getParamType(i)->isLabelTy())
3269 Args.push_back(getBasicBlock(Record[OpNum]));
3271 Args.push_back(getValue(Record, OpNum, NextValueNo,
3272 FTy->getParamType(i)));
3274 return Error(BitcodeError::InvalidRecord);
3277 // Read type/value pairs for varargs params.
3278 if (!FTy->isVarArg()) {
3279 if (OpNum != Record.size())
3280 return Error(BitcodeError::InvalidRecord);
3282 while (OpNum != Record.size()) {
3284 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3285 return Error(BitcodeError::InvalidRecord);
3290 I = CallInst::Create(Callee, Args);
3291 InstructionList.push_back(I);
3292 cast<CallInst>(I)->setCallingConv(
3293 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3294 CallInst::TailCallKind TCK = CallInst::TCK_None;
3296 TCK = CallInst::TCK_Tail;
3297 if (CCInfo & (1 << 14))
3298 TCK = CallInst::TCK_MustTail;
3299 cast<CallInst>(I)->setTailCallKind(TCK);
3300 cast<CallInst>(I)->setAttributes(PAL);
3303 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3304 if (Record.size() < 3)
3305 return Error(BitcodeError::InvalidRecord);
3306 Type *OpTy = getTypeByID(Record[0]);
3307 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3308 Type *ResTy = getTypeByID(Record[2]);
3309 if (!OpTy || !Op || !ResTy)
3310 return Error(BitcodeError::InvalidRecord);
3311 I = new VAArgInst(Op, ResTy);
3312 InstructionList.push_back(I);
3317 // Add instruction to end of current BB. If there is no current BB, reject
3321 return Error(BitcodeError::InvalidInstructionWithNoBB);
3323 CurBB->getInstList().push_back(I);
3325 // If this was a terminator instruction, move to the next block.
3326 if (isa<TerminatorInst>(I)) {
3328 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3331 // Non-void values get registered in the value table for future use.
3332 if (I && !I->getType()->isVoidTy())
3333 ValueList.AssignValue(I, NextValueNo++);
3338 // Check the function list for unresolved values.
3339 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3340 if (!A->getParent()) {
3341 // We found at least one unresolved value. Nuke them all to avoid leaks.
3342 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3343 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3344 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3348 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3352 // FIXME: Check for unresolved forward-declared metadata references
3353 // and clean up leaks.
3355 // Trim the value list down to the size it was before we parsed this function.
3356 ValueList.shrinkTo(ModuleValueListSize);
3357 MDValueList.shrinkTo(ModuleMDValueListSize);
3358 std::vector<BasicBlock*>().swap(FunctionBBs);
3359 return std::error_code();
3362 /// Find the function body in the bitcode stream
3363 std::error_code BitcodeReader::FindFunctionInStream(
3365 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3366 while (DeferredFunctionInfoIterator->second == 0) {
3367 if (Stream.AtEndOfStream())
3368 return Error(BitcodeError::CouldNotFindFunctionInStream);
3369 // ParseModule will parse the next body in the stream and set its
3370 // position in the DeferredFunctionInfo map.
3371 if (std::error_code EC = ParseModule(true))
3374 return std::error_code();
3377 //===----------------------------------------------------------------------===//
3378 // GVMaterializer implementation
3379 //===----------------------------------------------------------------------===//
3381 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3383 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3384 Function *F = dyn_cast<Function>(GV);
3385 // If it's not a function or is already material, ignore the request.
3386 if (!F || !F->isMaterializable())
3387 return std::error_code();
3389 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3390 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3391 // If its position is recorded as 0, its body is somewhere in the stream
3392 // but we haven't seen it yet.
3393 if (DFII->second == 0 && LazyStreamer)
3394 if (std::error_code EC = FindFunctionInStream(F, DFII))
3397 // Move the bit stream to the saved position of the deferred function body.
3398 Stream.JumpToBit(DFII->second);
3400 if (std::error_code EC = ParseFunctionBody(F))
3402 F->setIsMaterializable(false);
3404 // Upgrade any old intrinsic calls in the function.
3405 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3406 E = UpgradedIntrinsics.end(); I != E; ++I) {
3407 if (I->first != I->second) {
3408 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3410 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3411 UpgradeIntrinsicCall(CI, I->second);
3416 // Bring in any functions that this function forward-referenced via
3418 return materializeForwardReferencedFunctions();
3421 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3422 const Function *F = dyn_cast<Function>(GV);
3423 if (!F || F->isDeclaration())
3426 // Dematerializing F would leave dangling references that wouldn't be
3427 // reconnected on re-materialization.
3428 if (BlockAddressesTaken.count(F))
3431 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3434 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3435 Function *F = dyn_cast<Function>(GV);
3436 // If this function isn't dematerializable, this is a noop.
3437 if (!F || !isDematerializable(F))
3440 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3442 // Just forget the function body, we can remat it later.
3443 F->dropAllReferences();
3444 F->setIsMaterializable(true);
3447 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3448 assert(M == TheModule &&
3449 "Can only Materialize the Module this BitcodeReader is attached to.");
3451 // Promise to materialize all forward references.
3452 WillMaterializeAllForwardRefs = true;
3454 // Iterate over the module, deserializing any functions that are still on
3456 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3458 if (std::error_code EC = materialize(F))
3461 // At this point, if there are any function bodies, the current bit is
3462 // pointing to the END_BLOCK record after them. Now make sure the rest
3463 // of the bits in the module have been read.
3467 // Check that all block address forward references got resolved (as we
3469 if (!BasicBlockFwdRefs.empty())
3470 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3472 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3473 // delete the old functions to clean up. We can't do this unless the entire
3474 // module is materialized because there could always be another function body
3475 // with calls to the old function.
3476 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3477 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3478 if (I->first != I->second) {
3479 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3481 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3482 UpgradeIntrinsicCall(CI, I->second);
3484 if (!I->first->use_empty())
3485 I->first->replaceAllUsesWith(I->second);
3486 I->first->eraseFromParent();
3489 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3491 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3492 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3494 UpgradeDebugInfo(*M);
3495 return std::error_code();
3498 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3499 return IdentifiedStructTypes;
3502 std::error_code BitcodeReader::InitStream() {
3504 return InitLazyStream();
3505 return InitStreamFromBuffer();
3508 std::error_code BitcodeReader::InitStreamFromBuffer() {
3509 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3510 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3512 if (Buffer->getBufferSize() & 3)
3513 return Error(BitcodeError::InvalidBitcodeSignature);
3515 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3516 // The magic number is 0x0B17C0DE stored in little endian.
3517 if (isBitcodeWrapper(BufPtr, BufEnd))
3518 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3519 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3521 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3522 Stream.init(&*StreamFile);
3524 return std::error_code();
3527 std::error_code BitcodeReader::InitLazyStream() {
3528 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3530 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3531 StreamFile.reset(new BitstreamReader(Bytes));
3532 Stream.init(&*StreamFile);
3534 unsigned char buf[16];
3535 if (Bytes->readBytes(buf, 16, 0) != 16)
3536 return Error(BitcodeError::InvalidBitcodeSignature);
3538 if (!isBitcode(buf, buf + 16))
3539 return Error(BitcodeError::InvalidBitcodeSignature);
3541 if (isBitcodeWrapper(buf, buf + 4)) {
3542 const unsigned char *bitcodeStart = buf;
3543 const unsigned char *bitcodeEnd = buf + 16;
3544 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3545 Bytes->dropLeadingBytes(bitcodeStart - buf);
3546 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3548 return std::error_code();
3552 class BitcodeErrorCategoryType : public std::error_category {
3553 const char *name() const LLVM_NOEXCEPT override {
3554 return "llvm.bitcode";
3556 std::string message(int IE) const override {
3557 BitcodeError E = static_cast<BitcodeError>(IE);
3559 case BitcodeError::ConflictingMETADATA_KINDRecords:
3560 return "Conflicting METADATA_KIND records";
3561 case BitcodeError::CouldNotFindFunctionInStream:
3562 return "Could not find function in stream";
3563 case BitcodeError::ExpectedConstant:
3564 return "Expected a constant";
3565 case BitcodeError::InsufficientFunctionProtos:
3566 return "Insufficient function protos";
3567 case BitcodeError::InvalidBitcodeSignature:
3568 return "Invalid bitcode signature";
3569 case BitcodeError::InvalidBitcodeWrapperHeader:
3570 return "Invalid bitcode wrapper header";
3571 case BitcodeError::InvalidConstantReference:
3572 return "Invalid ronstant reference";
3573 case BitcodeError::InvalidID:
3574 return "Invalid ID";
3575 case BitcodeError::InvalidInstructionWithNoBB:
3576 return "Invalid instruction with no BB";
3577 case BitcodeError::InvalidRecord:
3578 return "Invalid record";
3579 case BitcodeError::InvalidTypeForValue:
3580 return "Invalid type for value";
3581 case BitcodeError::InvalidTYPETable:
3582 return "Invalid TYPE table";
3583 case BitcodeError::InvalidType:
3584 return "Invalid type";
3585 case BitcodeError::MalformedBlock:
3586 return "Malformed block";
3587 case BitcodeError::MalformedGlobalInitializerSet:
3588 return "Malformed global initializer set";
3589 case BitcodeError::InvalidMultipleBlocks:
3590 return "Invalid multiple blocks";
3591 case BitcodeError::NeverResolvedValueFoundInFunction:
3592 return "Never resolved value found in function";
3593 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3594 return "Never resolved function from blockaddress";
3595 case BitcodeError::InvalidValue:
3596 return "Invalid value";
3598 llvm_unreachable("Unknown error type!");
3603 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3605 const std::error_category &llvm::BitcodeErrorCategory() {
3606 return *ErrorCategory;
3609 //===----------------------------------------------------------------------===//
3610 // External interface
3611 //===----------------------------------------------------------------------===//
3613 /// \brief Get a lazy one-at-time loading module from bitcode.
3615 /// This isn't always used in a lazy context. In particular, it's also used by
3616 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3617 /// in forward-referenced functions from block address references.
3619 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3620 /// materialize everything -- in particular, if this isn't truly lazy.
3621 static ErrorOr<Module *>
3622 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3623 LLVMContext &Context, bool WillMaterializeAll) {
3624 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3625 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3626 M->setMaterializer(R);
3628 auto cleanupOnError = [&](std::error_code EC) {
3629 R->releaseBuffer(); // Never take ownership on error.
3630 delete M; // Also deletes R.
3634 if (std::error_code EC = R->ParseBitcodeInto(M))
3635 return cleanupOnError(EC);
3637 if (!WillMaterializeAll)
3638 // Resolve forward references from blockaddresses.
3639 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3640 return cleanupOnError(EC);
3642 Buffer.release(); // The BitcodeReader owns it now.
3647 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3648 LLVMContext &Context) {
3649 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3652 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3653 DataStreamer *streamer,
3654 LLVMContext &Context,
3655 std::string *ErrMsg) {
3656 Module *M = new Module(name, Context);
3657 BitcodeReader *R = new BitcodeReader(streamer, Context);
3658 M->setMaterializer(R);
3659 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3661 *ErrMsg = EC.message();
3662 delete M; // Also deletes R.
3668 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3669 LLVMContext &Context) {
3670 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3671 ErrorOr<Module *> ModuleOrErr =
3672 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3675 Module *M = ModuleOrErr.get();
3676 // Read in the entire module, and destroy the BitcodeReader.
3677 if (std::error_code EC = M->materializeAllPermanently()) {
3682 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3683 // written. We must defer until the Module has been fully materialized.
3688 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3689 LLVMContext &Context) {
3690 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3691 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3692 ErrorOr<std::string> Triple = R->parseTriple();
3693 if (Triple.getError())
3695 return Triple.get();