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(Value *V, unsigned Idx) {
450 WeakVH &OldV = MDValuePtrs[Idx];
456 // If there was a forward reference to this value, replace it.
457 MDNode *PrevVal = cast<MDNode>(OldV);
458 OldV->replaceAllUsesWith(V);
459 MDNode::deleteTemporary(PrevVal);
460 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
462 MDValuePtrs[Idx] = V;
465 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
469 if (Value *V = MDValuePtrs[Idx]) {
470 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
474 // Create and return a placeholder, which will later be RAUW'd.
475 Value *V = MDNode::getTemporary(Context, None);
476 MDValuePtrs[Idx] = V;
480 Type *BitcodeReader::getTypeByID(unsigned ID) {
481 // The type table size is always specified correctly.
482 if (ID >= TypeList.size())
485 if (Type *Ty = TypeList[ID])
488 // If we have a forward reference, the only possible case is when it is to a
489 // named struct. Just create a placeholder for now.
490 return TypeList[ID] = createIdentifiedStructType(Context);
493 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
495 auto *Ret = StructType::create(Context, Name);
496 IdentifiedStructTypes.push_back(Ret);
500 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
501 auto *Ret = StructType::create(Context);
502 IdentifiedStructTypes.push_back(Ret);
507 //===----------------------------------------------------------------------===//
508 // Functions for parsing blocks from the bitcode file
509 //===----------------------------------------------------------------------===//
512 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
513 /// been decoded from the given integer. This function must stay in sync with
514 /// 'encodeLLVMAttributesForBitcode'.
515 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
516 uint64_t EncodedAttrs) {
517 // FIXME: Remove in 4.0.
519 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
520 // the bits above 31 down by 11 bits.
521 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
522 assert((!Alignment || isPowerOf2_32(Alignment)) &&
523 "Alignment must be a power of two.");
526 B.addAlignmentAttr(Alignment);
527 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
528 (EncodedAttrs & 0xffff));
531 std::error_code BitcodeReader::ParseAttributeBlock() {
532 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
533 return Error(BitcodeError::InvalidRecord);
535 if (!MAttributes.empty())
536 return Error(BitcodeError::InvalidMultipleBlocks);
538 SmallVector<uint64_t, 64> Record;
540 SmallVector<AttributeSet, 8> Attrs;
542 // Read all the records.
544 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
546 switch (Entry.Kind) {
547 case BitstreamEntry::SubBlock: // Handled for us already.
548 case BitstreamEntry::Error:
549 return Error(BitcodeError::MalformedBlock);
550 case BitstreamEntry::EndBlock:
551 return std::error_code();
552 case BitstreamEntry::Record:
553 // The interesting case.
559 switch (Stream.readRecord(Entry.ID, Record)) {
560 default: // Default behavior: ignore.
562 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
563 // FIXME: Remove in 4.0.
564 if (Record.size() & 1)
565 return Error(BitcodeError::InvalidRecord);
567 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
569 decodeLLVMAttributesForBitcode(B, Record[i+1]);
570 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
573 MAttributes.push_back(AttributeSet::get(Context, Attrs));
577 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
578 for (unsigned i = 0, e = Record.size(); i != e; ++i)
579 Attrs.push_back(MAttributeGroups[Record[i]]);
581 MAttributes.push_back(AttributeSet::get(Context, Attrs));
589 // Returns Attribute::None on unrecognized codes.
590 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
593 return Attribute::None;
594 case bitc::ATTR_KIND_ALIGNMENT:
595 return Attribute::Alignment;
596 case bitc::ATTR_KIND_ALWAYS_INLINE:
597 return Attribute::AlwaysInline;
598 case bitc::ATTR_KIND_BUILTIN:
599 return Attribute::Builtin;
600 case bitc::ATTR_KIND_BY_VAL:
601 return Attribute::ByVal;
602 case bitc::ATTR_KIND_IN_ALLOCA:
603 return Attribute::InAlloca;
604 case bitc::ATTR_KIND_COLD:
605 return Attribute::Cold;
606 case bitc::ATTR_KIND_INLINE_HINT:
607 return Attribute::InlineHint;
608 case bitc::ATTR_KIND_IN_REG:
609 return Attribute::InReg;
610 case bitc::ATTR_KIND_JUMP_TABLE:
611 return Attribute::JumpTable;
612 case bitc::ATTR_KIND_MIN_SIZE:
613 return Attribute::MinSize;
614 case bitc::ATTR_KIND_NAKED:
615 return Attribute::Naked;
616 case bitc::ATTR_KIND_NEST:
617 return Attribute::Nest;
618 case bitc::ATTR_KIND_NO_ALIAS:
619 return Attribute::NoAlias;
620 case bitc::ATTR_KIND_NO_BUILTIN:
621 return Attribute::NoBuiltin;
622 case bitc::ATTR_KIND_NO_CAPTURE:
623 return Attribute::NoCapture;
624 case bitc::ATTR_KIND_NO_DUPLICATE:
625 return Attribute::NoDuplicate;
626 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
627 return Attribute::NoImplicitFloat;
628 case bitc::ATTR_KIND_NO_INLINE:
629 return Attribute::NoInline;
630 case bitc::ATTR_KIND_NON_LAZY_BIND:
631 return Attribute::NonLazyBind;
632 case bitc::ATTR_KIND_NON_NULL:
633 return Attribute::NonNull;
634 case bitc::ATTR_KIND_DEREFERENCEABLE:
635 return Attribute::Dereferenceable;
636 case bitc::ATTR_KIND_NO_RED_ZONE:
637 return Attribute::NoRedZone;
638 case bitc::ATTR_KIND_NO_RETURN:
639 return Attribute::NoReturn;
640 case bitc::ATTR_KIND_NO_UNWIND:
641 return Attribute::NoUnwind;
642 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
643 return Attribute::OptimizeForSize;
644 case bitc::ATTR_KIND_OPTIMIZE_NONE:
645 return Attribute::OptimizeNone;
646 case bitc::ATTR_KIND_READ_NONE:
647 return Attribute::ReadNone;
648 case bitc::ATTR_KIND_READ_ONLY:
649 return Attribute::ReadOnly;
650 case bitc::ATTR_KIND_RETURNED:
651 return Attribute::Returned;
652 case bitc::ATTR_KIND_RETURNS_TWICE:
653 return Attribute::ReturnsTwice;
654 case bitc::ATTR_KIND_S_EXT:
655 return Attribute::SExt;
656 case bitc::ATTR_KIND_STACK_ALIGNMENT:
657 return Attribute::StackAlignment;
658 case bitc::ATTR_KIND_STACK_PROTECT:
659 return Attribute::StackProtect;
660 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
661 return Attribute::StackProtectReq;
662 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
663 return Attribute::StackProtectStrong;
664 case bitc::ATTR_KIND_STRUCT_RET:
665 return Attribute::StructRet;
666 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
667 return Attribute::SanitizeAddress;
668 case bitc::ATTR_KIND_SANITIZE_THREAD:
669 return Attribute::SanitizeThread;
670 case bitc::ATTR_KIND_SANITIZE_MEMORY:
671 return Attribute::SanitizeMemory;
672 case bitc::ATTR_KIND_UW_TABLE:
673 return Attribute::UWTable;
674 case bitc::ATTR_KIND_Z_EXT:
675 return Attribute::ZExt;
679 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
680 Attribute::AttrKind *Kind) {
681 *Kind = GetAttrFromCode(Code);
682 if (*Kind == Attribute::None)
683 return Error(BitcodeError::InvalidValue);
684 return std::error_code();
687 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
688 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
689 return Error(BitcodeError::InvalidRecord);
691 if (!MAttributeGroups.empty())
692 return Error(BitcodeError::InvalidMultipleBlocks);
694 SmallVector<uint64_t, 64> Record;
696 // Read all the records.
698 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
700 switch (Entry.Kind) {
701 case BitstreamEntry::SubBlock: // Handled for us already.
702 case BitstreamEntry::Error:
703 return Error(BitcodeError::MalformedBlock);
704 case BitstreamEntry::EndBlock:
705 return std::error_code();
706 case BitstreamEntry::Record:
707 // The interesting case.
713 switch (Stream.readRecord(Entry.ID, Record)) {
714 default: // Default behavior: ignore.
716 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
717 if (Record.size() < 3)
718 return Error(BitcodeError::InvalidRecord);
720 uint64_t GrpID = Record[0];
721 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
724 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
725 if (Record[i] == 0) { // Enum attribute
726 Attribute::AttrKind Kind;
727 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
730 B.addAttribute(Kind);
731 } else if (Record[i] == 1) { // Integer attribute
732 Attribute::AttrKind Kind;
733 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
735 if (Kind == Attribute::Alignment)
736 B.addAlignmentAttr(Record[++i]);
737 else if (Kind == Attribute::StackAlignment)
738 B.addStackAlignmentAttr(Record[++i]);
739 else if (Kind == Attribute::Dereferenceable)
740 B.addDereferenceableAttr(Record[++i]);
741 } else { // String attribute
742 assert((Record[i] == 3 || Record[i] == 4) &&
743 "Invalid attribute group entry");
744 bool HasValue = (Record[i++] == 4);
745 SmallString<64> KindStr;
746 SmallString<64> ValStr;
748 while (Record[i] != 0 && i != e)
749 KindStr += Record[i++];
750 assert(Record[i] == 0 && "Kind string not null terminated");
753 // Has a value associated with it.
754 ++i; // Skip the '0' that terminates the "kind" string.
755 while (Record[i] != 0 && i != e)
756 ValStr += Record[i++];
757 assert(Record[i] == 0 && "Value string not null terminated");
760 B.addAttribute(KindStr.str(), ValStr.str());
764 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
771 std::error_code BitcodeReader::ParseTypeTable() {
772 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
773 return Error(BitcodeError::InvalidRecord);
775 return ParseTypeTableBody();
778 std::error_code BitcodeReader::ParseTypeTableBody() {
779 if (!TypeList.empty())
780 return Error(BitcodeError::InvalidMultipleBlocks);
782 SmallVector<uint64_t, 64> Record;
783 unsigned NumRecords = 0;
785 SmallString<64> TypeName;
787 // Read all the records for this type table.
789 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
791 switch (Entry.Kind) {
792 case BitstreamEntry::SubBlock: // Handled for us already.
793 case BitstreamEntry::Error:
794 return Error(BitcodeError::MalformedBlock);
795 case BitstreamEntry::EndBlock:
796 if (NumRecords != TypeList.size())
797 return Error(BitcodeError::MalformedBlock);
798 return std::error_code();
799 case BitstreamEntry::Record:
800 // The interesting case.
806 Type *ResultTy = nullptr;
807 switch (Stream.readRecord(Entry.ID, Record)) {
809 return Error(BitcodeError::InvalidValue);
810 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
811 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
812 // type list. This allows us to reserve space.
813 if (Record.size() < 1)
814 return Error(BitcodeError::InvalidRecord);
815 TypeList.resize(Record[0]);
817 case bitc::TYPE_CODE_VOID: // VOID
818 ResultTy = Type::getVoidTy(Context);
820 case bitc::TYPE_CODE_HALF: // HALF
821 ResultTy = Type::getHalfTy(Context);
823 case bitc::TYPE_CODE_FLOAT: // FLOAT
824 ResultTy = Type::getFloatTy(Context);
826 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
827 ResultTy = Type::getDoubleTy(Context);
829 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
830 ResultTy = Type::getX86_FP80Ty(Context);
832 case bitc::TYPE_CODE_FP128: // FP128
833 ResultTy = Type::getFP128Ty(Context);
835 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
836 ResultTy = Type::getPPC_FP128Ty(Context);
838 case bitc::TYPE_CODE_LABEL: // LABEL
839 ResultTy = Type::getLabelTy(Context);
841 case bitc::TYPE_CODE_METADATA: // METADATA
842 ResultTy = Type::getMetadataTy(Context);
844 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
845 ResultTy = Type::getX86_MMXTy(Context);
847 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
848 if (Record.size() < 1)
849 return Error(BitcodeError::InvalidRecord);
851 ResultTy = IntegerType::get(Context, Record[0]);
853 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
854 // [pointee type, address space]
855 if (Record.size() < 1)
856 return Error(BitcodeError::InvalidRecord);
857 unsigned AddressSpace = 0;
858 if (Record.size() == 2)
859 AddressSpace = Record[1];
860 ResultTy = getTypeByID(Record[0]);
862 return Error(BitcodeError::InvalidType);
863 ResultTy = PointerType::get(ResultTy, AddressSpace);
866 case bitc::TYPE_CODE_FUNCTION_OLD: {
867 // FIXME: attrid is dead, remove it in LLVM 4.0
868 // FUNCTION: [vararg, attrid, retty, paramty x N]
869 if (Record.size() < 3)
870 return Error(BitcodeError::InvalidRecord);
871 SmallVector<Type*, 8> ArgTys;
872 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
873 if (Type *T = getTypeByID(Record[i]))
879 ResultTy = getTypeByID(Record[2]);
880 if (!ResultTy || ArgTys.size() < Record.size()-3)
881 return Error(BitcodeError::InvalidType);
883 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
886 case bitc::TYPE_CODE_FUNCTION: {
887 // FUNCTION: [vararg, retty, paramty x N]
888 if (Record.size() < 2)
889 return Error(BitcodeError::InvalidRecord);
890 SmallVector<Type*, 8> ArgTys;
891 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
892 if (Type *T = getTypeByID(Record[i]))
898 ResultTy = getTypeByID(Record[1]);
899 if (!ResultTy || ArgTys.size() < Record.size()-2)
900 return Error(BitcodeError::InvalidType);
902 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
905 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
906 if (Record.size() < 1)
907 return Error(BitcodeError::InvalidRecord);
908 SmallVector<Type*, 8> EltTys;
909 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
910 if (Type *T = getTypeByID(Record[i]))
915 if (EltTys.size() != Record.size()-1)
916 return Error(BitcodeError::InvalidType);
917 ResultTy = StructType::get(Context, EltTys, Record[0]);
920 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
921 if (ConvertToString(Record, 0, TypeName))
922 return Error(BitcodeError::InvalidRecord);
925 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
926 if (Record.size() < 1)
927 return Error(BitcodeError::InvalidRecord);
929 if (NumRecords >= TypeList.size())
930 return Error(BitcodeError::InvalidTYPETable);
932 // Check to see if this was forward referenced, if so fill in the temp.
933 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
935 Res->setName(TypeName);
936 TypeList[NumRecords] = nullptr;
937 } else // Otherwise, create a new struct.
938 Res = createIdentifiedStructType(Context, TypeName);
941 SmallVector<Type*, 8> EltTys;
942 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
943 if (Type *T = getTypeByID(Record[i]))
948 if (EltTys.size() != Record.size()-1)
949 return Error(BitcodeError::InvalidRecord);
950 Res->setBody(EltTys, Record[0]);
954 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
955 if (Record.size() != 1)
956 return Error(BitcodeError::InvalidRecord);
958 if (NumRecords >= TypeList.size())
959 return Error(BitcodeError::InvalidTYPETable);
961 // Check to see if this was forward referenced, if so fill in the temp.
962 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
964 Res->setName(TypeName);
965 TypeList[NumRecords] = nullptr;
966 } else // Otherwise, create a new struct with no body.
967 Res = createIdentifiedStructType(Context, TypeName);
972 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
973 if (Record.size() < 2)
974 return Error(BitcodeError::InvalidRecord);
975 if ((ResultTy = getTypeByID(Record[1])))
976 ResultTy = ArrayType::get(ResultTy, Record[0]);
978 return Error(BitcodeError::InvalidType);
980 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
981 if (Record.size() < 2)
982 return Error(BitcodeError::InvalidRecord);
983 if ((ResultTy = getTypeByID(Record[1])))
984 ResultTy = VectorType::get(ResultTy, Record[0]);
986 return Error(BitcodeError::InvalidType);
990 if (NumRecords >= TypeList.size())
991 return Error(BitcodeError::InvalidTYPETable);
992 assert(ResultTy && "Didn't read a type?");
993 assert(!TypeList[NumRecords] && "Already read type?");
994 TypeList[NumRecords++] = ResultTy;
998 std::error_code BitcodeReader::ParseValueSymbolTable() {
999 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1000 return Error(BitcodeError::InvalidRecord);
1002 SmallVector<uint64_t, 64> Record;
1004 // Read all the records for this value table.
1005 SmallString<128> ValueName;
1007 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1009 switch (Entry.Kind) {
1010 case BitstreamEntry::SubBlock: // Handled for us already.
1011 case BitstreamEntry::Error:
1012 return Error(BitcodeError::MalformedBlock);
1013 case BitstreamEntry::EndBlock:
1014 return std::error_code();
1015 case BitstreamEntry::Record:
1016 // The interesting case.
1022 switch (Stream.readRecord(Entry.ID, Record)) {
1023 default: // Default behavior: unknown type.
1025 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1026 if (ConvertToString(Record, 1, ValueName))
1027 return Error(BitcodeError::InvalidRecord);
1028 unsigned ValueID = Record[0];
1029 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1030 return Error(BitcodeError::InvalidRecord);
1031 Value *V = ValueList[ValueID];
1033 V->setName(StringRef(ValueName.data(), ValueName.size()));
1037 case bitc::VST_CODE_BBENTRY: {
1038 if (ConvertToString(Record, 1, ValueName))
1039 return Error(BitcodeError::InvalidRecord);
1040 BasicBlock *BB = getBasicBlock(Record[0]);
1042 return Error(BitcodeError::InvalidRecord);
1044 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1052 std::error_code BitcodeReader::ParseMetadata() {
1053 unsigned NextMDValueNo = MDValueList.size();
1055 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1056 return Error(BitcodeError::InvalidRecord);
1058 SmallVector<uint64_t, 64> Record;
1060 // Read all the records.
1062 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1064 switch (Entry.Kind) {
1065 case BitstreamEntry::SubBlock: // Handled for us already.
1066 case BitstreamEntry::Error:
1067 return Error(BitcodeError::MalformedBlock);
1068 case BitstreamEntry::EndBlock:
1069 return std::error_code();
1070 case BitstreamEntry::Record:
1071 // The interesting case.
1075 bool IsFunctionLocal = false;
1078 unsigned Code = Stream.readRecord(Entry.ID, Record);
1080 default: // Default behavior: ignore.
1082 case bitc::METADATA_NAME: {
1083 // Read name of the named metadata.
1084 SmallString<8> Name(Record.begin(), Record.end());
1086 Code = Stream.ReadCode();
1088 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1089 unsigned NextBitCode = Stream.readRecord(Code, Record);
1090 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1092 // Read named metadata elements.
1093 unsigned Size = Record.size();
1094 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1095 for (unsigned i = 0; i != Size; ++i) {
1096 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1098 return Error(BitcodeError::InvalidRecord);
1099 NMD->addOperand(MD);
1103 case bitc::METADATA_FN_NODE:
1104 IsFunctionLocal = true;
1106 case bitc::METADATA_NODE: {
1107 if (Record.size() % 2 == 1)
1108 return Error(BitcodeError::InvalidRecord);
1110 unsigned Size = Record.size();
1111 SmallVector<Value*, 8> Elts;
1112 for (unsigned i = 0; i != Size; i += 2) {
1113 Type *Ty = getTypeByID(Record[i]);
1115 return Error(BitcodeError::InvalidRecord);
1116 if (Ty->isMetadataTy())
1117 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1118 else if (!Ty->isVoidTy())
1119 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1121 Elts.push_back(nullptr);
1123 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1124 IsFunctionLocal = false;
1125 MDValueList.AssignValue(V, NextMDValueNo++);
1128 case bitc::METADATA_STRING: {
1129 std::string String(Record.begin(), Record.end());
1130 llvm::UpgradeMDStringConstant(String);
1131 Value *V = MDString::get(Context, String);
1132 MDValueList.AssignValue(V, NextMDValueNo++);
1135 case bitc::METADATA_KIND: {
1136 if (Record.size() < 2)
1137 return Error(BitcodeError::InvalidRecord);
1139 unsigned Kind = Record[0];
1140 SmallString<8> Name(Record.begin()+1, Record.end());
1142 unsigned NewKind = TheModule->getMDKindID(Name.str());
1143 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1144 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1151 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1152 /// the LSB for dense VBR encoding.
1153 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1158 // There is no such thing as -0 with integers. "-0" really means MININT.
1162 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1163 /// values and aliases that we can.
1164 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1165 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1166 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1167 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1168 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1170 GlobalInitWorklist.swap(GlobalInits);
1171 AliasInitWorklist.swap(AliasInits);
1172 FunctionPrefixWorklist.swap(FunctionPrefixes);
1173 FunctionPrologueWorklist.swap(FunctionPrologues);
1175 while (!GlobalInitWorklist.empty()) {
1176 unsigned ValID = GlobalInitWorklist.back().second;
1177 if (ValID >= ValueList.size()) {
1178 // Not ready to resolve this yet, it requires something later in the file.
1179 GlobalInits.push_back(GlobalInitWorklist.back());
1181 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1182 GlobalInitWorklist.back().first->setInitializer(C);
1184 return Error(BitcodeError::ExpectedConstant);
1186 GlobalInitWorklist.pop_back();
1189 while (!AliasInitWorklist.empty()) {
1190 unsigned ValID = AliasInitWorklist.back().second;
1191 if (ValID >= ValueList.size()) {
1192 AliasInits.push_back(AliasInitWorklist.back());
1194 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1195 AliasInitWorklist.back().first->setAliasee(C);
1197 return Error(BitcodeError::ExpectedConstant);
1199 AliasInitWorklist.pop_back();
1202 while (!FunctionPrefixWorklist.empty()) {
1203 unsigned ValID = FunctionPrefixWorklist.back().second;
1204 if (ValID >= ValueList.size()) {
1205 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1207 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1208 FunctionPrefixWorklist.back().first->setPrefixData(C);
1210 return Error(BitcodeError::ExpectedConstant);
1212 FunctionPrefixWorklist.pop_back();
1215 while (!FunctionPrologueWorklist.empty()) {
1216 unsigned ValID = FunctionPrologueWorklist.back().second;
1217 if (ValID >= ValueList.size()) {
1218 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1220 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1221 FunctionPrologueWorklist.back().first->setPrologueData(C);
1223 return Error(BitcodeError::ExpectedConstant);
1225 FunctionPrologueWorklist.pop_back();
1228 return std::error_code();
1231 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1232 SmallVector<uint64_t, 8> Words(Vals.size());
1233 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1234 BitcodeReader::decodeSignRotatedValue);
1236 return APInt(TypeBits, Words);
1239 std::error_code BitcodeReader::ParseConstants() {
1240 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1241 return Error(BitcodeError::InvalidRecord);
1243 SmallVector<uint64_t, 64> Record;
1245 // Read all the records for this value table.
1246 Type *CurTy = Type::getInt32Ty(Context);
1247 unsigned NextCstNo = ValueList.size();
1249 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1251 switch (Entry.Kind) {
1252 case BitstreamEntry::SubBlock: // Handled for us already.
1253 case BitstreamEntry::Error:
1254 return Error(BitcodeError::MalformedBlock);
1255 case BitstreamEntry::EndBlock:
1256 if (NextCstNo != ValueList.size())
1257 return Error(BitcodeError::InvalidConstantReference);
1259 // Once all the constants have been read, go through and resolve forward
1261 ValueList.ResolveConstantForwardRefs();
1262 return std::error_code();
1263 case BitstreamEntry::Record:
1264 // The interesting case.
1271 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1273 default: // Default behavior: unknown constant
1274 case bitc::CST_CODE_UNDEF: // UNDEF
1275 V = UndefValue::get(CurTy);
1277 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1279 return Error(BitcodeError::InvalidRecord);
1280 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1281 return Error(BitcodeError::InvalidRecord);
1282 CurTy = TypeList[Record[0]];
1283 continue; // Skip the ValueList manipulation.
1284 case bitc::CST_CODE_NULL: // NULL
1285 V = Constant::getNullValue(CurTy);
1287 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1288 if (!CurTy->isIntegerTy() || Record.empty())
1289 return Error(BitcodeError::InvalidRecord);
1290 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1292 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1293 if (!CurTy->isIntegerTy() || Record.empty())
1294 return Error(BitcodeError::InvalidRecord);
1296 APInt VInt = ReadWideAPInt(Record,
1297 cast<IntegerType>(CurTy)->getBitWidth());
1298 V = ConstantInt::get(Context, VInt);
1302 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1304 return Error(BitcodeError::InvalidRecord);
1305 if (CurTy->isHalfTy())
1306 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1307 APInt(16, (uint16_t)Record[0])));
1308 else if (CurTy->isFloatTy())
1309 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1310 APInt(32, (uint32_t)Record[0])));
1311 else if (CurTy->isDoubleTy())
1312 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1313 APInt(64, Record[0])));
1314 else if (CurTy->isX86_FP80Ty()) {
1315 // Bits are not stored the same way as a normal i80 APInt, compensate.
1316 uint64_t Rearrange[2];
1317 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1318 Rearrange[1] = Record[0] >> 48;
1319 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1320 APInt(80, Rearrange)));
1321 } else if (CurTy->isFP128Ty())
1322 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1323 APInt(128, Record)));
1324 else if (CurTy->isPPC_FP128Ty())
1325 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1326 APInt(128, Record)));
1328 V = UndefValue::get(CurTy);
1332 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1334 return Error(BitcodeError::InvalidRecord);
1336 unsigned Size = Record.size();
1337 SmallVector<Constant*, 16> Elts;
1339 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1340 for (unsigned i = 0; i != Size; ++i)
1341 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1342 STy->getElementType(i)));
1343 V = ConstantStruct::get(STy, Elts);
1344 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1345 Type *EltTy = ATy->getElementType();
1346 for (unsigned i = 0; i != Size; ++i)
1347 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1348 V = ConstantArray::get(ATy, Elts);
1349 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1350 Type *EltTy = VTy->getElementType();
1351 for (unsigned i = 0; i != Size; ++i)
1352 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1353 V = ConstantVector::get(Elts);
1355 V = UndefValue::get(CurTy);
1359 case bitc::CST_CODE_STRING: // STRING: [values]
1360 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1362 return Error(BitcodeError::InvalidRecord);
1364 SmallString<16> Elts(Record.begin(), Record.end());
1365 V = ConstantDataArray::getString(Context, Elts,
1366 BitCode == bitc::CST_CODE_CSTRING);
1369 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1371 return Error(BitcodeError::InvalidRecord);
1373 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1374 unsigned Size = Record.size();
1376 if (EltTy->isIntegerTy(8)) {
1377 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1378 if (isa<VectorType>(CurTy))
1379 V = ConstantDataVector::get(Context, Elts);
1381 V = ConstantDataArray::get(Context, Elts);
1382 } else if (EltTy->isIntegerTy(16)) {
1383 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1384 if (isa<VectorType>(CurTy))
1385 V = ConstantDataVector::get(Context, Elts);
1387 V = ConstantDataArray::get(Context, Elts);
1388 } else if (EltTy->isIntegerTy(32)) {
1389 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1390 if (isa<VectorType>(CurTy))
1391 V = ConstantDataVector::get(Context, Elts);
1393 V = ConstantDataArray::get(Context, Elts);
1394 } else if (EltTy->isIntegerTy(64)) {
1395 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1396 if (isa<VectorType>(CurTy))
1397 V = ConstantDataVector::get(Context, Elts);
1399 V = ConstantDataArray::get(Context, Elts);
1400 } else if (EltTy->isFloatTy()) {
1401 SmallVector<float, 16> Elts(Size);
1402 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1403 if (isa<VectorType>(CurTy))
1404 V = ConstantDataVector::get(Context, Elts);
1406 V = ConstantDataArray::get(Context, Elts);
1407 } else if (EltTy->isDoubleTy()) {
1408 SmallVector<double, 16> Elts(Size);
1409 std::transform(Record.begin(), Record.end(), Elts.begin(),
1411 if (isa<VectorType>(CurTy))
1412 V = ConstantDataVector::get(Context, Elts);
1414 V = ConstantDataArray::get(Context, Elts);
1416 return Error(BitcodeError::InvalidTypeForValue);
1421 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1422 if (Record.size() < 3)
1423 return Error(BitcodeError::InvalidRecord);
1424 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1426 V = UndefValue::get(CurTy); // Unknown binop.
1428 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1429 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1431 if (Record.size() >= 4) {
1432 if (Opc == Instruction::Add ||
1433 Opc == Instruction::Sub ||
1434 Opc == Instruction::Mul ||
1435 Opc == Instruction::Shl) {
1436 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1437 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1438 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1439 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1440 } else if (Opc == Instruction::SDiv ||
1441 Opc == Instruction::UDiv ||
1442 Opc == Instruction::LShr ||
1443 Opc == Instruction::AShr) {
1444 if (Record[3] & (1 << bitc::PEO_EXACT))
1445 Flags |= SDivOperator::IsExact;
1448 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1452 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1453 if (Record.size() < 3)
1454 return Error(BitcodeError::InvalidRecord);
1455 int Opc = GetDecodedCastOpcode(Record[0]);
1457 V = UndefValue::get(CurTy); // Unknown cast.
1459 Type *OpTy = getTypeByID(Record[1]);
1461 return Error(BitcodeError::InvalidRecord);
1462 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1463 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1464 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1468 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1469 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1470 if (Record.size() & 1)
1471 return Error(BitcodeError::InvalidRecord);
1472 SmallVector<Constant*, 16> Elts;
1473 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1474 Type *ElTy = getTypeByID(Record[i]);
1476 return Error(BitcodeError::InvalidRecord);
1477 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1479 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1480 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1482 bitc::CST_CODE_CE_INBOUNDS_GEP);
1485 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1486 if (Record.size() < 3)
1487 return Error(BitcodeError::InvalidRecord);
1489 Type *SelectorTy = Type::getInt1Ty(Context);
1491 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1492 // vector. Otherwise, it must be a single bit.
1493 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1494 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1495 VTy->getNumElements());
1497 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1499 ValueList.getConstantFwdRef(Record[1],CurTy),
1500 ValueList.getConstantFwdRef(Record[2],CurTy));
1503 case bitc::CST_CODE_CE_EXTRACTELT
1504 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1505 if (Record.size() < 3)
1506 return Error(BitcodeError::InvalidRecord);
1508 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1510 return Error(BitcodeError::InvalidRecord);
1511 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1512 Constant *Op1 = nullptr;
1513 if (Record.size() == 4) {
1514 Type *IdxTy = getTypeByID(Record[2]);
1516 return Error(BitcodeError::InvalidRecord);
1517 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1518 } else // TODO: Remove with llvm 4.0
1519 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1521 return Error(BitcodeError::InvalidRecord);
1522 V = ConstantExpr::getExtractElement(Op0, Op1);
1525 case bitc::CST_CODE_CE_INSERTELT
1526 : { // CE_INSERTELT: [opval, opval, opty, opval]
1527 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1528 if (Record.size() < 3 || !OpTy)
1529 return Error(BitcodeError::InvalidRecord);
1530 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1531 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1532 OpTy->getElementType());
1533 Constant *Op2 = nullptr;
1534 if (Record.size() == 4) {
1535 Type *IdxTy = getTypeByID(Record[2]);
1537 return Error(BitcodeError::InvalidRecord);
1538 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1539 } else // TODO: Remove with llvm 4.0
1540 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1542 return Error(BitcodeError::InvalidRecord);
1543 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1546 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1547 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1548 if (Record.size() < 3 || !OpTy)
1549 return Error(BitcodeError::InvalidRecord);
1550 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1551 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1552 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1553 OpTy->getNumElements());
1554 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1555 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1558 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1559 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1561 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1562 if (Record.size() < 4 || !RTy || !OpTy)
1563 return Error(BitcodeError::InvalidRecord);
1564 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1565 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1566 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1567 RTy->getNumElements());
1568 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1569 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1572 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1573 if (Record.size() < 4)
1574 return Error(BitcodeError::InvalidRecord);
1575 Type *OpTy = getTypeByID(Record[0]);
1577 return Error(BitcodeError::InvalidRecord);
1578 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1579 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1581 if (OpTy->isFPOrFPVectorTy())
1582 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1584 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1587 // This maintains backward compatibility, pre-asm dialect keywords.
1588 // FIXME: Remove with the 4.0 release.
1589 case bitc::CST_CODE_INLINEASM_OLD: {
1590 if (Record.size() < 2)
1591 return Error(BitcodeError::InvalidRecord);
1592 std::string AsmStr, ConstrStr;
1593 bool HasSideEffects = Record[0] & 1;
1594 bool IsAlignStack = Record[0] >> 1;
1595 unsigned AsmStrSize = Record[1];
1596 if (2+AsmStrSize >= Record.size())
1597 return Error(BitcodeError::InvalidRecord);
1598 unsigned ConstStrSize = Record[2+AsmStrSize];
1599 if (3+AsmStrSize+ConstStrSize > Record.size())
1600 return Error(BitcodeError::InvalidRecord);
1602 for (unsigned i = 0; i != AsmStrSize; ++i)
1603 AsmStr += (char)Record[2+i];
1604 for (unsigned i = 0; i != ConstStrSize; ++i)
1605 ConstrStr += (char)Record[3+AsmStrSize+i];
1606 PointerType *PTy = cast<PointerType>(CurTy);
1607 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1608 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1611 // This version adds support for the asm dialect keywords (e.g.,
1613 case bitc::CST_CODE_INLINEASM: {
1614 if (Record.size() < 2)
1615 return Error(BitcodeError::InvalidRecord);
1616 std::string AsmStr, ConstrStr;
1617 bool HasSideEffects = Record[0] & 1;
1618 bool IsAlignStack = (Record[0] >> 1) & 1;
1619 unsigned AsmDialect = Record[0] >> 2;
1620 unsigned AsmStrSize = Record[1];
1621 if (2+AsmStrSize >= Record.size())
1622 return Error(BitcodeError::InvalidRecord);
1623 unsigned ConstStrSize = Record[2+AsmStrSize];
1624 if (3+AsmStrSize+ConstStrSize > Record.size())
1625 return Error(BitcodeError::InvalidRecord);
1627 for (unsigned i = 0; i != AsmStrSize; ++i)
1628 AsmStr += (char)Record[2+i];
1629 for (unsigned i = 0; i != ConstStrSize; ++i)
1630 ConstrStr += (char)Record[3+AsmStrSize+i];
1631 PointerType *PTy = cast<PointerType>(CurTy);
1632 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1633 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1634 InlineAsm::AsmDialect(AsmDialect));
1637 case bitc::CST_CODE_BLOCKADDRESS:{
1638 if (Record.size() < 3)
1639 return Error(BitcodeError::InvalidRecord);
1640 Type *FnTy = getTypeByID(Record[0]);
1642 return Error(BitcodeError::InvalidRecord);
1644 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1646 return Error(BitcodeError::InvalidRecord);
1648 // Don't let Fn get dematerialized.
1649 BlockAddressesTaken.insert(Fn);
1651 // If the function is already parsed we can insert the block address right
1654 unsigned BBID = Record[2];
1656 // Invalid reference to entry block.
1657 return Error(BitcodeError::InvalidID);
1659 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1660 for (size_t I = 0, E = BBID; I != E; ++I) {
1662 return Error(BitcodeError::InvalidID);
1667 // Otherwise insert a placeholder and remember it so it can be inserted
1668 // when the function is parsed.
1669 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1671 BasicBlockFwdRefQueue.push_back(Fn);
1672 if (FwdBBs.size() < BBID + 1)
1673 FwdBBs.resize(BBID + 1);
1675 FwdBBs[BBID] = BasicBlock::Create(Context);
1678 V = BlockAddress::get(Fn, BB);
1683 ValueList.AssignValue(V, NextCstNo);
1688 std::error_code BitcodeReader::ParseUseLists() {
1689 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1690 return Error(BitcodeError::InvalidRecord);
1692 // Read all the records.
1693 SmallVector<uint64_t, 64> Record;
1695 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1697 switch (Entry.Kind) {
1698 case BitstreamEntry::SubBlock: // Handled for us already.
1699 case BitstreamEntry::Error:
1700 return Error(BitcodeError::MalformedBlock);
1701 case BitstreamEntry::EndBlock:
1702 return std::error_code();
1703 case BitstreamEntry::Record:
1704 // The interesting case.
1708 // Read a use list record.
1711 switch (Stream.readRecord(Entry.ID, Record)) {
1712 default: // Default behavior: unknown type.
1714 case bitc::USELIST_CODE_BB:
1717 case bitc::USELIST_CODE_DEFAULT: {
1718 unsigned RecordLength = Record.size();
1719 if (RecordLength < 3)
1720 // Records should have at least an ID and two indexes.
1721 return Error(BitcodeError::InvalidRecord);
1722 unsigned ID = Record.back();
1727 assert(ID < FunctionBBs.size() && "Basic block not found");
1728 V = FunctionBBs[ID];
1731 unsigned NumUses = 0;
1732 SmallDenseMap<const Use *, unsigned, 16> Order;
1733 for (const Use &U : V->uses()) {
1734 if (++NumUses > Record.size())
1736 Order[&U] = Record[NumUses - 1];
1738 if (Order.size() != Record.size() || NumUses > Record.size())
1739 // Mismatches can happen if the functions are being materialized lazily
1740 // (out-of-order), or a value has been upgraded.
1743 V->sortUseList([&](const Use &L, const Use &R) {
1744 return Order.lookup(&L) < Order.lookup(&R);
1752 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1753 /// remember where it is and then skip it. This lets us lazily deserialize the
1755 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1756 // Get the function we are talking about.
1757 if (FunctionsWithBodies.empty())
1758 return Error(BitcodeError::InsufficientFunctionProtos);
1760 Function *Fn = FunctionsWithBodies.back();
1761 FunctionsWithBodies.pop_back();
1763 // Save the current stream state.
1764 uint64_t CurBit = Stream.GetCurrentBitNo();
1765 DeferredFunctionInfo[Fn] = CurBit;
1767 // Skip over the function block for now.
1768 if (Stream.SkipBlock())
1769 return Error(BitcodeError::InvalidRecord);
1770 return std::error_code();
1773 std::error_code BitcodeReader::GlobalCleanup() {
1774 // Patch the initializers for globals and aliases up.
1775 ResolveGlobalAndAliasInits();
1776 if (!GlobalInits.empty() || !AliasInits.empty())
1777 return Error(BitcodeError::MalformedGlobalInitializerSet);
1779 // Look for intrinsic functions which need to be upgraded at some point
1780 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1783 if (UpgradeIntrinsicFunction(FI, NewFn))
1784 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1787 // Look for global variables which need to be renamed.
1788 for (Module::global_iterator
1789 GI = TheModule->global_begin(), GE = TheModule->global_end();
1791 GlobalVariable *GV = GI++;
1792 UpgradeGlobalVariable(GV);
1795 // Force deallocation of memory for these vectors to favor the client that
1796 // want lazy deserialization.
1797 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1798 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1799 return std::error_code();
1802 std::error_code BitcodeReader::ParseModule(bool Resume) {
1804 Stream.JumpToBit(NextUnreadBit);
1805 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1806 return Error(BitcodeError::InvalidRecord);
1808 SmallVector<uint64_t, 64> Record;
1809 std::vector<std::string> SectionTable;
1810 std::vector<std::string> GCTable;
1812 // Read all the records for this module.
1814 BitstreamEntry Entry = Stream.advance();
1816 switch (Entry.Kind) {
1817 case BitstreamEntry::Error:
1818 return Error(BitcodeError::MalformedBlock);
1819 case BitstreamEntry::EndBlock:
1820 return GlobalCleanup();
1822 case BitstreamEntry::SubBlock:
1824 default: // Skip unknown content.
1825 if (Stream.SkipBlock())
1826 return Error(BitcodeError::InvalidRecord);
1828 case bitc::BLOCKINFO_BLOCK_ID:
1829 if (Stream.ReadBlockInfoBlock())
1830 return Error(BitcodeError::MalformedBlock);
1832 case bitc::PARAMATTR_BLOCK_ID:
1833 if (std::error_code EC = ParseAttributeBlock())
1836 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1837 if (std::error_code EC = ParseAttributeGroupBlock())
1840 case bitc::TYPE_BLOCK_ID_NEW:
1841 if (std::error_code EC = ParseTypeTable())
1844 case bitc::VALUE_SYMTAB_BLOCK_ID:
1845 if (std::error_code EC = ParseValueSymbolTable())
1847 SeenValueSymbolTable = true;
1849 case bitc::CONSTANTS_BLOCK_ID:
1850 if (std::error_code EC = ParseConstants())
1852 if (std::error_code EC = ResolveGlobalAndAliasInits())
1855 case bitc::METADATA_BLOCK_ID:
1856 if (std::error_code EC = ParseMetadata())
1859 case bitc::FUNCTION_BLOCK_ID:
1860 // If this is the first function body we've seen, reverse the
1861 // FunctionsWithBodies list.
1862 if (!SeenFirstFunctionBody) {
1863 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1864 if (std::error_code EC = GlobalCleanup())
1866 SeenFirstFunctionBody = true;
1869 if (std::error_code EC = RememberAndSkipFunctionBody())
1871 // For streaming bitcode, suspend parsing when we reach the function
1872 // bodies. Subsequent materialization calls will resume it when
1873 // necessary. For streaming, the function bodies must be at the end of
1874 // the bitcode. If the bitcode file is old, the symbol table will be
1875 // at the end instead and will not have been seen yet. In this case,
1876 // just finish the parse now.
1877 if (LazyStreamer && SeenValueSymbolTable) {
1878 NextUnreadBit = Stream.GetCurrentBitNo();
1879 return std::error_code();
1882 case bitc::USELIST_BLOCK_ID:
1883 if (std::error_code EC = ParseUseLists())
1889 case BitstreamEntry::Record:
1890 // The interesting case.
1896 switch (Stream.readRecord(Entry.ID, Record)) {
1897 default: break; // Default behavior, ignore unknown content.
1898 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1899 if (Record.size() < 1)
1900 return Error(BitcodeError::InvalidRecord);
1901 // Only version #0 and #1 are supported so far.
1902 unsigned module_version = Record[0];
1903 switch (module_version) {
1905 return Error(BitcodeError::InvalidValue);
1907 UseRelativeIDs = false;
1910 UseRelativeIDs = true;
1915 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1917 if (ConvertToString(Record, 0, S))
1918 return Error(BitcodeError::InvalidRecord);
1919 TheModule->setTargetTriple(S);
1922 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1924 if (ConvertToString(Record, 0, S))
1925 return Error(BitcodeError::InvalidRecord);
1926 TheModule->setDataLayout(S);
1929 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1931 if (ConvertToString(Record, 0, S))
1932 return Error(BitcodeError::InvalidRecord);
1933 TheModule->setModuleInlineAsm(S);
1936 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1937 // FIXME: Remove in 4.0.
1939 if (ConvertToString(Record, 0, S))
1940 return Error(BitcodeError::InvalidRecord);
1944 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1946 if (ConvertToString(Record, 0, S))
1947 return Error(BitcodeError::InvalidRecord);
1948 SectionTable.push_back(S);
1951 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1953 if (ConvertToString(Record, 0, S))
1954 return Error(BitcodeError::InvalidRecord);
1955 GCTable.push_back(S);
1958 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1959 if (Record.size() < 2)
1960 return Error(BitcodeError::InvalidRecord);
1961 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1962 unsigned ComdatNameSize = Record[1];
1963 std::string ComdatName;
1964 ComdatName.reserve(ComdatNameSize);
1965 for (unsigned i = 0; i != ComdatNameSize; ++i)
1966 ComdatName += (char)Record[2 + i];
1967 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1968 C->setSelectionKind(SK);
1969 ComdatList.push_back(C);
1972 // GLOBALVAR: [pointer type, isconst, initid,
1973 // linkage, alignment, section, visibility, threadlocal,
1974 // unnamed_addr, dllstorageclass]
1975 case bitc::MODULE_CODE_GLOBALVAR: {
1976 if (Record.size() < 6)
1977 return Error(BitcodeError::InvalidRecord);
1978 Type *Ty = getTypeByID(Record[0]);
1980 return Error(BitcodeError::InvalidRecord);
1981 if (!Ty->isPointerTy())
1982 return Error(BitcodeError::InvalidTypeForValue);
1983 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1984 Ty = cast<PointerType>(Ty)->getElementType();
1986 bool isConstant = Record[1];
1987 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1988 unsigned Alignment = (1 << Record[4]) >> 1;
1989 std::string Section;
1991 if (Record[5]-1 >= SectionTable.size())
1992 return Error(BitcodeError::InvalidID);
1993 Section = SectionTable[Record[5]-1];
1995 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1996 // Local linkage must have default visibility.
1997 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1998 // FIXME: Change to an error if non-default in 4.0.
1999 Visibility = GetDecodedVisibility(Record[6]);
2001 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2002 if (Record.size() > 7)
2003 TLM = GetDecodedThreadLocalMode(Record[7]);
2005 bool UnnamedAddr = false;
2006 if (Record.size() > 8)
2007 UnnamedAddr = Record[8];
2009 bool ExternallyInitialized = false;
2010 if (Record.size() > 9)
2011 ExternallyInitialized = Record[9];
2013 GlobalVariable *NewGV =
2014 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2015 TLM, AddressSpace, ExternallyInitialized);
2016 NewGV->setAlignment(Alignment);
2017 if (!Section.empty())
2018 NewGV->setSection(Section);
2019 NewGV->setVisibility(Visibility);
2020 NewGV->setUnnamedAddr(UnnamedAddr);
2022 if (Record.size() > 10)
2023 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2025 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2027 ValueList.push_back(NewGV);
2029 // Remember which value to use for the global initializer.
2030 if (unsigned InitID = Record[2])
2031 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2033 if (Record.size() > 11)
2034 if (unsigned ComdatID = Record[11]) {
2035 assert(ComdatID <= ComdatList.size());
2036 NewGV->setComdat(ComdatList[ComdatID - 1]);
2040 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2041 // alignment, section, visibility, gc, unnamed_addr,
2042 // prologuedata, dllstorageclass, comdat, prefixdata]
2043 case bitc::MODULE_CODE_FUNCTION: {
2044 if (Record.size() < 8)
2045 return Error(BitcodeError::InvalidRecord);
2046 Type *Ty = getTypeByID(Record[0]);
2048 return Error(BitcodeError::InvalidRecord);
2049 if (!Ty->isPointerTy())
2050 return Error(BitcodeError::InvalidTypeForValue);
2052 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2054 return Error(BitcodeError::InvalidTypeForValue);
2056 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2059 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2060 bool isProto = Record[2];
2061 Func->setLinkage(GetDecodedLinkage(Record[3]));
2062 Func->setAttributes(getAttributes(Record[4]));
2064 Func->setAlignment((1 << Record[5]) >> 1);
2066 if (Record[6]-1 >= SectionTable.size())
2067 return Error(BitcodeError::InvalidID);
2068 Func->setSection(SectionTable[Record[6]-1]);
2070 // Local linkage must have default visibility.
2071 if (!Func->hasLocalLinkage())
2072 // FIXME: Change to an error if non-default in 4.0.
2073 Func->setVisibility(GetDecodedVisibility(Record[7]));
2074 if (Record.size() > 8 && Record[8]) {
2075 if (Record[8]-1 > GCTable.size())
2076 return Error(BitcodeError::InvalidID);
2077 Func->setGC(GCTable[Record[8]-1].c_str());
2079 bool UnnamedAddr = false;
2080 if (Record.size() > 9)
2081 UnnamedAddr = Record[9];
2082 Func->setUnnamedAddr(UnnamedAddr);
2083 if (Record.size() > 10 && Record[10] != 0)
2084 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2086 if (Record.size() > 11)
2087 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2089 UpgradeDLLImportExportLinkage(Func, Record[3]);
2091 if (Record.size() > 12)
2092 if (unsigned ComdatID = Record[12]) {
2093 assert(ComdatID <= ComdatList.size());
2094 Func->setComdat(ComdatList[ComdatID - 1]);
2097 if (Record.size() > 13 && Record[13] != 0)
2098 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2100 ValueList.push_back(Func);
2102 // If this is a function with a body, remember the prototype we are
2103 // creating now, so that we can match up the body with them later.
2105 Func->setIsMaterializable(true);
2106 FunctionsWithBodies.push_back(Func);
2108 DeferredFunctionInfo[Func] = 0;
2112 // ALIAS: [alias type, aliasee val#, linkage]
2113 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2114 case bitc::MODULE_CODE_ALIAS: {
2115 if (Record.size() < 3)
2116 return Error(BitcodeError::InvalidRecord);
2117 Type *Ty = getTypeByID(Record[0]);
2119 return Error(BitcodeError::InvalidRecord);
2120 auto *PTy = dyn_cast<PointerType>(Ty);
2122 return Error(BitcodeError::InvalidTypeForValue);
2125 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2126 GetDecodedLinkage(Record[2]), "", TheModule);
2127 // Old bitcode files didn't have visibility field.
2128 // Local linkage must have default visibility.
2129 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2130 // FIXME: Change to an error if non-default in 4.0.
2131 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2132 if (Record.size() > 4)
2133 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2135 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2136 if (Record.size() > 5)
2137 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2138 if (Record.size() > 6)
2139 NewGA->setUnnamedAddr(Record[6]);
2140 ValueList.push_back(NewGA);
2141 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2144 /// MODULE_CODE_PURGEVALS: [numvals]
2145 case bitc::MODULE_CODE_PURGEVALS:
2146 // Trim down the value list to the specified size.
2147 if (Record.size() < 1 || Record[0] > ValueList.size())
2148 return Error(BitcodeError::InvalidRecord);
2149 ValueList.shrinkTo(Record[0]);
2156 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2157 TheModule = nullptr;
2159 if (std::error_code EC = InitStream())
2162 // Sniff for the signature.
2163 if (Stream.Read(8) != 'B' ||
2164 Stream.Read(8) != 'C' ||
2165 Stream.Read(4) != 0x0 ||
2166 Stream.Read(4) != 0xC ||
2167 Stream.Read(4) != 0xE ||
2168 Stream.Read(4) != 0xD)
2169 return Error(BitcodeError::InvalidBitcodeSignature);
2171 // We expect a number of well-defined blocks, though we don't necessarily
2172 // need to understand them all.
2174 if (Stream.AtEndOfStream())
2175 return std::error_code();
2177 BitstreamEntry Entry =
2178 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2180 switch (Entry.Kind) {
2181 case BitstreamEntry::Error:
2182 return Error(BitcodeError::MalformedBlock);
2183 case BitstreamEntry::EndBlock:
2184 return std::error_code();
2186 case BitstreamEntry::SubBlock:
2188 case bitc::BLOCKINFO_BLOCK_ID:
2189 if (Stream.ReadBlockInfoBlock())
2190 return Error(BitcodeError::MalformedBlock);
2192 case bitc::MODULE_BLOCK_ID:
2193 // Reject multiple MODULE_BLOCK's in a single bitstream.
2195 return Error(BitcodeError::InvalidMultipleBlocks);
2197 if (std::error_code EC = ParseModule(false))
2200 return std::error_code();
2203 if (Stream.SkipBlock())
2204 return Error(BitcodeError::InvalidRecord);
2208 case BitstreamEntry::Record:
2209 // There should be no records in the top-level of blocks.
2211 // The ranlib in Xcode 4 will align archive members by appending newlines
2212 // to the end of them. If this file size is a multiple of 4 but not 8, we
2213 // have to read and ignore these final 4 bytes :-(
2214 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2215 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2216 Stream.AtEndOfStream())
2217 return std::error_code();
2219 return Error(BitcodeError::InvalidRecord);
2224 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2225 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2226 return Error(BitcodeError::InvalidRecord);
2228 SmallVector<uint64_t, 64> Record;
2231 // Read all the records for this module.
2233 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2235 switch (Entry.Kind) {
2236 case BitstreamEntry::SubBlock: // Handled for us already.
2237 case BitstreamEntry::Error:
2238 return Error(BitcodeError::MalformedBlock);
2239 case BitstreamEntry::EndBlock:
2241 case BitstreamEntry::Record:
2242 // The interesting case.
2247 switch (Stream.readRecord(Entry.ID, Record)) {
2248 default: break; // Default behavior, ignore unknown content.
2249 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2251 if (ConvertToString(Record, 0, S))
2252 return Error(BitcodeError::InvalidRecord);
2259 llvm_unreachable("Exit infinite loop");
2262 ErrorOr<std::string> BitcodeReader::parseTriple() {
2263 if (std::error_code EC = InitStream())
2266 // Sniff for the signature.
2267 if (Stream.Read(8) != 'B' ||
2268 Stream.Read(8) != 'C' ||
2269 Stream.Read(4) != 0x0 ||
2270 Stream.Read(4) != 0xC ||
2271 Stream.Read(4) != 0xE ||
2272 Stream.Read(4) != 0xD)
2273 return Error(BitcodeError::InvalidBitcodeSignature);
2275 // We expect a number of well-defined blocks, though we don't necessarily
2276 // need to understand them all.
2278 BitstreamEntry Entry = Stream.advance();
2280 switch (Entry.Kind) {
2281 case BitstreamEntry::Error:
2282 return Error(BitcodeError::MalformedBlock);
2283 case BitstreamEntry::EndBlock:
2284 return std::error_code();
2286 case BitstreamEntry::SubBlock:
2287 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2288 return parseModuleTriple();
2290 // Ignore other sub-blocks.
2291 if (Stream.SkipBlock())
2292 return Error(BitcodeError::MalformedBlock);
2295 case BitstreamEntry::Record:
2296 Stream.skipRecord(Entry.ID);
2302 /// ParseMetadataAttachment - Parse metadata attachments.
2303 std::error_code BitcodeReader::ParseMetadataAttachment() {
2304 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2305 return Error(BitcodeError::InvalidRecord);
2307 SmallVector<uint64_t, 64> Record;
2309 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2311 switch (Entry.Kind) {
2312 case BitstreamEntry::SubBlock: // Handled for us already.
2313 case BitstreamEntry::Error:
2314 return Error(BitcodeError::MalformedBlock);
2315 case BitstreamEntry::EndBlock:
2316 return std::error_code();
2317 case BitstreamEntry::Record:
2318 // The interesting case.
2322 // Read a metadata attachment record.
2324 switch (Stream.readRecord(Entry.ID, Record)) {
2325 default: // Default behavior: ignore.
2327 case bitc::METADATA_ATTACHMENT: {
2328 unsigned RecordLength = Record.size();
2329 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2330 return Error(BitcodeError::InvalidRecord);
2331 Instruction *Inst = InstructionList[Record[0]];
2332 for (unsigned i = 1; i != RecordLength; i = i+2) {
2333 unsigned Kind = Record[i];
2334 DenseMap<unsigned, unsigned>::iterator I =
2335 MDKindMap.find(Kind);
2336 if (I == MDKindMap.end())
2337 return Error(BitcodeError::InvalidID);
2338 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2339 Inst->setMetadata(I->second, cast<MDNode>(Node));
2340 if (I->second == LLVMContext::MD_tbaa)
2341 InstsWithTBAATag.push_back(Inst);
2349 /// ParseFunctionBody - Lazily parse the specified function body block.
2350 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2351 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2352 return Error(BitcodeError::InvalidRecord);
2354 InstructionList.clear();
2355 unsigned ModuleValueListSize = ValueList.size();
2356 unsigned ModuleMDValueListSize = MDValueList.size();
2358 // Add all the function arguments to the value table.
2359 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2360 ValueList.push_back(I);
2362 unsigned NextValueNo = ValueList.size();
2363 BasicBlock *CurBB = nullptr;
2364 unsigned CurBBNo = 0;
2368 // Read all the records.
2369 SmallVector<uint64_t, 64> Record;
2371 BitstreamEntry Entry = Stream.advance();
2373 switch (Entry.Kind) {
2374 case BitstreamEntry::Error:
2375 return Error(BitcodeError::MalformedBlock);
2376 case BitstreamEntry::EndBlock:
2377 goto OutOfRecordLoop;
2379 case BitstreamEntry::SubBlock:
2381 default: // Skip unknown content.
2382 if (Stream.SkipBlock())
2383 return Error(BitcodeError::InvalidRecord);
2385 case bitc::CONSTANTS_BLOCK_ID:
2386 if (std::error_code EC = ParseConstants())
2388 NextValueNo = ValueList.size();
2390 case bitc::VALUE_SYMTAB_BLOCK_ID:
2391 if (std::error_code EC = ParseValueSymbolTable())
2394 case bitc::METADATA_ATTACHMENT_ID:
2395 if (std::error_code EC = ParseMetadataAttachment())
2398 case bitc::METADATA_BLOCK_ID:
2399 if (std::error_code EC = ParseMetadata())
2402 case bitc::USELIST_BLOCK_ID:
2403 if (std::error_code EC = ParseUseLists())
2409 case BitstreamEntry::Record:
2410 // The interesting case.
2416 Instruction *I = nullptr;
2417 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2419 default: // Default behavior: reject
2420 return Error(BitcodeError::InvalidValue);
2421 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2422 if (Record.size() < 1 || Record[0] == 0)
2423 return Error(BitcodeError::InvalidRecord);
2424 // Create all the basic blocks for the function.
2425 FunctionBBs.resize(Record[0]);
2427 // See if anything took the address of blocks in this function.
2428 auto BBFRI = BasicBlockFwdRefs.find(F);
2429 if (BBFRI == BasicBlockFwdRefs.end()) {
2430 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2431 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2433 auto &BBRefs = BBFRI->second;
2434 // Check for invalid basic block references.
2435 if (BBRefs.size() > FunctionBBs.size())
2436 return Error(BitcodeError::InvalidID);
2437 assert(!BBRefs.empty() && "Unexpected empty array");
2438 assert(!BBRefs.front() && "Invalid reference to entry block");
2439 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2441 if (I < RE && BBRefs[I]) {
2442 BBRefs[I]->insertInto(F);
2443 FunctionBBs[I] = BBRefs[I];
2445 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2448 // Erase from the table.
2449 BasicBlockFwdRefs.erase(BBFRI);
2452 CurBB = FunctionBBs[0];
2456 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2457 // This record indicates that the last instruction is at the same
2458 // location as the previous instruction with a location.
2461 // Get the last instruction emitted.
2462 if (CurBB && !CurBB->empty())
2464 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2465 !FunctionBBs[CurBBNo-1]->empty())
2466 I = &FunctionBBs[CurBBNo-1]->back();
2469 return Error(BitcodeError::InvalidRecord);
2470 I->setDebugLoc(LastLoc);
2474 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2475 I = nullptr; // Get the last instruction emitted.
2476 if (CurBB && !CurBB->empty())
2478 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2479 !FunctionBBs[CurBBNo-1]->empty())
2480 I = &FunctionBBs[CurBBNo-1]->back();
2481 if (!I || Record.size() < 4)
2482 return Error(BitcodeError::InvalidRecord);
2484 unsigned Line = Record[0], Col = Record[1];
2485 unsigned ScopeID = Record[2], IAID = Record[3];
2487 MDNode *Scope = nullptr, *IA = nullptr;
2488 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2489 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2490 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2491 I->setDebugLoc(LastLoc);
2496 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2499 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2500 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2501 OpNum+1 > Record.size())
2502 return Error(BitcodeError::InvalidRecord);
2504 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2506 return Error(BitcodeError::InvalidRecord);
2507 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2508 InstructionList.push_back(I);
2509 if (OpNum < Record.size()) {
2510 if (Opc == Instruction::Add ||
2511 Opc == Instruction::Sub ||
2512 Opc == Instruction::Mul ||
2513 Opc == Instruction::Shl) {
2514 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2515 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2516 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2517 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2518 } else if (Opc == Instruction::SDiv ||
2519 Opc == Instruction::UDiv ||
2520 Opc == Instruction::LShr ||
2521 Opc == Instruction::AShr) {
2522 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2523 cast<BinaryOperator>(I)->setIsExact(true);
2524 } else if (isa<FPMathOperator>(I)) {
2526 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2527 FMF.setUnsafeAlgebra();
2528 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2530 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2532 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2533 FMF.setNoSignedZeros();
2534 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2535 FMF.setAllowReciprocal();
2537 I->setFastMathFlags(FMF);
2543 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2546 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2547 OpNum+2 != Record.size())
2548 return Error(BitcodeError::InvalidRecord);
2550 Type *ResTy = getTypeByID(Record[OpNum]);
2551 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2552 if (Opc == -1 || !ResTy)
2553 return Error(BitcodeError::InvalidRecord);
2554 Instruction *Temp = nullptr;
2555 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2557 InstructionList.push_back(Temp);
2558 CurBB->getInstList().push_back(Temp);
2561 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2563 InstructionList.push_back(I);
2566 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2567 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2570 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2571 return Error(BitcodeError::InvalidRecord);
2573 SmallVector<Value*, 16> GEPIdx;
2574 while (OpNum != Record.size()) {
2576 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2577 return Error(BitcodeError::InvalidRecord);
2578 GEPIdx.push_back(Op);
2581 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2582 InstructionList.push_back(I);
2583 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2584 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2588 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2589 // EXTRACTVAL: [opty, opval, n x indices]
2592 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2593 return Error(BitcodeError::InvalidRecord);
2595 SmallVector<unsigned, 4> EXTRACTVALIdx;
2596 for (unsigned RecSize = Record.size();
2597 OpNum != RecSize; ++OpNum) {
2598 uint64_t Index = Record[OpNum];
2599 if ((unsigned)Index != Index)
2600 return Error(BitcodeError::InvalidValue);
2601 EXTRACTVALIdx.push_back((unsigned)Index);
2604 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2605 InstructionList.push_back(I);
2609 case bitc::FUNC_CODE_INST_INSERTVAL: {
2610 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2613 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2614 return Error(BitcodeError::InvalidRecord);
2616 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2617 return Error(BitcodeError::InvalidRecord);
2619 SmallVector<unsigned, 4> INSERTVALIdx;
2620 for (unsigned RecSize = Record.size();
2621 OpNum != RecSize; ++OpNum) {
2622 uint64_t Index = Record[OpNum];
2623 if ((unsigned)Index != Index)
2624 return Error(BitcodeError::InvalidValue);
2625 INSERTVALIdx.push_back((unsigned)Index);
2628 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2629 InstructionList.push_back(I);
2633 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2634 // obsolete form of select
2635 // handles select i1 ... in old bitcode
2637 Value *TrueVal, *FalseVal, *Cond;
2638 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2639 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2640 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2641 return Error(BitcodeError::InvalidRecord);
2643 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2644 InstructionList.push_back(I);
2648 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2649 // new form of select
2650 // handles select i1 or select [N x i1]
2652 Value *TrueVal, *FalseVal, *Cond;
2653 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2654 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2655 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2656 return Error(BitcodeError::InvalidRecord);
2658 // select condition can be either i1 or [N x i1]
2659 if (VectorType* vector_type =
2660 dyn_cast<VectorType>(Cond->getType())) {
2662 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2663 return Error(BitcodeError::InvalidTypeForValue);
2666 if (Cond->getType() != Type::getInt1Ty(Context))
2667 return Error(BitcodeError::InvalidTypeForValue);
2670 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2671 InstructionList.push_back(I);
2675 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2678 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2679 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2680 return Error(BitcodeError::InvalidRecord);
2681 I = ExtractElementInst::Create(Vec, Idx);
2682 InstructionList.push_back(I);
2686 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2688 Value *Vec, *Elt, *Idx;
2689 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2690 popValue(Record, OpNum, NextValueNo,
2691 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2692 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2693 return Error(BitcodeError::InvalidRecord);
2694 I = InsertElementInst::Create(Vec, Elt, Idx);
2695 InstructionList.push_back(I);
2699 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2701 Value *Vec1, *Vec2, *Mask;
2702 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2703 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2704 return Error(BitcodeError::InvalidRecord);
2706 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2707 return Error(BitcodeError::InvalidRecord);
2708 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2709 InstructionList.push_back(I);
2713 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2714 // Old form of ICmp/FCmp returning bool
2715 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2716 // both legal on vectors but had different behaviour.
2717 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2718 // FCmp/ICmp returning bool or vector of bool
2722 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2723 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2724 OpNum+1 != Record.size())
2725 return Error(BitcodeError::InvalidRecord);
2727 if (LHS->getType()->isFPOrFPVectorTy())
2728 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2730 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2731 InstructionList.push_back(I);
2735 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2737 unsigned Size = Record.size();
2739 I = ReturnInst::Create(Context);
2740 InstructionList.push_back(I);
2745 Value *Op = nullptr;
2746 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2747 return Error(BitcodeError::InvalidRecord);
2748 if (OpNum != Record.size())
2749 return Error(BitcodeError::InvalidRecord);
2751 I = ReturnInst::Create(Context, Op);
2752 InstructionList.push_back(I);
2755 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2756 if (Record.size() != 1 && Record.size() != 3)
2757 return Error(BitcodeError::InvalidRecord);
2758 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2760 return Error(BitcodeError::InvalidRecord);
2762 if (Record.size() == 1) {
2763 I = BranchInst::Create(TrueDest);
2764 InstructionList.push_back(I);
2767 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2768 Value *Cond = getValue(Record, 2, NextValueNo,
2769 Type::getInt1Ty(Context));
2770 if (!FalseDest || !Cond)
2771 return Error(BitcodeError::InvalidRecord);
2772 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2773 InstructionList.push_back(I);
2777 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2779 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2780 // "New" SwitchInst format with case ranges. The changes to write this
2781 // format were reverted but we still recognize bitcode that uses it.
2782 // Hopefully someday we will have support for case ranges and can use
2783 // this format again.
2785 Type *OpTy = getTypeByID(Record[1]);
2786 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2788 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2789 BasicBlock *Default = getBasicBlock(Record[3]);
2790 if (!OpTy || !Cond || !Default)
2791 return Error(BitcodeError::InvalidRecord);
2793 unsigned NumCases = Record[4];
2795 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2796 InstructionList.push_back(SI);
2798 unsigned CurIdx = 5;
2799 for (unsigned i = 0; i != NumCases; ++i) {
2800 SmallVector<ConstantInt*, 1> CaseVals;
2801 unsigned NumItems = Record[CurIdx++];
2802 for (unsigned ci = 0; ci != NumItems; ++ci) {
2803 bool isSingleNumber = Record[CurIdx++];
2806 unsigned ActiveWords = 1;
2807 if (ValueBitWidth > 64)
2808 ActiveWords = Record[CurIdx++];
2809 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2811 CurIdx += ActiveWords;
2813 if (!isSingleNumber) {
2815 if (ValueBitWidth > 64)
2816 ActiveWords = Record[CurIdx++];
2818 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2820 CurIdx += ActiveWords;
2822 // FIXME: It is not clear whether values in the range should be
2823 // compared as signed or unsigned values. The partially
2824 // implemented changes that used this format in the past used
2825 // unsigned comparisons.
2826 for ( ; Low.ule(High); ++Low)
2827 CaseVals.push_back(ConstantInt::get(Context, Low));
2829 CaseVals.push_back(ConstantInt::get(Context, Low));
2831 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2832 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2833 cve = CaseVals.end(); cvi != cve; ++cvi)
2834 SI->addCase(*cvi, DestBB);
2840 // Old SwitchInst format without case ranges.
2842 if (Record.size() < 3 || (Record.size() & 1) == 0)
2843 return Error(BitcodeError::InvalidRecord);
2844 Type *OpTy = getTypeByID(Record[0]);
2845 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2846 BasicBlock *Default = getBasicBlock(Record[2]);
2847 if (!OpTy || !Cond || !Default)
2848 return Error(BitcodeError::InvalidRecord);
2849 unsigned NumCases = (Record.size()-3)/2;
2850 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2851 InstructionList.push_back(SI);
2852 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2853 ConstantInt *CaseVal =
2854 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2855 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2856 if (!CaseVal || !DestBB) {
2858 return Error(BitcodeError::InvalidRecord);
2860 SI->addCase(CaseVal, DestBB);
2865 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2866 if (Record.size() < 2)
2867 return Error(BitcodeError::InvalidRecord);
2868 Type *OpTy = getTypeByID(Record[0]);
2869 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2870 if (!OpTy || !Address)
2871 return Error(BitcodeError::InvalidRecord);
2872 unsigned NumDests = Record.size()-2;
2873 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2874 InstructionList.push_back(IBI);
2875 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2876 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2877 IBI->addDestination(DestBB);
2880 return Error(BitcodeError::InvalidRecord);
2887 case bitc::FUNC_CODE_INST_INVOKE: {
2888 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2889 if (Record.size() < 4)
2890 return Error(BitcodeError::InvalidRecord);
2891 AttributeSet PAL = getAttributes(Record[0]);
2892 unsigned CCInfo = Record[1];
2893 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2894 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2898 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2899 return Error(BitcodeError::InvalidRecord);
2901 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2902 FunctionType *FTy = !CalleeTy ? nullptr :
2903 dyn_cast<FunctionType>(CalleeTy->getElementType());
2905 // Check that the right number of fixed parameters are here.
2906 if (!FTy || !NormalBB || !UnwindBB ||
2907 Record.size() < OpNum+FTy->getNumParams())
2908 return Error(BitcodeError::InvalidRecord);
2910 SmallVector<Value*, 16> Ops;
2911 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2912 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2913 FTy->getParamType(i)));
2915 return Error(BitcodeError::InvalidRecord);
2918 if (!FTy->isVarArg()) {
2919 if (Record.size() != OpNum)
2920 return Error(BitcodeError::InvalidRecord);
2922 // Read type/value pairs for varargs params.
2923 while (OpNum != Record.size()) {
2925 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2926 return Error(BitcodeError::InvalidRecord);
2931 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2932 InstructionList.push_back(I);
2933 cast<InvokeInst>(I)->setCallingConv(
2934 static_cast<CallingConv::ID>(CCInfo));
2935 cast<InvokeInst>(I)->setAttributes(PAL);
2938 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2940 Value *Val = nullptr;
2941 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2942 return Error(BitcodeError::InvalidRecord);
2943 I = ResumeInst::Create(Val);
2944 InstructionList.push_back(I);
2947 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2948 I = new UnreachableInst(Context);
2949 InstructionList.push_back(I);
2951 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2952 if (Record.size() < 1 || ((Record.size()-1)&1))
2953 return Error(BitcodeError::InvalidRecord);
2954 Type *Ty = getTypeByID(Record[0]);
2956 return Error(BitcodeError::InvalidRecord);
2958 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2959 InstructionList.push_back(PN);
2961 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2963 // With the new function encoding, it is possible that operands have
2964 // negative IDs (for forward references). Use a signed VBR
2965 // representation to keep the encoding small.
2967 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2969 V = getValue(Record, 1+i, NextValueNo, Ty);
2970 BasicBlock *BB = getBasicBlock(Record[2+i]);
2972 return Error(BitcodeError::InvalidRecord);
2973 PN->addIncoming(V, BB);
2979 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2980 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2982 if (Record.size() < 4)
2983 return Error(BitcodeError::InvalidRecord);
2984 Type *Ty = getTypeByID(Record[Idx++]);
2986 return Error(BitcodeError::InvalidRecord);
2987 Value *PersFn = nullptr;
2988 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2989 return Error(BitcodeError::InvalidRecord);
2991 bool IsCleanup = !!Record[Idx++];
2992 unsigned NumClauses = Record[Idx++];
2993 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2994 LP->setCleanup(IsCleanup);
2995 for (unsigned J = 0; J != NumClauses; ++J) {
2996 LandingPadInst::ClauseType CT =
2997 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3000 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3002 return Error(BitcodeError::InvalidRecord);
3005 assert((CT != LandingPadInst::Catch ||
3006 !isa<ArrayType>(Val->getType())) &&
3007 "Catch clause has a invalid type!");
3008 assert((CT != LandingPadInst::Filter ||
3009 isa<ArrayType>(Val->getType())) &&
3010 "Filter clause has invalid type!");
3011 LP->addClause(cast<Constant>(Val));
3015 InstructionList.push_back(I);
3019 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3020 if (Record.size() != 4)
3021 return Error(BitcodeError::InvalidRecord);
3023 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3024 Type *OpTy = getTypeByID(Record[1]);
3025 Value *Size = getFnValueByID(Record[2], OpTy);
3026 unsigned AlignRecord = Record[3];
3027 bool InAlloca = AlignRecord & (1 << 5);
3028 unsigned Align = AlignRecord & ((1 << 5) - 1);
3030 return Error(BitcodeError::InvalidRecord);
3031 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3032 AI->setUsedWithInAlloca(InAlloca);
3034 InstructionList.push_back(I);
3037 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3040 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3041 OpNum+2 != Record.size())
3042 return Error(BitcodeError::InvalidRecord);
3044 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3045 InstructionList.push_back(I);
3048 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3049 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3052 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3053 OpNum+4 != Record.size())
3054 return Error(BitcodeError::InvalidRecord);
3056 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3057 if (Ordering == NotAtomic || Ordering == Release ||
3058 Ordering == AcquireRelease)
3059 return Error(BitcodeError::InvalidRecord);
3060 if (Ordering != NotAtomic && Record[OpNum] == 0)
3061 return Error(BitcodeError::InvalidRecord);
3062 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3064 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3065 Ordering, SynchScope);
3066 InstructionList.push_back(I);
3069 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3072 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3073 popValue(Record, OpNum, NextValueNo,
3074 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3075 OpNum+2 != Record.size())
3076 return Error(BitcodeError::InvalidRecord);
3078 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3079 InstructionList.push_back(I);
3082 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3083 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3086 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3087 popValue(Record, OpNum, NextValueNo,
3088 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3089 OpNum+4 != Record.size())
3090 return Error(BitcodeError::InvalidRecord);
3092 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3093 if (Ordering == NotAtomic || Ordering == Acquire ||
3094 Ordering == AcquireRelease)
3095 return Error(BitcodeError::InvalidRecord);
3096 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3097 if (Ordering != NotAtomic && Record[OpNum] == 0)
3098 return Error(BitcodeError::InvalidRecord);
3100 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3101 Ordering, SynchScope);
3102 InstructionList.push_back(I);
3105 case bitc::FUNC_CODE_INST_CMPXCHG: {
3106 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3107 // failureordering?, isweak?]
3109 Value *Ptr, *Cmp, *New;
3110 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3111 popValue(Record, OpNum, NextValueNo,
3112 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3113 popValue(Record, OpNum, NextValueNo,
3114 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3115 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3116 return Error(BitcodeError::InvalidRecord);
3117 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3118 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3119 return Error(BitcodeError::InvalidRecord);
3120 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3122 AtomicOrdering FailureOrdering;
3123 if (Record.size() < 7)
3125 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3127 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3129 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3131 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3133 if (Record.size() < 8) {
3134 // Before weak cmpxchgs existed, the instruction simply returned the
3135 // value loaded from memory, so bitcode files from that era will be
3136 // expecting the first component of a modern cmpxchg.
3137 CurBB->getInstList().push_back(I);
3138 I = ExtractValueInst::Create(I, 0);
3140 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3143 InstructionList.push_back(I);
3146 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3147 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3150 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3151 popValue(Record, OpNum, NextValueNo,
3152 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3153 OpNum+4 != Record.size())
3154 return Error(BitcodeError::InvalidRecord);
3155 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3156 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3157 Operation > AtomicRMWInst::LAST_BINOP)
3158 return Error(BitcodeError::InvalidRecord);
3159 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3160 if (Ordering == NotAtomic || Ordering == Unordered)
3161 return Error(BitcodeError::InvalidRecord);
3162 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3163 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3164 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3165 InstructionList.push_back(I);
3168 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3169 if (2 != Record.size())
3170 return Error(BitcodeError::InvalidRecord);
3171 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3172 if (Ordering == NotAtomic || Ordering == Unordered ||
3173 Ordering == Monotonic)
3174 return Error(BitcodeError::InvalidRecord);
3175 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3176 I = new FenceInst(Context, Ordering, SynchScope);
3177 InstructionList.push_back(I);
3180 case bitc::FUNC_CODE_INST_CALL: {
3181 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3182 if (Record.size() < 3)
3183 return Error(BitcodeError::InvalidRecord);
3185 AttributeSet PAL = getAttributes(Record[0]);
3186 unsigned CCInfo = Record[1];
3190 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3191 return Error(BitcodeError::InvalidRecord);
3193 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3194 FunctionType *FTy = nullptr;
3195 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3196 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3197 return Error(BitcodeError::InvalidRecord);
3199 SmallVector<Value*, 16> Args;
3200 // Read the fixed params.
3201 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3202 if (FTy->getParamType(i)->isLabelTy())
3203 Args.push_back(getBasicBlock(Record[OpNum]));
3205 Args.push_back(getValue(Record, OpNum, NextValueNo,
3206 FTy->getParamType(i)));
3208 return Error(BitcodeError::InvalidRecord);
3211 // Read type/value pairs for varargs params.
3212 if (!FTy->isVarArg()) {
3213 if (OpNum != Record.size())
3214 return Error(BitcodeError::InvalidRecord);
3216 while (OpNum != Record.size()) {
3218 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3219 return Error(BitcodeError::InvalidRecord);
3224 I = CallInst::Create(Callee, Args);
3225 InstructionList.push_back(I);
3226 cast<CallInst>(I)->setCallingConv(
3227 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3228 CallInst::TailCallKind TCK = CallInst::TCK_None;
3230 TCK = CallInst::TCK_Tail;
3231 if (CCInfo & (1 << 14))
3232 TCK = CallInst::TCK_MustTail;
3233 cast<CallInst>(I)->setTailCallKind(TCK);
3234 cast<CallInst>(I)->setAttributes(PAL);
3237 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3238 if (Record.size() < 3)
3239 return Error(BitcodeError::InvalidRecord);
3240 Type *OpTy = getTypeByID(Record[0]);
3241 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3242 Type *ResTy = getTypeByID(Record[2]);
3243 if (!OpTy || !Op || !ResTy)
3244 return Error(BitcodeError::InvalidRecord);
3245 I = new VAArgInst(Op, ResTy);
3246 InstructionList.push_back(I);
3251 // Add instruction to end of current BB. If there is no current BB, reject
3255 return Error(BitcodeError::InvalidInstructionWithNoBB);
3257 CurBB->getInstList().push_back(I);
3259 // If this was a terminator instruction, move to the next block.
3260 if (isa<TerminatorInst>(I)) {
3262 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3265 // Non-void values get registered in the value table for future use.
3266 if (I && !I->getType()->isVoidTy())
3267 ValueList.AssignValue(I, NextValueNo++);
3272 // Check the function list for unresolved values.
3273 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3274 if (!A->getParent()) {
3275 // We found at least one unresolved value. Nuke them all to avoid leaks.
3276 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3277 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3278 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3282 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3286 // FIXME: Check for unresolved forward-declared metadata references
3287 // and clean up leaks.
3289 // Trim the value list down to the size it was before we parsed this function.
3290 ValueList.shrinkTo(ModuleValueListSize);
3291 MDValueList.shrinkTo(ModuleMDValueListSize);
3292 std::vector<BasicBlock*>().swap(FunctionBBs);
3293 return std::error_code();
3296 /// Find the function body in the bitcode stream
3297 std::error_code BitcodeReader::FindFunctionInStream(
3299 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3300 while (DeferredFunctionInfoIterator->second == 0) {
3301 if (Stream.AtEndOfStream())
3302 return Error(BitcodeError::CouldNotFindFunctionInStream);
3303 // ParseModule will parse the next body in the stream and set its
3304 // position in the DeferredFunctionInfo map.
3305 if (std::error_code EC = ParseModule(true))
3308 return std::error_code();
3311 //===----------------------------------------------------------------------===//
3312 // GVMaterializer implementation
3313 //===----------------------------------------------------------------------===//
3315 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3317 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3318 Function *F = dyn_cast<Function>(GV);
3319 // If it's not a function or is already material, ignore the request.
3320 if (!F || !F->isMaterializable())
3321 return std::error_code();
3323 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3324 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3325 // If its position is recorded as 0, its body is somewhere in the stream
3326 // but we haven't seen it yet.
3327 if (DFII->second == 0 && LazyStreamer)
3328 if (std::error_code EC = FindFunctionInStream(F, DFII))
3331 // Move the bit stream to the saved position of the deferred function body.
3332 Stream.JumpToBit(DFII->second);
3334 if (std::error_code EC = ParseFunctionBody(F))
3336 F->setIsMaterializable(false);
3338 // Upgrade any old intrinsic calls in the function.
3339 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3340 E = UpgradedIntrinsics.end(); I != E; ++I) {
3341 if (I->first != I->second) {
3342 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3344 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3345 UpgradeIntrinsicCall(CI, I->second);
3350 // Bring in any functions that this function forward-referenced via
3352 return materializeForwardReferencedFunctions();
3355 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3356 const Function *F = dyn_cast<Function>(GV);
3357 if (!F || F->isDeclaration())
3360 // Dematerializing F would leave dangling references that wouldn't be
3361 // reconnected on re-materialization.
3362 if (BlockAddressesTaken.count(F))
3365 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3368 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3369 Function *F = dyn_cast<Function>(GV);
3370 // If this function isn't dematerializable, this is a noop.
3371 if (!F || !isDematerializable(F))
3374 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3376 // Just forget the function body, we can remat it later.
3377 F->dropAllReferences();
3378 F->setIsMaterializable(true);
3381 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3382 assert(M == TheModule &&
3383 "Can only Materialize the Module this BitcodeReader is attached to.");
3385 // Promise to materialize all forward references.
3386 WillMaterializeAllForwardRefs = true;
3388 // Iterate over the module, deserializing any functions that are still on
3390 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3392 if (std::error_code EC = materialize(F))
3395 // At this point, if there are any function bodies, the current bit is
3396 // pointing to the END_BLOCK record after them. Now make sure the rest
3397 // of the bits in the module have been read.
3401 // Check that all block address forward references got resolved (as we
3403 if (!BasicBlockFwdRefs.empty())
3404 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3406 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3407 // delete the old functions to clean up. We can't do this unless the entire
3408 // module is materialized because there could always be another function body
3409 // with calls to the old function.
3410 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3411 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3412 if (I->first != I->second) {
3413 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3415 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3416 UpgradeIntrinsicCall(CI, I->second);
3418 if (!I->first->use_empty())
3419 I->first->replaceAllUsesWith(I->second);
3420 I->first->eraseFromParent();
3423 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3425 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3426 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3428 UpgradeDebugInfo(*M);
3429 return std::error_code();
3432 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3433 return IdentifiedStructTypes;
3436 std::error_code BitcodeReader::InitStream() {
3438 return InitLazyStream();
3439 return InitStreamFromBuffer();
3442 std::error_code BitcodeReader::InitStreamFromBuffer() {
3443 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3444 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3446 if (Buffer->getBufferSize() & 3)
3447 return Error(BitcodeError::InvalidBitcodeSignature);
3449 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3450 // The magic number is 0x0B17C0DE stored in little endian.
3451 if (isBitcodeWrapper(BufPtr, BufEnd))
3452 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3453 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3455 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3456 Stream.init(&*StreamFile);
3458 return std::error_code();
3461 std::error_code BitcodeReader::InitLazyStream() {
3462 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3464 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3465 StreamFile.reset(new BitstreamReader(Bytes));
3466 Stream.init(&*StreamFile);
3468 unsigned char buf[16];
3469 if (Bytes->readBytes(buf, 16, 0) != 16)
3470 return Error(BitcodeError::InvalidBitcodeSignature);
3472 if (!isBitcode(buf, buf + 16))
3473 return Error(BitcodeError::InvalidBitcodeSignature);
3475 if (isBitcodeWrapper(buf, buf + 4)) {
3476 const unsigned char *bitcodeStart = buf;
3477 const unsigned char *bitcodeEnd = buf + 16;
3478 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3479 Bytes->dropLeadingBytes(bitcodeStart - buf);
3480 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3482 return std::error_code();
3486 class BitcodeErrorCategoryType : public std::error_category {
3487 const char *name() const LLVM_NOEXCEPT override {
3488 return "llvm.bitcode";
3490 std::string message(int IE) const override {
3491 BitcodeError E = static_cast<BitcodeError>(IE);
3493 case BitcodeError::ConflictingMETADATA_KINDRecords:
3494 return "Conflicting METADATA_KIND records";
3495 case BitcodeError::CouldNotFindFunctionInStream:
3496 return "Could not find function in stream";
3497 case BitcodeError::ExpectedConstant:
3498 return "Expected a constant";
3499 case BitcodeError::InsufficientFunctionProtos:
3500 return "Insufficient function protos";
3501 case BitcodeError::InvalidBitcodeSignature:
3502 return "Invalid bitcode signature";
3503 case BitcodeError::InvalidBitcodeWrapperHeader:
3504 return "Invalid bitcode wrapper header";
3505 case BitcodeError::InvalidConstantReference:
3506 return "Invalid ronstant reference";
3507 case BitcodeError::InvalidID:
3508 return "Invalid ID";
3509 case BitcodeError::InvalidInstructionWithNoBB:
3510 return "Invalid instruction with no BB";
3511 case BitcodeError::InvalidRecord:
3512 return "Invalid record";
3513 case BitcodeError::InvalidTypeForValue:
3514 return "Invalid type for value";
3515 case BitcodeError::InvalidTYPETable:
3516 return "Invalid TYPE table";
3517 case BitcodeError::InvalidType:
3518 return "Invalid type";
3519 case BitcodeError::MalformedBlock:
3520 return "Malformed block";
3521 case BitcodeError::MalformedGlobalInitializerSet:
3522 return "Malformed global initializer set";
3523 case BitcodeError::InvalidMultipleBlocks:
3524 return "Invalid multiple blocks";
3525 case BitcodeError::NeverResolvedValueFoundInFunction:
3526 return "Never resolved value found in function";
3527 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3528 return "Never resolved function from blockaddress";
3529 case BitcodeError::InvalidValue:
3530 return "Invalid value";
3532 llvm_unreachable("Unknown error type!");
3537 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3539 const std::error_category &llvm::BitcodeErrorCategory() {
3540 return *ErrorCategory;
3543 //===----------------------------------------------------------------------===//
3544 // External interface
3545 //===----------------------------------------------------------------------===//
3547 /// \brief Get a lazy one-at-time loading module from bitcode.
3549 /// This isn't always used in a lazy context. In particular, it's also used by
3550 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3551 /// in forward-referenced functions from block address references.
3553 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3554 /// materialize everything -- in particular, if this isn't truly lazy.
3555 static ErrorOr<Module *>
3556 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3557 LLVMContext &Context, bool WillMaterializeAll) {
3558 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3559 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3560 M->setMaterializer(R);
3562 auto cleanupOnError = [&](std::error_code EC) {
3563 R->releaseBuffer(); // Never take ownership on error.
3564 delete M; // Also deletes R.
3568 if (std::error_code EC = R->ParseBitcodeInto(M))
3569 return cleanupOnError(EC);
3571 if (!WillMaterializeAll)
3572 // Resolve forward references from blockaddresses.
3573 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3574 return cleanupOnError(EC);
3576 Buffer.release(); // The BitcodeReader owns it now.
3581 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3582 LLVMContext &Context) {
3583 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3586 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3587 DataStreamer *streamer,
3588 LLVMContext &Context,
3589 std::string *ErrMsg) {
3590 Module *M = new Module(name, Context);
3591 BitcodeReader *R = new BitcodeReader(streamer, Context);
3592 M->setMaterializer(R);
3593 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3595 *ErrMsg = EC.message();
3596 delete M; // Also deletes R.
3602 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3603 LLVMContext &Context) {
3604 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3605 ErrorOr<Module *> ModuleOrErr =
3606 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3609 Module *M = ModuleOrErr.get();
3610 // Read in the entire module, and destroy the BitcodeReader.
3611 if (std::error_code EC = M->materializeAllPermanently()) {
3616 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3617 // written. We must defer until the Module has been fully materialized.
3622 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3623 LLVMContext &Context) {
3624 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3625 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3626 ErrorOr<std::string> Triple = R->parseTriple();
3627 if (Triple.getError())
3629 return Triple.get();