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/DiagnosticPrinter.h"
19 #include "llvm/IR/InlineAsm.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/OperandTraits.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/DataStream.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
34 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
37 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
38 DiagnosticSeverity Severity,
40 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
42 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
44 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
45 std::error_code EC, const Twine &Message) {
46 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
47 DiagnosticHandler(DI);
51 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
53 return Error(DiagnosticHandler, EC, EC.message());
56 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
57 return ::Error(DiagnosticHandler, make_error_code(E), Message);
60 std::error_code BitcodeReader::Error(const Twine &Message) {
61 return ::Error(DiagnosticHandler,
62 make_error_code(BitcodeError::CorruptedBitcode), Message);
65 std::error_code BitcodeReader::Error(BitcodeError E) {
66 return ::Error(DiagnosticHandler, make_error_code(E));
69 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
73 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
76 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
77 DiagnosticHandlerFunction DiagnosticHandler)
78 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
79 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
80 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
81 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
82 WillMaterializeAllForwardRefs(false) {}
84 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
85 DiagnosticHandlerFunction DiagnosticHandler)
86 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
87 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
88 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
89 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
90 WillMaterializeAllForwardRefs(false) {}
92 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
93 if (WillMaterializeAllForwardRefs)
94 return std::error_code();
97 WillMaterializeAllForwardRefs = true;
99 while (!BasicBlockFwdRefQueue.empty()) {
100 Function *F = BasicBlockFwdRefQueue.front();
101 BasicBlockFwdRefQueue.pop_front();
102 assert(F && "Expected valid function");
103 if (!BasicBlockFwdRefs.count(F))
104 // Already materialized.
107 // Check for a function that isn't materializable to prevent an infinite
108 // loop. When parsing a blockaddress stored in a global variable, there
109 // isn't a trivial way to check if a function will have a body without a
110 // linear search through FunctionsWithBodies, so just check it here.
111 if (!F->isMaterializable())
112 return Error("Never resolved function from blockaddress");
114 // Try to materialize F.
115 if (std::error_code EC = materialize(F))
118 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
121 WillMaterializeAllForwardRefs = false;
122 return std::error_code();
125 void BitcodeReader::FreeState() {
127 std::vector<Type*>().swap(TypeList);
130 std::vector<Comdat *>().swap(ComdatList);
132 std::vector<AttributeSet>().swap(MAttributes);
133 std::vector<BasicBlock*>().swap(FunctionBBs);
134 std::vector<Function*>().swap(FunctionsWithBodies);
135 DeferredFunctionInfo.clear();
138 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
139 BasicBlockFwdRefQueue.clear();
142 //===----------------------------------------------------------------------===//
143 // Helper functions to implement forward reference resolution, etc.
144 //===----------------------------------------------------------------------===//
146 /// ConvertToString - Convert a string from a record into an std::string, return
148 template<typename StrTy>
149 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
151 if (Idx > Record.size())
154 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
155 Result += (char)Record[i];
159 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
161 default: // Map unknown/new linkages to external
163 return GlobalValue::ExternalLinkage;
165 return GlobalValue::WeakAnyLinkage;
167 return GlobalValue::AppendingLinkage;
169 return GlobalValue::InternalLinkage;
171 return GlobalValue::LinkOnceAnyLinkage;
173 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
175 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
177 return GlobalValue::ExternalWeakLinkage;
179 return GlobalValue::CommonLinkage;
181 return GlobalValue::PrivateLinkage;
183 return GlobalValue::WeakODRLinkage;
185 return GlobalValue::LinkOnceODRLinkage;
187 return GlobalValue::AvailableExternallyLinkage;
189 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
191 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
193 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
197 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
199 default: // Map unknown visibilities to default.
200 case 0: return GlobalValue::DefaultVisibility;
201 case 1: return GlobalValue::HiddenVisibility;
202 case 2: return GlobalValue::ProtectedVisibility;
206 static GlobalValue::DLLStorageClassTypes
207 GetDecodedDLLStorageClass(unsigned Val) {
209 default: // Map unknown values to default.
210 case 0: return GlobalValue::DefaultStorageClass;
211 case 1: return GlobalValue::DLLImportStorageClass;
212 case 2: return GlobalValue::DLLExportStorageClass;
216 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
218 case 0: return GlobalVariable::NotThreadLocal;
219 default: // Map unknown non-zero value to general dynamic.
220 case 1: return GlobalVariable::GeneralDynamicTLSModel;
221 case 2: return GlobalVariable::LocalDynamicTLSModel;
222 case 3: return GlobalVariable::InitialExecTLSModel;
223 case 4: return GlobalVariable::LocalExecTLSModel;
227 static int GetDecodedCastOpcode(unsigned Val) {
230 case bitc::CAST_TRUNC : return Instruction::Trunc;
231 case bitc::CAST_ZEXT : return Instruction::ZExt;
232 case bitc::CAST_SEXT : return Instruction::SExt;
233 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
234 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
235 case bitc::CAST_UITOFP : return Instruction::UIToFP;
236 case bitc::CAST_SITOFP : return Instruction::SIToFP;
237 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
238 case bitc::CAST_FPEXT : return Instruction::FPExt;
239 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
240 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
241 case bitc::CAST_BITCAST : return Instruction::BitCast;
242 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
245 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
248 case bitc::BINOP_ADD:
249 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
250 case bitc::BINOP_SUB:
251 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
252 case bitc::BINOP_MUL:
253 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
254 case bitc::BINOP_UDIV: return Instruction::UDiv;
255 case bitc::BINOP_SDIV:
256 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
257 case bitc::BINOP_UREM: return Instruction::URem;
258 case bitc::BINOP_SREM:
259 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
260 case bitc::BINOP_SHL: return Instruction::Shl;
261 case bitc::BINOP_LSHR: return Instruction::LShr;
262 case bitc::BINOP_ASHR: return Instruction::AShr;
263 case bitc::BINOP_AND: return Instruction::And;
264 case bitc::BINOP_OR: return Instruction::Or;
265 case bitc::BINOP_XOR: return Instruction::Xor;
269 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
271 default: return AtomicRMWInst::BAD_BINOP;
272 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
273 case bitc::RMW_ADD: return AtomicRMWInst::Add;
274 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
275 case bitc::RMW_AND: return AtomicRMWInst::And;
276 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
277 case bitc::RMW_OR: return AtomicRMWInst::Or;
278 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
279 case bitc::RMW_MAX: return AtomicRMWInst::Max;
280 case bitc::RMW_MIN: return AtomicRMWInst::Min;
281 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
282 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
286 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
288 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
289 case bitc::ORDERING_UNORDERED: return Unordered;
290 case bitc::ORDERING_MONOTONIC: return Monotonic;
291 case bitc::ORDERING_ACQUIRE: return Acquire;
292 case bitc::ORDERING_RELEASE: return Release;
293 case bitc::ORDERING_ACQREL: return AcquireRelease;
294 default: // Map unknown orderings to sequentially-consistent.
295 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
299 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
301 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
302 default: // Map unknown scopes to cross-thread.
303 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
307 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
309 default: // Map unknown selection kinds to any.
310 case bitc::COMDAT_SELECTION_KIND_ANY:
312 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
313 return Comdat::ExactMatch;
314 case bitc::COMDAT_SELECTION_KIND_LARGEST:
315 return Comdat::Largest;
316 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
317 return Comdat::NoDuplicates;
318 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
319 return Comdat::SameSize;
323 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
325 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
326 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
332 /// @brief A class for maintaining the slot number definition
333 /// as a placeholder for the actual definition for forward constants defs.
334 class ConstantPlaceHolder : public ConstantExpr {
335 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
337 // allocate space for exactly one operand
338 void *operator new(size_t s) {
339 return User::operator new(s, 1);
341 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
342 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
343 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
346 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
347 static bool classof(const Value *V) {
348 return isa<ConstantExpr>(V) &&
349 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
353 /// Provide fast operand accessors
354 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
358 // FIXME: can we inherit this from ConstantExpr?
360 struct OperandTraits<ConstantPlaceHolder> :
361 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
363 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
367 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
376 WeakVH &OldV = ValuePtrs[Idx];
382 // Handle constants and non-constants (e.g. instrs) differently for
384 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
385 ResolveConstants.push_back(std::make_pair(PHC, Idx));
388 // If there was a forward reference to this value, replace it.
389 Value *PrevVal = OldV;
390 OldV->replaceAllUsesWith(V);
396 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
401 if (Value *V = ValuePtrs[Idx]) {
402 assert(Ty == V->getType() && "Type mismatch in constant table!");
403 return cast<Constant>(V);
406 // Create and return a placeholder, which will later be RAUW'd.
407 Constant *C = new ConstantPlaceHolder(Ty, Context);
412 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
416 if (Value *V = ValuePtrs[Idx]) {
417 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
421 // No type specified, must be invalid reference.
422 if (!Ty) return nullptr;
424 // Create and return a placeholder, which will later be RAUW'd.
425 Value *V = new Argument(Ty);
430 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
431 /// resolves any forward references. The idea behind this is that we sometimes
432 /// get constants (such as large arrays) which reference *many* forward ref
433 /// constants. Replacing each of these causes a lot of thrashing when
434 /// building/reuniquing the constant. Instead of doing this, we look at all the
435 /// uses and rewrite all the place holders at once for any constant that uses
437 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
438 // Sort the values by-pointer so that they are efficient to look up with a
440 std::sort(ResolveConstants.begin(), ResolveConstants.end());
442 SmallVector<Constant*, 64> NewOps;
444 while (!ResolveConstants.empty()) {
445 Value *RealVal = operator[](ResolveConstants.back().second);
446 Constant *Placeholder = ResolveConstants.back().first;
447 ResolveConstants.pop_back();
449 // Loop over all users of the placeholder, updating them to reference the
450 // new value. If they reference more than one placeholder, update them all
452 while (!Placeholder->use_empty()) {
453 auto UI = Placeholder->user_begin();
456 // If the using object isn't uniqued, just update the operands. This
457 // handles instructions and initializers for global variables.
458 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
459 UI.getUse().set(RealVal);
463 // Otherwise, we have a constant that uses the placeholder. Replace that
464 // constant with a new constant that has *all* placeholder uses updated.
465 Constant *UserC = cast<Constant>(U);
466 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
469 if (!isa<ConstantPlaceHolder>(*I)) {
470 // Not a placeholder reference.
472 } else if (*I == Placeholder) {
473 // Common case is that it just references this one placeholder.
476 // Otherwise, look up the placeholder in ResolveConstants.
477 ResolveConstantsTy::iterator It =
478 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
479 std::pair<Constant*, unsigned>(cast<Constant>(*I),
481 assert(It != ResolveConstants.end() && It->first == *I);
482 NewOp = operator[](It->second);
485 NewOps.push_back(cast<Constant>(NewOp));
488 // Make the new constant.
490 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
491 NewC = ConstantArray::get(UserCA->getType(), NewOps);
492 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
493 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
494 } else if (isa<ConstantVector>(UserC)) {
495 NewC = ConstantVector::get(NewOps);
497 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
498 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
501 UserC->replaceAllUsesWith(NewC);
502 UserC->destroyConstant();
506 // Update all ValueHandles, they should be the only users at this point.
507 Placeholder->replaceAllUsesWith(RealVal);
512 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
521 TrackingMDRef &OldMD = MDValuePtrs[Idx];
527 // If there was a forward reference to this value, replace it.
528 MDNodeFwdDecl *PrevMD = cast<MDNodeFwdDecl>(OldMD.get());
529 PrevMD->replaceAllUsesWith(MD);
530 MDNode::deleteTemporary(PrevMD);
534 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
538 if (Metadata *MD = MDValuePtrs[Idx])
541 // Create and return a placeholder, which will later be RAUW'd.
544 Metadata *MD = MDNode::getTemporary(Context, None);
545 MDValuePtrs[Idx].reset(MD);
549 void BitcodeReaderMDValueList::tryToResolveCycles() {
555 // Still forward references... can't resolve cycles.
558 // Resolve any cycles.
559 for (auto &MD : MDValuePtrs) {
560 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Unexpected forward reference");
561 if (auto *N = dyn_cast_or_null<UniquableMDNode>(MD))
566 Type *BitcodeReader::getTypeByID(unsigned ID) {
567 // The type table size is always specified correctly.
568 if (ID >= TypeList.size())
571 if (Type *Ty = TypeList[ID])
574 // If we have a forward reference, the only possible case is when it is to a
575 // named struct. Just create a placeholder for now.
576 return TypeList[ID] = createIdentifiedStructType(Context);
579 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
581 auto *Ret = StructType::create(Context, Name);
582 IdentifiedStructTypes.push_back(Ret);
586 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
587 auto *Ret = StructType::create(Context);
588 IdentifiedStructTypes.push_back(Ret);
593 //===----------------------------------------------------------------------===//
594 // Functions for parsing blocks from the bitcode file
595 //===----------------------------------------------------------------------===//
598 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
599 /// been decoded from the given integer. This function must stay in sync with
600 /// 'encodeLLVMAttributesForBitcode'.
601 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
602 uint64_t EncodedAttrs) {
603 // FIXME: Remove in 4.0.
605 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
606 // the bits above 31 down by 11 bits.
607 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
608 assert((!Alignment || isPowerOf2_32(Alignment)) &&
609 "Alignment must be a power of two.");
612 B.addAlignmentAttr(Alignment);
613 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
614 (EncodedAttrs & 0xffff));
617 std::error_code BitcodeReader::ParseAttributeBlock() {
618 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
619 return Error("Invalid record");
621 if (!MAttributes.empty())
622 return Error("Invalid multiple blocks");
624 SmallVector<uint64_t, 64> Record;
626 SmallVector<AttributeSet, 8> Attrs;
628 // Read all the records.
630 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
632 switch (Entry.Kind) {
633 case BitstreamEntry::SubBlock: // Handled for us already.
634 case BitstreamEntry::Error:
635 return Error("Malformed block");
636 case BitstreamEntry::EndBlock:
637 return std::error_code();
638 case BitstreamEntry::Record:
639 // The interesting case.
645 switch (Stream.readRecord(Entry.ID, Record)) {
646 default: // Default behavior: ignore.
648 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
649 // FIXME: Remove in 4.0.
650 if (Record.size() & 1)
651 return Error("Invalid record");
653 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
655 decodeLLVMAttributesForBitcode(B, Record[i+1]);
656 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
659 MAttributes.push_back(AttributeSet::get(Context, Attrs));
663 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
664 for (unsigned i = 0, e = Record.size(); i != e; ++i)
665 Attrs.push_back(MAttributeGroups[Record[i]]);
667 MAttributes.push_back(AttributeSet::get(Context, Attrs));
675 // Returns Attribute::None on unrecognized codes.
676 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
679 return Attribute::None;
680 case bitc::ATTR_KIND_ALIGNMENT:
681 return Attribute::Alignment;
682 case bitc::ATTR_KIND_ALWAYS_INLINE:
683 return Attribute::AlwaysInline;
684 case bitc::ATTR_KIND_BUILTIN:
685 return Attribute::Builtin;
686 case bitc::ATTR_KIND_BY_VAL:
687 return Attribute::ByVal;
688 case bitc::ATTR_KIND_IN_ALLOCA:
689 return Attribute::InAlloca;
690 case bitc::ATTR_KIND_COLD:
691 return Attribute::Cold;
692 case bitc::ATTR_KIND_INLINE_HINT:
693 return Attribute::InlineHint;
694 case bitc::ATTR_KIND_IN_REG:
695 return Attribute::InReg;
696 case bitc::ATTR_KIND_JUMP_TABLE:
697 return Attribute::JumpTable;
698 case bitc::ATTR_KIND_MIN_SIZE:
699 return Attribute::MinSize;
700 case bitc::ATTR_KIND_NAKED:
701 return Attribute::Naked;
702 case bitc::ATTR_KIND_NEST:
703 return Attribute::Nest;
704 case bitc::ATTR_KIND_NO_ALIAS:
705 return Attribute::NoAlias;
706 case bitc::ATTR_KIND_NO_BUILTIN:
707 return Attribute::NoBuiltin;
708 case bitc::ATTR_KIND_NO_CAPTURE:
709 return Attribute::NoCapture;
710 case bitc::ATTR_KIND_NO_DUPLICATE:
711 return Attribute::NoDuplicate;
712 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
713 return Attribute::NoImplicitFloat;
714 case bitc::ATTR_KIND_NO_INLINE:
715 return Attribute::NoInline;
716 case bitc::ATTR_KIND_NON_LAZY_BIND:
717 return Attribute::NonLazyBind;
718 case bitc::ATTR_KIND_NON_NULL:
719 return Attribute::NonNull;
720 case bitc::ATTR_KIND_DEREFERENCEABLE:
721 return Attribute::Dereferenceable;
722 case bitc::ATTR_KIND_NO_RED_ZONE:
723 return Attribute::NoRedZone;
724 case bitc::ATTR_KIND_NO_RETURN:
725 return Attribute::NoReturn;
726 case bitc::ATTR_KIND_NO_UNWIND:
727 return Attribute::NoUnwind;
728 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
729 return Attribute::OptimizeForSize;
730 case bitc::ATTR_KIND_OPTIMIZE_NONE:
731 return Attribute::OptimizeNone;
732 case bitc::ATTR_KIND_READ_NONE:
733 return Attribute::ReadNone;
734 case bitc::ATTR_KIND_READ_ONLY:
735 return Attribute::ReadOnly;
736 case bitc::ATTR_KIND_RETURNED:
737 return Attribute::Returned;
738 case bitc::ATTR_KIND_RETURNS_TWICE:
739 return Attribute::ReturnsTwice;
740 case bitc::ATTR_KIND_S_EXT:
741 return Attribute::SExt;
742 case bitc::ATTR_KIND_STACK_ALIGNMENT:
743 return Attribute::StackAlignment;
744 case bitc::ATTR_KIND_STACK_PROTECT:
745 return Attribute::StackProtect;
746 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
747 return Attribute::StackProtectReq;
748 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
749 return Attribute::StackProtectStrong;
750 case bitc::ATTR_KIND_STRUCT_RET:
751 return Attribute::StructRet;
752 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
753 return Attribute::SanitizeAddress;
754 case bitc::ATTR_KIND_SANITIZE_THREAD:
755 return Attribute::SanitizeThread;
756 case bitc::ATTR_KIND_SANITIZE_MEMORY:
757 return Attribute::SanitizeMemory;
758 case bitc::ATTR_KIND_UW_TABLE:
759 return Attribute::UWTable;
760 case bitc::ATTR_KIND_Z_EXT:
761 return Attribute::ZExt;
765 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
766 Attribute::AttrKind *Kind) {
767 *Kind = GetAttrFromCode(Code);
768 if (*Kind == Attribute::None)
769 return Error(BitcodeError::CorruptedBitcode,
770 "Unknown attribute kind (" + Twine(Code) + ")");
771 return std::error_code();
774 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
775 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
776 return Error("Invalid record");
778 if (!MAttributeGroups.empty())
779 return Error("Invalid multiple blocks");
781 SmallVector<uint64_t, 64> Record;
783 // Read all the records.
785 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
787 switch (Entry.Kind) {
788 case BitstreamEntry::SubBlock: // Handled for us already.
789 case BitstreamEntry::Error:
790 return Error("Malformed block");
791 case BitstreamEntry::EndBlock:
792 return std::error_code();
793 case BitstreamEntry::Record:
794 // The interesting case.
800 switch (Stream.readRecord(Entry.ID, Record)) {
801 default: // Default behavior: ignore.
803 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
804 if (Record.size() < 3)
805 return Error("Invalid record");
807 uint64_t GrpID = Record[0];
808 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
811 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
812 if (Record[i] == 0) { // Enum attribute
813 Attribute::AttrKind Kind;
814 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
817 B.addAttribute(Kind);
818 } else if (Record[i] == 1) { // Integer attribute
819 Attribute::AttrKind Kind;
820 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
822 if (Kind == Attribute::Alignment)
823 B.addAlignmentAttr(Record[++i]);
824 else if (Kind == Attribute::StackAlignment)
825 B.addStackAlignmentAttr(Record[++i]);
826 else if (Kind == Attribute::Dereferenceable)
827 B.addDereferenceableAttr(Record[++i]);
828 } else { // String attribute
829 assert((Record[i] == 3 || Record[i] == 4) &&
830 "Invalid attribute group entry");
831 bool HasValue = (Record[i++] == 4);
832 SmallString<64> KindStr;
833 SmallString<64> ValStr;
835 while (Record[i] != 0 && i != e)
836 KindStr += Record[i++];
837 assert(Record[i] == 0 && "Kind string not null terminated");
840 // Has a value associated with it.
841 ++i; // Skip the '0' that terminates the "kind" string.
842 while (Record[i] != 0 && i != e)
843 ValStr += Record[i++];
844 assert(Record[i] == 0 && "Value string not null terminated");
847 B.addAttribute(KindStr.str(), ValStr.str());
851 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
858 std::error_code BitcodeReader::ParseTypeTable() {
859 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
860 return Error("Invalid record");
862 return ParseTypeTableBody();
865 std::error_code BitcodeReader::ParseTypeTableBody() {
866 if (!TypeList.empty())
867 return Error("Invalid multiple blocks");
869 SmallVector<uint64_t, 64> Record;
870 unsigned NumRecords = 0;
872 SmallString<64> TypeName;
874 // Read all the records for this type table.
876 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
878 switch (Entry.Kind) {
879 case BitstreamEntry::SubBlock: // Handled for us already.
880 case BitstreamEntry::Error:
881 return Error("Malformed block");
882 case BitstreamEntry::EndBlock:
883 if (NumRecords != TypeList.size())
884 return Error("Malformed block");
885 return std::error_code();
886 case BitstreamEntry::Record:
887 // The interesting case.
893 Type *ResultTy = nullptr;
894 switch (Stream.readRecord(Entry.ID, Record)) {
896 return Error("Invalid value");
897 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
898 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
899 // type list. This allows us to reserve space.
900 if (Record.size() < 1)
901 return Error("Invalid record");
902 TypeList.resize(Record[0]);
904 case bitc::TYPE_CODE_VOID: // VOID
905 ResultTy = Type::getVoidTy(Context);
907 case bitc::TYPE_CODE_HALF: // HALF
908 ResultTy = Type::getHalfTy(Context);
910 case bitc::TYPE_CODE_FLOAT: // FLOAT
911 ResultTy = Type::getFloatTy(Context);
913 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
914 ResultTy = Type::getDoubleTy(Context);
916 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
917 ResultTy = Type::getX86_FP80Ty(Context);
919 case bitc::TYPE_CODE_FP128: // FP128
920 ResultTy = Type::getFP128Ty(Context);
922 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
923 ResultTy = Type::getPPC_FP128Ty(Context);
925 case bitc::TYPE_CODE_LABEL: // LABEL
926 ResultTy = Type::getLabelTy(Context);
928 case bitc::TYPE_CODE_METADATA: // METADATA
929 ResultTy = Type::getMetadataTy(Context);
931 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
932 ResultTy = Type::getX86_MMXTy(Context);
934 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
935 if (Record.size() < 1)
936 return Error("Invalid record");
938 ResultTy = IntegerType::get(Context, Record[0]);
940 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
941 // [pointee type, address space]
942 if (Record.size() < 1)
943 return Error("Invalid record");
944 unsigned AddressSpace = 0;
945 if (Record.size() == 2)
946 AddressSpace = Record[1];
947 ResultTy = getTypeByID(Record[0]);
949 return Error("Invalid type");
950 ResultTy = PointerType::get(ResultTy, AddressSpace);
953 case bitc::TYPE_CODE_FUNCTION_OLD: {
954 // FIXME: attrid is dead, remove it in LLVM 4.0
955 // FUNCTION: [vararg, attrid, retty, paramty x N]
956 if (Record.size() < 3)
957 return Error("Invalid record");
958 SmallVector<Type*, 8> ArgTys;
959 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
960 if (Type *T = getTypeByID(Record[i]))
966 ResultTy = getTypeByID(Record[2]);
967 if (!ResultTy || ArgTys.size() < Record.size()-3)
968 return Error("Invalid type");
970 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
973 case bitc::TYPE_CODE_FUNCTION: {
974 // FUNCTION: [vararg, retty, paramty x N]
975 if (Record.size() < 2)
976 return Error("Invalid record");
977 SmallVector<Type*, 8> ArgTys;
978 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
979 if (Type *T = getTypeByID(Record[i]))
985 ResultTy = getTypeByID(Record[1]);
986 if (!ResultTy || ArgTys.size() < Record.size()-2)
987 return Error("Invalid type");
989 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
992 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
993 if (Record.size() < 1)
994 return Error("Invalid record");
995 SmallVector<Type*, 8> EltTys;
996 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
997 if (Type *T = getTypeByID(Record[i]))
1002 if (EltTys.size() != Record.size()-1)
1003 return Error("Invalid type");
1004 ResultTy = StructType::get(Context, EltTys, Record[0]);
1007 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1008 if (ConvertToString(Record, 0, TypeName))
1009 return Error("Invalid record");
1012 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1013 if (Record.size() < 1)
1014 return Error("Invalid record");
1016 if (NumRecords >= TypeList.size())
1017 return Error("Invalid TYPE table");
1019 // Check to see if this was forward referenced, if so fill in the temp.
1020 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1022 Res->setName(TypeName);
1023 TypeList[NumRecords] = nullptr;
1024 } else // Otherwise, create a new struct.
1025 Res = createIdentifiedStructType(Context, TypeName);
1028 SmallVector<Type*, 8> EltTys;
1029 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1030 if (Type *T = getTypeByID(Record[i]))
1031 EltTys.push_back(T);
1035 if (EltTys.size() != Record.size()-1)
1036 return Error("Invalid record");
1037 Res->setBody(EltTys, Record[0]);
1041 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1042 if (Record.size() != 1)
1043 return Error("Invalid record");
1045 if (NumRecords >= TypeList.size())
1046 return Error("Invalid TYPE table");
1048 // Check to see if this was forward referenced, if so fill in the temp.
1049 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1051 Res->setName(TypeName);
1052 TypeList[NumRecords] = nullptr;
1053 } else // Otherwise, create a new struct with no body.
1054 Res = createIdentifiedStructType(Context, TypeName);
1059 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1060 if (Record.size() < 2)
1061 return Error("Invalid record");
1062 if ((ResultTy = getTypeByID(Record[1])))
1063 ResultTy = ArrayType::get(ResultTy, Record[0]);
1065 return Error("Invalid type");
1067 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1068 if (Record.size() < 2)
1069 return Error("Invalid record");
1070 if ((ResultTy = getTypeByID(Record[1])))
1071 ResultTy = VectorType::get(ResultTy, Record[0]);
1073 return Error("Invalid type");
1077 if (NumRecords >= TypeList.size())
1078 return Error("Invalid TYPE table");
1079 assert(ResultTy && "Didn't read a type?");
1080 assert(!TypeList[NumRecords] && "Already read type?");
1081 TypeList[NumRecords++] = ResultTy;
1085 std::error_code BitcodeReader::ParseValueSymbolTable() {
1086 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1087 return Error("Invalid record");
1089 SmallVector<uint64_t, 64> Record;
1091 // Read all the records for this value table.
1092 SmallString<128> ValueName;
1094 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1096 switch (Entry.Kind) {
1097 case BitstreamEntry::SubBlock: // Handled for us already.
1098 case BitstreamEntry::Error:
1099 return Error("Malformed block");
1100 case BitstreamEntry::EndBlock:
1101 return std::error_code();
1102 case BitstreamEntry::Record:
1103 // The interesting case.
1109 switch (Stream.readRecord(Entry.ID, Record)) {
1110 default: // Default behavior: unknown type.
1112 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1113 if (ConvertToString(Record, 1, ValueName))
1114 return Error("Invalid record");
1115 unsigned ValueID = Record[0];
1116 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1117 return Error("Invalid record");
1118 Value *V = ValueList[ValueID];
1120 V->setName(StringRef(ValueName.data(), ValueName.size()));
1124 case bitc::VST_CODE_BBENTRY: {
1125 if (ConvertToString(Record, 1, ValueName))
1126 return Error("Invalid record");
1127 BasicBlock *BB = getBasicBlock(Record[0]);
1129 return Error("Invalid record");
1131 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1139 std::error_code BitcodeReader::ParseMetadata() {
1140 unsigned NextMDValueNo = MDValueList.size();
1142 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1143 return Error("Invalid record");
1145 SmallVector<uint64_t, 64> Record;
1147 // Read all the records.
1149 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1151 switch (Entry.Kind) {
1152 case BitstreamEntry::SubBlock: // Handled for us already.
1153 case BitstreamEntry::Error:
1154 return Error("Malformed block");
1155 case BitstreamEntry::EndBlock:
1156 MDValueList.tryToResolveCycles();
1157 return std::error_code();
1158 case BitstreamEntry::Record:
1159 // The interesting case.
1165 unsigned Code = Stream.readRecord(Entry.ID, Record);
1166 bool IsDistinct = false;
1168 default: // Default behavior: ignore.
1170 case bitc::METADATA_NAME: {
1171 // Read name of the named metadata.
1172 SmallString<8> Name(Record.begin(), Record.end());
1174 Code = Stream.ReadCode();
1176 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1177 unsigned NextBitCode = Stream.readRecord(Code, Record);
1178 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1180 // Read named metadata elements.
1181 unsigned Size = Record.size();
1182 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1183 for (unsigned i = 0; i != Size; ++i) {
1184 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1186 return Error("Invalid record");
1187 NMD->addOperand(MD);
1191 case bitc::METADATA_OLD_FN_NODE: {
1192 // FIXME: Remove in 4.0.
1193 // This is a LocalAsMetadata record, the only type of function-local
1195 if (Record.size() % 2 == 1)
1196 return Error("Invalid record");
1198 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1199 // to be legal, but there's no upgrade path.
1200 auto dropRecord = [&] {
1201 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1203 if (Record.size() != 2) {
1208 Type *Ty = getTypeByID(Record[0]);
1209 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1214 MDValueList.AssignValue(
1215 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1219 case bitc::METADATA_OLD_NODE: {
1220 // FIXME: Remove in 4.0.
1221 if (Record.size() % 2 == 1)
1222 return Error("Invalid record");
1224 unsigned Size = Record.size();
1225 SmallVector<Metadata *, 8> Elts;
1226 for (unsigned i = 0; i != Size; i += 2) {
1227 Type *Ty = getTypeByID(Record[i]);
1229 return Error("Invalid record");
1230 if (Ty->isMetadataTy())
1231 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1232 else if (!Ty->isVoidTy()) {
1234 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1235 assert(isa<ConstantAsMetadata>(MD) &&
1236 "Expected non-function-local metadata");
1239 Elts.push_back(nullptr);
1241 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1244 case bitc::METADATA_VALUE: {
1245 if (Record.size() != 2)
1246 return Error("Invalid record");
1248 Type *Ty = getTypeByID(Record[0]);
1249 if (Ty->isMetadataTy() || Ty->isVoidTy())
1250 return Error("Invalid record");
1252 MDValueList.AssignValue(
1253 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1257 case bitc::METADATA_DISTINCT_NODE:
1260 case bitc::METADATA_NODE: {
1261 SmallVector<Metadata *, 8> Elts;
1262 Elts.reserve(Record.size());
1263 for (unsigned ID : Record)
1264 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1265 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1266 : MDNode::get(Context, Elts),
1270 case bitc::METADATA_LOCATION: {
1271 if (Record.size() != 5)
1272 return Error("Invalid record");
1274 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1275 unsigned Line = Record[1];
1276 unsigned Column = Record[2];
1277 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1278 Metadata *InlinedAt =
1279 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1280 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1284 case bitc::METADATA_STRING: {
1285 std::string String(Record.begin(), Record.end());
1286 llvm::UpgradeMDStringConstant(String);
1287 Metadata *MD = MDString::get(Context, String);
1288 MDValueList.AssignValue(MD, NextMDValueNo++);
1291 case bitc::METADATA_KIND: {
1292 if (Record.size() < 2)
1293 return Error("Invalid record");
1295 unsigned Kind = Record[0];
1296 SmallString<8> Name(Record.begin()+1, Record.end());
1298 unsigned NewKind = TheModule->getMDKindID(Name.str());
1299 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1300 return Error("Conflicting METADATA_KIND records");
1307 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1308 /// the LSB for dense VBR encoding.
1309 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1314 // There is no such thing as -0 with integers. "-0" really means MININT.
1318 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1319 /// values and aliases that we can.
1320 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1321 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1322 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1323 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1324 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1326 GlobalInitWorklist.swap(GlobalInits);
1327 AliasInitWorklist.swap(AliasInits);
1328 FunctionPrefixWorklist.swap(FunctionPrefixes);
1329 FunctionPrologueWorklist.swap(FunctionPrologues);
1331 while (!GlobalInitWorklist.empty()) {
1332 unsigned ValID = GlobalInitWorklist.back().second;
1333 if (ValID >= ValueList.size()) {
1334 // Not ready to resolve this yet, it requires something later in the file.
1335 GlobalInits.push_back(GlobalInitWorklist.back());
1337 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1338 GlobalInitWorklist.back().first->setInitializer(C);
1340 return Error("Expected a constant");
1342 GlobalInitWorklist.pop_back();
1345 while (!AliasInitWorklist.empty()) {
1346 unsigned ValID = AliasInitWorklist.back().second;
1347 if (ValID >= ValueList.size()) {
1348 AliasInits.push_back(AliasInitWorklist.back());
1350 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1351 AliasInitWorklist.back().first->setAliasee(C);
1353 return Error("Expected a constant");
1355 AliasInitWorklist.pop_back();
1358 while (!FunctionPrefixWorklist.empty()) {
1359 unsigned ValID = FunctionPrefixWorklist.back().second;
1360 if (ValID >= ValueList.size()) {
1361 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1363 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1364 FunctionPrefixWorklist.back().first->setPrefixData(C);
1366 return Error("Expected a constant");
1368 FunctionPrefixWorklist.pop_back();
1371 while (!FunctionPrologueWorklist.empty()) {
1372 unsigned ValID = FunctionPrologueWorklist.back().second;
1373 if (ValID >= ValueList.size()) {
1374 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1376 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1377 FunctionPrologueWorklist.back().first->setPrologueData(C);
1379 return Error("Expected a constant");
1381 FunctionPrologueWorklist.pop_back();
1384 return std::error_code();
1387 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1388 SmallVector<uint64_t, 8> Words(Vals.size());
1389 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1390 BitcodeReader::decodeSignRotatedValue);
1392 return APInt(TypeBits, Words);
1395 std::error_code BitcodeReader::ParseConstants() {
1396 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1397 return Error("Invalid record");
1399 SmallVector<uint64_t, 64> Record;
1401 // Read all the records for this value table.
1402 Type *CurTy = Type::getInt32Ty(Context);
1403 unsigned NextCstNo = ValueList.size();
1405 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1407 switch (Entry.Kind) {
1408 case BitstreamEntry::SubBlock: // Handled for us already.
1409 case BitstreamEntry::Error:
1410 return Error("Malformed block");
1411 case BitstreamEntry::EndBlock:
1412 if (NextCstNo != ValueList.size())
1413 return Error("Invalid ronstant reference");
1415 // Once all the constants have been read, go through and resolve forward
1417 ValueList.ResolveConstantForwardRefs();
1418 return std::error_code();
1419 case BitstreamEntry::Record:
1420 // The interesting case.
1427 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1429 default: // Default behavior: unknown constant
1430 case bitc::CST_CODE_UNDEF: // UNDEF
1431 V = UndefValue::get(CurTy);
1433 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1435 return Error("Invalid record");
1436 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1437 return Error("Invalid record");
1438 CurTy = TypeList[Record[0]];
1439 continue; // Skip the ValueList manipulation.
1440 case bitc::CST_CODE_NULL: // NULL
1441 V = Constant::getNullValue(CurTy);
1443 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1444 if (!CurTy->isIntegerTy() || Record.empty())
1445 return Error("Invalid record");
1446 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1448 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1449 if (!CurTy->isIntegerTy() || Record.empty())
1450 return Error("Invalid record");
1452 APInt VInt = ReadWideAPInt(Record,
1453 cast<IntegerType>(CurTy)->getBitWidth());
1454 V = ConstantInt::get(Context, VInt);
1458 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1460 return Error("Invalid record");
1461 if (CurTy->isHalfTy())
1462 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1463 APInt(16, (uint16_t)Record[0])));
1464 else if (CurTy->isFloatTy())
1465 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1466 APInt(32, (uint32_t)Record[0])));
1467 else if (CurTy->isDoubleTy())
1468 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1469 APInt(64, Record[0])));
1470 else if (CurTy->isX86_FP80Ty()) {
1471 // Bits are not stored the same way as a normal i80 APInt, compensate.
1472 uint64_t Rearrange[2];
1473 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1474 Rearrange[1] = Record[0] >> 48;
1475 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1476 APInt(80, Rearrange)));
1477 } else if (CurTy->isFP128Ty())
1478 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1479 APInt(128, Record)));
1480 else if (CurTy->isPPC_FP128Ty())
1481 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1482 APInt(128, Record)));
1484 V = UndefValue::get(CurTy);
1488 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1490 return Error("Invalid record");
1492 unsigned Size = Record.size();
1493 SmallVector<Constant*, 16> Elts;
1495 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1496 for (unsigned i = 0; i != Size; ++i)
1497 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1498 STy->getElementType(i)));
1499 V = ConstantStruct::get(STy, Elts);
1500 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1501 Type *EltTy = ATy->getElementType();
1502 for (unsigned i = 0; i != Size; ++i)
1503 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1504 V = ConstantArray::get(ATy, Elts);
1505 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1506 Type *EltTy = VTy->getElementType();
1507 for (unsigned i = 0; i != Size; ++i)
1508 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1509 V = ConstantVector::get(Elts);
1511 V = UndefValue::get(CurTy);
1515 case bitc::CST_CODE_STRING: // STRING: [values]
1516 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1518 return Error("Invalid record");
1520 SmallString<16> Elts(Record.begin(), Record.end());
1521 V = ConstantDataArray::getString(Context, Elts,
1522 BitCode == bitc::CST_CODE_CSTRING);
1525 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1527 return Error("Invalid record");
1529 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1530 unsigned Size = Record.size();
1532 if (EltTy->isIntegerTy(8)) {
1533 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1534 if (isa<VectorType>(CurTy))
1535 V = ConstantDataVector::get(Context, Elts);
1537 V = ConstantDataArray::get(Context, Elts);
1538 } else if (EltTy->isIntegerTy(16)) {
1539 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1540 if (isa<VectorType>(CurTy))
1541 V = ConstantDataVector::get(Context, Elts);
1543 V = ConstantDataArray::get(Context, Elts);
1544 } else if (EltTy->isIntegerTy(32)) {
1545 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1546 if (isa<VectorType>(CurTy))
1547 V = ConstantDataVector::get(Context, Elts);
1549 V = ConstantDataArray::get(Context, Elts);
1550 } else if (EltTy->isIntegerTy(64)) {
1551 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1552 if (isa<VectorType>(CurTy))
1553 V = ConstantDataVector::get(Context, Elts);
1555 V = ConstantDataArray::get(Context, Elts);
1556 } else if (EltTy->isFloatTy()) {
1557 SmallVector<float, 16> Elts(Size);
1558 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1559 if (isa<VectorType>(CurTy))
1560 V = ConstantDataVector::get(Context, Elts);
1562 V = ConstantDataArray::get(Context, Elts);
1563 } else if (EltTy->isDoubleTy()) {
1564 SmallVector<double, 16> Elts(Size);
1565 std::transform(Record.begin(), Record.end(), Elts.begin(),
1567 if (isa<VectorType>(CurTy))
1568 V = ConstantDataVector::get(Context, Elts);
1570 V = ConstantDataArray::get(Context, Elts);
1572 return Error("Invalid type for value");
1577 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1578 if (Record.size() < 3)
1579 return Error("Invalid record");
1580 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1582 V = UndefValue::get(CurTy); // Unknown binop.
1584 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1585 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1587 if (Record.size() >= 4) {
1588 if (Opc == Instruction::Add ||
1589 Opc == Instruction::Sub ||
1590 Opc == Instruction::Mul ||
1591 Opc == Instruction::Shl) {
1592 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1593 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1594 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1595 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1596 } else if (Opc == Instruction::SDiv ||
1597 Opc == Instruction::UDiv ||
1598 Opc == Instruction::LShr ||
1599 Opc == Instruction::AShr) {
1600 if (Record[3] & (1 << bitc::PEO_EXACT))
1601 Flags |= SDivOperator::IsExact;
1604 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1608 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1609 if (Record.size() < 3)
1610 return Error("Invalid record");
1611 int Opc = GetDecodedCastOpcode(Record[0]);
1613 V = UndefValue::get(CurTy); // Unknown cast.
1615 Type *OpTy = getTypeByID(Record[1]);
1617 return Error("Invalid record");
1618 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1619 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1620 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1624 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1625 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1626 if (Record.size() & 1)
1627 return Error("Invalid record");
1628 SmallVector<Constant*, 16> Elts;
1629 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1630 Type *ElTy = getTypeByID(Record[i]);
1632 return Error("Invalid record");
1633 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1635 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1636 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1638 bitc::CST_CODE_CE_INBOUNDS_GEP);
1641 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1642 if (Record.size() < 3)
1643 return Error("Invalid record");
1645 Type *SelectorTy = Type::getInt1Ty(Context);
1647 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1648 // vector. Otherwise, it must be a single bit.
1649 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1650 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1651 VTy->getNumElements());
1653 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1655 ValueList.getConstantFwdRef(Record[1],CurTy),
1656 ValueList.getConstantFwdRef(Record[2],CurTy));
1659 case bitc::CST_CODE_CE_EXTRACTELT
1660 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1661 if (Record.size() < 3)
1662 return Error("Invalid record");
1664 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1666 return Error("Invalid record");
1667 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1668 Constant *Op1 = nullptr;
1669 if (Record.size() == 4) {
1670 Type *IdxTy = getTypeByID(Record[2]);
1672 return Error("Invalid record");
1673 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1674 } else // TODO: Remove with llvm 4.0
1675 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1677 return Error("Invalid record");
1678 V = ConstantExpr::getExtractElement(Op0, Op1);
1681 case bitc::CST_CODE_CE_INSERTELT
1682 : { // CE_INSERTELT: [opval, opval, opty, opval]
1683 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1684 if (Record.size() < 3 || !OpTy)
1685 return Error("Invalid record");
1686 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1687 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1688 OpTy->getElementType());
1689 Constant *Op2 = nullptr;
1690 if (Record.size() == 4) {
1691 Type *IdxTy = getTypeByID(Record[2]);
1693 return Error("Invalid record");
1694 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1695 } else // TODO: Remove with llvm 4.0
1696 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1698 return Error("Invalid record");
1699 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1702 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1703 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1704 if (Record.size() < 3 || !OpTy)
1705 return Error("Invalid record");
1706 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1707 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1708 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1709 OpTy->getNumElements());
1710 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1711 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1714 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1715 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1717 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1718 if (Record.size() < 4 || !RTy || !OpTy)
1719 return Error("Invalid record");
1720 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1721 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1722 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1723 RTy->getNumElements());
1724 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1725 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1728 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1729 if (Record.size() < 4)
1730 return Error("Invalid record");
1731 Type *OpTy = getTypeByID(Record[0]);
1733 return Error("Invalid record");
1734 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1735 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1737 if (OpTy->isFPOrFPVectorTy())
1738 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1740 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1743 // This maintains backward compatibility, pre-asm dialect keywords.
1744 // FIXME: Remove with the 4.0 release.
1745 case bitc::CST_CODE_INLINEASM_OLD: {
1746 if (Record.size() < 2)
1747 return Error("Invalid record");
1748 std::string AsmStr, ConstrStr;
1749 bool HasSideEffects = Record[0] & 1;
1750 bool IsAlignStack = Record[0] >> 1;
1751 unsigned AsmStrSize = Record[1];
1752 if (2+AsmStrSize >= Record.size())
1753 return Error("Invalid record");
1754 unsigned ConstStrSize = Record[2+AsmStrSize];
1755 if (3+AsmStrSize+ConstStrSize > Record.size())
1756 return Error("Invalid record");
1758 for (unsigned i = 0; i != AsmStrSize; ++i)
1759 AsmStr += (char)Record[2+i];
1760 for (unsigned i = 0; i != ConstStrSize; ++i)
1761 ConstrStr += (char)Record[3+AsmStrSize+i];
1762 PointerType *PTy = cast<PointerType>(CurTy);
1763 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1764 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1767 // This version adds support for the asm dialect keywords (e.g.,
1769 case bitc::CST_CODE_INLINEASM: {
1770 if (Record.size() < 2)
1771 return Error("Invalid record");
1772 std::string AsmStr, ConstrStr;
1773 bool HasSideEffects = Record[0] & 1;
1774 bool IsAlignStack = (Record[0] >> 1) & 1;
1775 unsigned AsmDialect = Record[0] >> 2;
1776 unsigned AsmStrSize = Record[1];
1777 if (2+AsmStrSize >= Record.size())
1778 return Error("Invalid record");
1779 unsigned ConstStrSize = Record[2+AsmStrSize];
1780 if (3+AsmStrSize+ConstStrSize > Record.size())
1781 return Error("Invalid record");
1783 for (unsigned i = 0; i != AsmStrSize; ++i)
1784 AsmStr += (char)Record[2+i];
1785 for (unsigned i = 0; i != ConstStrSize; ++i)
1786 ConstrStr += (char)Record[3+AsmStrSize+i];
1787 PointerType *PTy = cast<PointerType>(CurTy);
1788 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1789 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1790 InlineAsm::AsmDialect(AsmDialect));
1793 case bitc::CST_CODE_BLOCKADDRESS:{
1794 if (Record.size() < 3)
1795 return Error("Invalid record");
1796 Type *FnTy = getTypeByID(Record[0]);
1798 return Error("Invalid record");
1800 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1802 return Error("Invalid record");
1804 // Don't let Fn get dematerialized.
1805 BlockAddressesTaken.insert(Fn);
1807 // If the function is already parsed we can insert the block address right
1810 unsigned BBID = Record[2];
1812 // Invalid reference to entry block.
1813 return Error("Invalid ID");
1815 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1816 for (size_t I = 0, E = BBID; I != E; ++I) {
1818 return Error("Invalid ID");
1823 // Otherwise insert a placeholder and remember it so it can be inserted
1824 // when the function is parsed.
1825 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1827 BasicBlockFwdRefQueue.push_back(Fn);
1828 if (FwdBBs.size() < BBID + 1)
1829 FwdBBs.resize(BBID + 1);
1831 FwdBBs[BBID] = BasicBlock::Create(Context);
1834 V = BlockAddress::get(Fn, BB);
1839 ValueList.AssignValue(V, NextCstNo);
1844 std::error_code BitcodeReader::ParseUseLists() {
1845 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1846 return Error("Invalid record");
1848 // Read all the records.
1849 SmallVector<uint64_t, 64> Record;
1851 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1853 switch (Entry.Kind) {
1854 case BitstreamEntry::SubBlock: // Handled for us already.
1855 case BitstreamEntry::Error:
1856 return Error("Malformed block");
1857 case BitstreamEntry::EndBlock:
1858 return std::error_code();
1859 case BitstreamEntry::Record:
1860 // The interesting case.
1864 // Read a use list record.
1867 switch (Stream.readRecord(Entry.ID, Record)) {
1868 default: // Default behavior: unknown type.
1870 case bitc::USELIST_CODE_BB:
1873 case bitc::USELIST_CODE_DEFAULT: {
1874 unsigned RecordLength = Record.size();
1875 if (RecordLength < 3)
1876 // Records should have at least an ID and two indexes.
1877 return Error("Invalid record");
1878 unsigned ID = Record.back();
1883 assert(ID < FunctionBBs.size() && "Basic block not found");
1884 V = FunctionBBs[ID];
1887 unsigned NumUses = 0;
1888 SmallDenseMap<const Use *, unsigned, 16> Order;
1889 for (const Use &U : V->uses()) {
1890 if (++NumUses > Record.size())
1892 Order[&U] = Record[NumUses - 1];
1894 if (Order.size() != Record.size() || NumUses > Record.size())
1895 // Mismatches can happen if the functions are being materialized lazily
1896 // (out-of-order), or a value has been upgraded.
1899 V->sortUseList([&](const Use &L, const Use &R) {
1900 return Order.lookup(&L) < Order.lookup(&R);
1908 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1909 /// remember where it is and then skip it. This lets us lazily deserialize the
1911 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1912 // Get the function we are talking about.
1913 if (FunctionsWithBodies.empty())
1914 return Error("Insufficient function protos");
1916 Function *Fn = FunctionsWithBodies.back();
1917 FunctionsWithBodies.pop_back();
1919 // Save the current stream state.
1920 uint64_t CurBit = Stream.GetCurrentBitNo();
1921 DeferredFunctionInfo[Fn] = CurBit;
1923 // Skip over the function block for now.
1924 if (Stream.SkipBlock())
1925 return Error("Invalid record");
1926 return std::error_code();
1929 std::error_code BitcodeReader::GlobalCleanup() {
1930 // Patch the initializers for globals and aliases up.
1931 ResolveGlobalAndAliasInits();
1932 if (!GlobalInits.empty() || !AliasInits.empty())
1933 return Error("Malformed global initializer set");
1935 // Look for intrinsic functions which need to be upgraded at some point
1936 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1939 if (UpgradeIntrinsicFunction(FI, NewFn))
1940 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1943 // Look for global variables which need to be renamed.
1944 for (Module::global_iterator
1945 GI = TheModule->global_begin(), GE = TheModule->global_end();
1947 GlobalVariable *GV = GI++;
1948 UpgradeGlobalVariable(GV);
1951 // Force deallocation of memory for these vectors to favor the client that
1952 // want lazy deserialization.
1953 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1954 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1955 return std::error_code();
1958 std::error_code BitcodeReader::ParseModule(bool Resume) {
1960 Stream.JumpToBit(NextUnreadBit);
1961 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1962 return Error("Invalid record");
1964 SmallVector<uint64_t, 64> Record;
1965 std::vector<std::string> SectionTable;
1966 std::vector<std::string> GCTable;
1968 // Read all the records for this module.
1970 BitstreamEntry Entry = Stream.advance();
1972 switch (Entry.Kind) {
1973 case BitstreamEntry::Error:
1974 return Error("Malformed block");
1975 case BitstreamEntry::EndBlock:
1976 return GlobalCleanup();
1978 case BitstreamEntry::SubBlock:
1980 default: // Skip unknown content.
1981 if (Stream.SkipBlock())
1982 return Error("Invalid record");
1984 case bitc::BLOCKINFO_BLOCK_ID:
1985 if (Stream.ReadBlockInfoBlock())
1986 return Error("Malformed block");
1988 case bitc::PARAMATTR_BLOCK_ID:
1989 if (std::error_code EC = ParseAttributeBlock())
1992 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1993 if (std::error_code EC = ParseAttributeGroupBlock())
1996 case bitc::TYPE_BLOCK_ID_NEW:
1997 if (std::error_code EC = ParseTypeTable())
2000 case bitc::VALUE_SYMTAB_BLOCK_ID:
2001 if (std::error_code EC = ParseValueSymbolTable())
2003 SeenValueSymbolTable = true;
2005 case bitc::CONSTANTS_BLOCK_ID:
2006 if (std::error_code EC = ParseConstants())
2008 if (std::error_code EC = ResolveGlobalAndAliasInits())
2011 case bitc::METADATA_BLOCK_ID:
2012 if (std::error_code EC = ParseMetadata())
2015 case bitc::FUNCTION_BLOCK_ID:
2016 // If this is the first function body we've seen, reverse the
2017 // FunctionsWithBodies list.
2018 if (!SeenFirstFunctionBody) {
2019 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2020 if (std::error_code EC = GlobalCleanup())
2022 SeenFirstFunctionBody = true;
2025 if (std::error_code EC = RememberAndSkipFunctionBody())
2027 // For streaming bitcode, suspend parsing when we reach the function
2028 // bodies. Subsequent materialization calls will resume it when
2029 // necessary. For streaming, the function bodies must be at the end of
2030 // the bitcode. If the bitcode file is old, the symbol table will be
2031 // at the end instead and will not have been seen yet. In this case,
2032 // just finish the parse now.
2033 if (LazyStreamer && SeenValueSymbolTable) {
2034 NextUnreadBit = Stream.GetCurrentBitNo();
2035 return std::error_code();
2038 case bitc::USELIST_BLOCK_ID:
2039 if (std::error_code EC = ParseUseLists())
2045 case BitstreamEntry::Record:
2046 // The interesting case.
2052 switch (Stream.readRecord(Entry.ID, Record)) {
2053 default: break; // Default behavior, ignore unknown content.
2054 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2055 if (Record.size() < 1)
2056 return Error("Invalid record");
2057 // Only version #0 and #1 are supported so far.
2058 unsigned module_version = Record[0];
2059 switch (module_version) {
2061 return Error("Invalid value");
2063 UseRelativeIDs = false;
2066 UseRelativeIDs = true;
2071 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2073 if (ConvertToString(Record, 0, S))
2074 return Error("Invalid record");
2075 TheModule->setTargetTriple(S);
2078 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2080 if (ConvertToString(Record, 0, S))
2081 return Error("Invalid record");
2082 TheModule->setDataLayout(S);
2085 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2087 if (ConvertToString(Record, 0, S))
2088 return Error("Invalid record");
2089 TheModule->setModuleInlineAsm(S);
2092 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2093 // FIXME: Remove in 4.0.
2095 if (ConvertToString(Record, 0, S))
2096 return Error("Invalid record");
2100 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2102 if (ConvertToString(Record, 0, S))
2103 return Error("Invalid record");
2104 SectionTable.push_back(S);
2107 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2109 if (ConvertToString(Record, 0, S))
2110 return Error("Invalid record");
2111 GCTable.push_back(S);
2114 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2115 if (Record.size() < 2)
2116 return Error("Invalid record");
2117 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2118 unsigned ComdatNameSize = Record[1];
2119 std::string ComdatName;
2120 ComdatName.reserve(ComdatNameSize);
2121 for (unsigned i = 0; i != ComdatNameSize; ++i)
2122 ComdatName += (char)Record[2 + i];
2123 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2124 C->setSelectionKind(SK);
2125 ComdatList.push_back(C);
2128 // GLOBALVAR: [pointer type, isconst, initid,
2129 // linkage, alignment, section, visibility, threadlocal,
2130 // unnamed_addr, dllstorageclass]
2131 case bitc::MODULE_CODE_GLOBALVAR: {
2132 if (Record.size() < 6)
2133 return Error("Invalid record");
2134 Type *Ty = getTypeByID(Record[0]);
2136 return Error("Invalid record");
2137 if (!Ty->isPointerTy())
2138 return Error("Invalid type for value");
2139 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2140 Ty = cast<PointerType>(Ty)->getElementType();
2142 bool isConstant = Record[1];
2143 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Record[3]);
2144 unsigned Alignment = (1 << Record[4]) >> 1;
2145 std::string Section;
2147 if (Record[5]-1 >= SectionTable.size())
2148 return Error("Invalid ID");
2149 Section = SectionTable[Record[5]-1];
2151 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2152 // Local linkage must have default visibility.
2153 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2154 // FIXME: Change to an error if non-default in 4.0.
2155 Visibility = GetDecodedVisibility(Record[6]);
2157 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2158 if (Record.size() > 7)
2159 TLM = GetDecodedThreadLocalMode(Record[7]);
2161 bool UnnamedAddr = false;
2162 if (Record.size() > 8)
2163 UnnamedAddr = Record[8];
2165 bool ExternallyInitialized = false;
2166 if (Record.size() > 9)
2167 ExternallyInitialized = Record[9];
2169 GlobalVariable *NewGV =
2170 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2171 TLM, AddressSpace, ExternallyInitialized);
2172 NewGV->setAlignment(Alignment);
2173 if (!Section.empty())
2174 NewGV->setSection(Section);
2175 NewGV->setVisibility(Visibility);
2176 NewGV->setUnnamedAddr(UnnamedAddr);
2178 if (Record.size() > 10)
2179 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2181 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2183 ValueList.push_back(NewGV);
2185 // Remember which value to use for the global initializer.
2186 if (unsigned InitID = Record[2])
2187 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2189 if (Record.size() > 11)
2190 if (unsigned ComdatID = Record[11]) {
2191 assert(ComdatID <= ComdatList.size());
2192 NewGV->setComdat(ComdatList[ComdatID - 1]);
2196 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2197 // alignment, section, visibility, gc, unnamed_addr,
2198 // prologuedata, dllstorageclass, comdat, prefixdata]
2199 case bitc::MODULE_CODE_FUNCTION: {
2200 if (Record.size() < 8)
2201 return Error("Invalid record");
2202 Type *Ty = getTypeByID(Record[0]);
2204 return Error("Invalid record");
2205 if (!Ty->isPointerTy())
2206 return Error("Invalid type for value");
2208 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2210 return Error("Invalid type for value");
2212 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2215 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2216 bool isProto = Record[2];
2217 Func->setLinkage(getDecodedLinkage(Record[3]));
2218 Func->setAttributes(getAttributes(Record[4]));
2220 Func->setAlignment((1 << Record[5]) >> 1);
2222 if (Record[6]-1 >= SectionTable.size())
2223 return Error("Invalid ID");
2224 Func->setSection(SectionTable[Record[6]-1]);
2226 // Local linkage must have default visibility.
2227 if (!Func->hasLocalLinkage())
2228 // FIXME: Change to an error if non-default in 4.0.
2229 Func->setVisibility(GetDecodedVisibility(Record[7]));
2230 if (Record.size() > 8 && Record[8]) {
2231 if (Record[8]-1 > GCTable.size())
2232 return Error("Invalid ID");
2233 Func->setGC(GCTable[Record[8]-1].c_str());
2235 bool UnnamedAddr = false;
2236 if (Record.size() > 9)
2237 UnnamedAddr = Record[9];
2238 Func->setUnnamedAddr(UnnamedAddr);
2239 if (Record.size() > 10 && Record[10] != 0)
2240 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2242 if (Record.size() > 11)
2243 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2245 UpgradeDLLImportExportLinkage(Func, Record[3]);
2247 if (Record.size() > 12)
2248 if (unsigned ComdatID = Record[12]) {
2249 assert(ComdatID <= ComdatList.size());
2250 Func->setComdat(ComdatList[ComdatID - 1]);
2253 if (Record.size() > 13 && Record[13] != 0)
2254 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2256 ValueList.push_back(Func);
2258 // If this is a function with a body, remember the prototype we are
2259 // creating now, so that we can match up the body with them later.
2261 Func->setIsMaterializable(true);
2262 FunctionsWithBodies.push_back(Func);
2264 DeferredFunctionInfo[Func] = 0;
2268 // ALIAS: [alias type, aliasee val#, linkage]
2269 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2270 case bitc::MODULE_CODE_ALIAS: {
2271 if (Record.size() < 3)
2272 return Error("Invalid record");
2273 Type *Ty = getTypeByID(Record[0]);
2275 return Error("Invalid record");
2276 auto *PTy = dyn_cast<PointerType>(Ty);
2278 return Error("Invalid type for value");
2281 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2282 getDecodedLinkage(Record[2]), "", TheModule);
2283 // Old bitcode files didn't have visibility field.
2284 // Local linkage must have default visibility.
2285 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2286 // FIXME: Change to an error if non-default in 4.0.
2287 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2288 if (Record.size() > 4)
2289 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2291 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2292 if (Record.size() > 5)
2293 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2294 if (Record.size() > 6)
2295 NewGA->setUnnamedAddr(Record[6]);
2296 ValueList.push_back(NewGA);
2297 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2300 /// MODULE_CODE_PURGEVALS: [numvals]
2301 case bitc::MODULE_CODE_PURGEVALS:
2302 // Trim down the value list to the specified size.
2303 if (Record.size() < 1 || Record[0] > ValueList.size())
2304 return Error("Invalid record");
2305 ValueList.shrinkTo(Record[0]);
2312 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2313 TheModule = nullptr;
2315 if (std::error_code EC = InitStream())
2318 // Sniff for the signature.
2319 if (Stream.Read(8) != 'B' ||
2320 Stream.Read(8) != 'C' ||
2321 Stream.Read(4) != 0x0 ||
2322 Stream.Read(4) != 0xC ||
2323 Stream.Read(4) != 0xE ||
2324 Stream.Read(4) != 0xD)
2325 return Error("Invalid bitcode signature");
2327 // We expect a number of well-defined blocks, though we don't necessarily
2328 // need to understand them all.
2330 if (Stream.AtEndOfStream())
2331 return std::error_code();
2333 BitstreamEntry Entry =
2334 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2336 switch (Entry.Kind) {
2337 case BitstreamEntry::Error:
2338 return Error("Malformed block");
2339 case BitstreamEntry::EndBlock:
2340 return std::error_code();
2342 case BitstreamEntry::SubBlock:
2344 case bitc::BLOCKINFO_BLOCK_ID:
2345 if (Stream.ReadBlockInfoBlock())
2346 return Error("Malformed block");
2348 case bitc::MODULE_BLOCK_ID:
2349 // Reject multiple MODULE_BLOCK's in a single bitstream.
2351 return Error("Invalid multiple blocks");
2353 if (std::error_code EC = ParseModule(false))
2356 return std::error_code();
2359 if (Stream.SkipBlock())
2360 return Error("Invalid record");
2364 case BitstreamEntry::Record:
2365 // There should be no records in the top-level of blocks.
2367 // The ranlib in Xcode 4 will align archive members by appending newlines
2368 // to the end of them. If this file size is a multiple of 4 but not 8, we
2369 // have to read and ignore these final 4 bytes :-(
2370 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2371 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2372 Stream.AtEndOfStream())
2373 return std::error_code();
2375 return Error("Invalid record");
2380 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2381 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2382 return Error("Invalid record");
2384 SmallVector<uint64_t, 64> Record;
2387 // Read all the records for this module.
2389 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2391 switch (Entry.Kind) {
2392 case BitstreamEntry::SubBlock: // Handled for us already.
2393 case BitstreamEntry::Error:
2394 return Error("Malformed block");
2395 case BitstreamEntry::EndBlock:
2397 case BitstreamEntry::Record:
2398 // The interesting case.
2403 switch (Stream.readRecord(Entry.ID, Record)) {
2404 default: break; // Default behavior, ignore unknown content.
2405 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2407 if (ConvertToString(Record, 0, S))
2408 return Error("Invalid record");
2415 llvm_unreachable("Exit infinite loop");
2418 ErrorOr<std::string> BitcodeReader::parseTriple() {
2419 if (std::error_code EC = InitStream())
2422 // Sniff for the signature.
2423 if (Stream.Read(8) != 'B' ||
2424 Stream.Read(8) != 'C' ||
2425 Stream.Read(4) != 0x0 ||
2426 Stream.Read(4) != 0xC ||
2427 Stream.Read(4) != 0xE ||
2428 Stream.Read(4) != 0xD)
2429 return Error("Invalid bitcode signature");
2431 // We expect a number of well-defined blocks, though we don't necessarily
2432 // need to understand them all.
2434 BitstreamEntry Entry = Stream.advance();
2436 switch (Entry.Kind) {
2437 case BitstreamEntry::Error:
2438 return Error("Malformed block");
2439 case BitstreamEntry::EndBlock:
2440 return std::error_code();
2442 case BitstreamEntry::SubBlock:
2443 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2444 return parseModuleTriple();
2446 // Ignore other sub-blocks.
2447 if (Stream.SkipBlock())
2448 return Error("Malformed block");
2451 case BitstreamEntry::Record:
2452 Stream.skipRecord(Entry.ID);
2458 /// ParseMetadataAttachment - Parse metadata attachments.
2459 std::error_code BitcodeReader::ParseMetadataAttachment() {
2460 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2461 return Error("Invalid record");
2463 SmallVector<uint64_t, 64> Record;
2465 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2467 switch (Entry.Kind) {
2468 case BitstreamEntry::SubBlock: // Handled for us already.
2469 case BitstreamEntry::Error:
2470 return Error("Malformed block");
2471 case BitstreamEntry::EndBlock:
2472 return std::error_code();
2473 case BitstreamEntry::Record:
2474 // The interesting case.
2478 // Read a metadata attachment record.
2480 switch (Stream.readRecord(Entry.ID, Record)) {
2481 default: // Default behavior: ignore.
2483 case bitc::METADATA_ATTACHMENT: {
2484 unsigned RecordLength = Record.size();
2485 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2486 return Error("Invalid record");
2487 Instruction *Inst = InstructionList[Record[0]];
2488 for (unsigned i = 1; i != RecordLength; i = i+2) {
2489 unsigned Kind = Record[i];
2490 DenseMap<unsigned, unsigned>::iterator I =
2491 MDKindMap.find(Kind);
2492 if (I == MDKindMap.end())
2493 return Error("Invalid ID");
2494 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2495 if (isa<LocalAsMetadata>(Node))
2496 // Drop the attachment. This used to be legal, but there's no
2499 Inst->setMetadata(I->second, cast<MDNode>(Node));
2500 if (I->second == LLVMContext::MD_tbaa)
2501 InstsWithTBAATag.push_back(Inst);
2509 /// ParseFunctionBody - Lazily parse the specified function body block.
2510 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2511 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2512 return Error("Invalid record");
2514 InstructionList.clear();
2515 unsigned ModuleValueListSize = ValueList.size();
2516 unsigned ModuleMDValueListSize = MDValueList.size();
2518 // Add all the function arguments to the value table.
2519 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2520 ValueList.push_back(I);
2522 unsigned NextValueNo = ValueList.size();
2523 BasicBlock *CurBB = nullptr;
2524 unsigned CurBBNo = 0;
2527 auto getLastInstruction = [&]() -> Instruction * {
2528 if (CurBB && !CurBB->empty())
2529 return &CurBB->back();
2530 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2531 !FunctionBBs[CurBBNo - 1]->empty())
2532 return &FunctionBBs[CurBBNo - 1]->back();
2536 // Read all the records.
2537 SmallVector<uint64_t, 64> Record;
2539 BitstreamEntry Entry = Stream.advance();
2541 switch (Entry.Kind) {
2542 case BitstreamEntry::Error:
2543 return Error("Malformed block");
2544 case BitstreamEntry::EndBlock:
2545 goto OutOfRecordLoop;
2547 case BitstreamEntry::SubBlock:
2549 default: // Skip unknown content.
2550 if (Stream.SkipBlock())
2551 return Error("Invalid record");
2553 case bitc::CONSTANTS_BLOCK_ID:
2554 if (std::error_code EC = ParseConstants())
2556 NextValueNo = ValueList.size();
2558 case bitc::VALUE_SYMTAB_BLOCK_ID:
2559 if (std::error_code EC = ParseValueSymbolTable())
2562 case bitc::METADATA_ATTACHMENT_ID:
2563 if (std::error_code EC = ParseMetadataAttachment())
2566 case bitc::METADATA_BLOCK_ID:
2567 if (std::error_code EC = ParseMetadata())
2570 case bitc::USELIST_BLOCK_ID:
2571 if (std::error_code EC = ParseUseLists())
2577 case BitstreamEntry::Record:
2578 // The interesting case.
2584 Instruction *I = nullptr;
2585 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2587 default: // Default behavior: reject
2588 return Error("Invalid value");
2589 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2590 if (Record.size() < 1 || Record[0] == 0)
2591 return Error("Invalid record");
2592 // Create all the basic blocks for the function.
2593 FunctionBBs.resize(Record[0]);
2595 // See if anything took the address of blocks in this function.
2596 auto BBFRI = BasicBlockFwdRefs.find(F);
2597 if (BBFRI == BasicBlockFwdRefs.end()) {
2598 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2599 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2601 auto &BBRefs = BBFRI->second;
2602 // Check for invalid basic block references.
2603 if (BBRefs.size() > FunctionBBs.size())
2604 return Error("Invalid ID");
2605 assert(!BBRefs.empty() && "Unexpected empty array");
2606 assert(!BBRefs.front() && "Invalid reference to entry block");
2607 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2609 if (I < RE && BBRefs[I]) {
2610 BBRefs[I]->insertInto(F);
2611 FunctionBBs[I] = BBRefs[I];
2613 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2616 // Erase from the table.
2617 BasicBlockFwdRefs.erase(BBFRI);
2620 CurBB = FunctionBBs[0];
2624 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2625 // This record indicates that the last instruction is at the same
2626 // location as the previous instruction with a location.
2627 I = getLastInstruction();
2630 return Error("Invalid record");
2631 I->setDebugLoc(LastLoc);
2635 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2636 I = getLastInstruction();
2637 if (!I || Record.size() < 4)
2638 return Error("Invalid record");
2640 unsigned Line = Record[0], Col = Record[1];
2641 unsigned ScopeID = Record[2], IAID = Record[3];
2643 MDNode *Scope = nullptr, *IA = nullptr;
2644 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2645 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2646 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2647 I->setDebugLoc(LastLoc);
2652 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2655 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2656 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2657 OpNum+1 > Record.size())
2658 return Error("Invalid record");
2660 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2662 return Error("Invalid record");
2663 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2664 InstructionList.push_back(I);
2665 if (OpNum < Record.size()) {
2666 if (Opc == Instruction::Add ||
2667 Opc == Instruction::Sub ||
2668 Opc == Instruction::Mul ||
2669 Opc == Instruction::Shl) {
2670 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2671 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2672 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2673 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2674 } else if (Opc == Instruction::SDiv ||
2675 Opc == Instruction::UDiv ||
2676 Opc == Instruction::LShr ||
2677 Opc == Instruction::AShr) {
2678 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2679 cast<BinaryOperator>(I)->setIsExact(true);
2680 } else if (isa<FPMathOperator>(I)) {
2682 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2683 FMF.setUnsafeAlgebra();
2684 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2686 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2688 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2689 FMF.setNoSignedZeros();
2690 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2691 FMF.setAllowReciprocal();
2693 I->setFastMathFlags(FMF);
2699 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2702 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2703 OpNum+2 != Record.size())
2704 return Error("Invalid record");
2706 Type *ResTy = getTypeByID(Record[OpNum]);
2707 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2708 if (Opc == -1 || !ResTy)
2709 return Error("Invalid record");
2710 Instruction *Temp = nullptr;
2711 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2713 InstructionList.push_back(Temp);
2714 CurBB->getInstList().push_back(Temp);
2717 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2719 InstructionList.push_back(I);
2722 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2723 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2726 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2727 return Error("Invalid record");
2729 SmallVector<Value*, 16> GEPIdx;
2730 while (OpNum != Record.size()) {
2732 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2733 return Error("Invalid record");
2734 GEPIdx.push_back(Op);
2737 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2738 InstructionList.push_back(I);
2739 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2740 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2744 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2745 // EXTRACTVAL: [opty, opval, n x indices]
2748 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2749 return Error("Invalid record");
2751 SmallVector<unsigned, 4> EXTRACTVALIdx;
2752 for (unsigned RecSize = Record.size();
2753 OpNum != RecSize; ++OpNum) {
2754 uint64_t Index = Record[OpNum];
2755 if ((unsigned)Index != Index)
2756 return Error("Invalid value");
2757 EXTRACTVALIdx.push_back((unsigned)Index);
2760 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2761 InstructionList.push_back(I);
2765 case bitc::FUNC_CODE_INST_INSERTVAL: {
2766 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2769 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2770 return Error("Invalid record");
2772 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2773 return Error("Invalid record");
2775 SmallVector<unsigned, 4> INSERTVALIdx;
2776 for (unsigned RecSize = Record.size();
2777 OpNum != RecSize; ++OpNum) {
2778 uint64_t Index = Record[OpNum];
2779 if ((unsigned)Index != Index)
2780 return Error("Invalid value");
2781 INSERTVALIdx.push_back((unsigned)Index);
2784 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2785 InstructionList.push_back(I);
2789 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2790 // obsolete form of select
2791 // handles select i1 ... in old bitcode
2793 Value *TrueVal, *FalseVal, *Cond;
2794 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2795 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2796 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2797 return Error("Invalid record");
2799 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2800 InstructionList.push_back(I);
2804 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2805 // new form of select
2806 // handles select i1 or select [N x i1]
2808 Value *TrueVal, *FalseVal, *Cond;
2809 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2810 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2811 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2812 return Error("Invalid record");
2814 // select condition can be either i1 or [N x i1]
2815 if (VectorType* vector_type =
2816 dyn_cast<VectorType>(Cond->getType())) {
2818 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2819 return Error("Invalid type for value");
2822 if (Cond->getType() != Type::getInt1Ty(Context))
2823 return Error("Invalid type for value");
2826 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2827 InstructionList.push_back(I);
2831 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2834 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2835 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2836 return Error("Invalid record");
2837 I = ExtractElementInst::Create(Vec, Idx);
2838 InstructionList.push_back(I);
2842 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2844 Value *Vec, *Elt, *Idx;
2845 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2846 popValue(Record, OpNum, NextValueNo,
2847 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2848 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2849 return Error("Invalid record");
2850 I = InsertElementInst::Create(Vec, Elt, Idx);
2851 InstructionList.push_back(I);
2855 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2857 Value *Vec1, *Vec2, *Mask;
2858 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2859 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2860 return Error("Invalid record");
2862 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2863 return Error("Invalid record");
2864 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2865 InstructionList.push_back(I);
2869 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2870 // Old form of ICmp/FCmp returning bool
2871 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2872 // both legal on vectors but had different behaviour.
2873 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2874 // FCmp/ICmp returning bool or vector of bool
2878 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2879 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2880 OpNum+1 != Record.size())
2881 return Error("Invalid record");
2883 if (LHS->getType()->isFPOrFPVectorTy())
2884 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2886 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2887 InstructionList.push_back(I);
2891 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2893 unsigned Size = Record.size();
2895 I = ReturnInst::Create(Context);
2896 InstructionList.push_back(I);
2901 Value *Op = nullptr;
2902 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2903 return Error("Invalid record");
2904 if (OpNum != Record.size())
2905 return Error("Invalid record");
2907 I = ReturnInst::Create(Context, Op);
2908 InstructionList.push_back(I);
2911 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2912 if (Record.size() != 1 && Record.size() != 3)
2913 return Error("Invalid record");
2914 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2916 return Error("Invalid record");
2918 if (Record.size() == 1) {
2919 I = BranchInst::Create(TrueDest);
2920 InstructionList.push_back(I);
2923 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2924 Value *Cond = getValue(Record, 2, NextValueNo,
2925 Type::getInt1Ty(Context));
2926 if (!FalseDest || !Cond)
2927 return Error("Invalid record");
2928 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2929 InstructionList.push_back(I);
2933 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2935 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2936 // "New" SwitchInst format with case ranges. The changes to write this
2937 // format were reverted but we still recognize bitcode that uses it.
2938 // Hopefully someday we will have support for case ranges and can use
2939 // this format again.
2941 Type *OpTy = getTypeByID(Record[1]);
2942 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2944 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2945 BasicBlock *Default = getBasicBlock(Record[3]);
2946 if (!OpTy || !Cond || !Default)
2947 return Error("Invalid record");
2949 unsigned NumCases = Record[4];
2951 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2952 InstructionList.push_back(SI);
2954 unsigned CurIdx = 5;
2955 for (unsigned i = 0; i != NumCases; ++i) {
2956 SmallVector<ConstantInt*, 1> CaseVals;
2957 unsigned NumItems = Record[CurIdx++];
2958 for (unsigned ci = 0; ci != NumItems; ++ci) {
2959 bool isSingleNumber = Record[CurIdx++];
2962 unsigned ActiveWords = 1;
2963 if (ValueBitWidth > 64)
2964 ActiveWords = Record[CurIdx++];
2965 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2967 CurIdx += ActiveWords;
2969 if (!isSingleNumber) {
2971 if (ValueBitWidth > 64)
2972 ActiveWords = Record[CurIdx++];
2974 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2976 CurIdx += ActiveWords;
2978 // FIXME: It is not clear whether values in the range should be
2979 // compared as signed or unsigned values. The partially
2980 // implemented changes that used this format in the past used
2981 // unsigned comparisons.
2982 for ( ; Low.ule(High); ++Low)
2983 CaseVals.push_back(ConstantInt::get(Context, Low));
2985 CaseVals.push_back(ConstantInt::get(Context, Low));
2987 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2988 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2989 cve = CaseVals.end(); cvi != cve; ++cvi)
2990 SI->addCase(*cvi, DestBB);
2996 // Old SwitchInst format without case ranges.
2998 if (Record.size() < 3 || (Record.size() & 1) == 0)
2999 return Error("Invalid record");
3000 Type *OpTy = getTypeByID(Record[0]);
3001 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3002 BasicBlock *Default = getBasicBlock(Record[2]);
3003 if (!OpTy || !Cond || !Default)
3004 return Error("Invalid record");
3005 unsigned NumCases = (Record.size()-3)/2;
3006 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3007 InstructionList.push_back(SI);
3008 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3009 ConstantInt *CaseVal =
3010 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3011 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3012 if (!CaseVal || !DestBB) {
3014 return Error("Invalid record");
3016 SI->addCase(CaseVal, DestBB);
3021 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3022 if (Record.size() < 2)
3023 return Error("Invalid record");
3024 Type *OpTy = getTypeByID(Record[0]);
3025 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3026 if (!OpTy || !Address)
3027 return Error("Invalid record");
3028 unsigned NumDests = Record.size()-2;
3029 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3030 InstructionList.push_back(IBI);
3031 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3032 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3033 IBI->addDestination(DestBB);
3036 return Error("Invalid record");
3043 case bitc::FUNC_CODE_INST_INVOKE: {
3044 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3045 if (Record.size() < 4)
3046 return Error("Invalid record");
3047 AttributeSet PAL = getAttributes(Record[0]);
3048 unsigned CCInfo = Record[1];
3049 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3050 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3054 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3055 return Error("Invalid record");
3057 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3058 FunctionType *FTy = !CalleeTy ? nullptr :
3059 dyn_cast<FunctionType>(CalleeTy->getElementType());
3061 // Check that the right number of fixed parameters are here.
3062 if (!FTy || !NormalBB || !UnwindBB ||
3063 Record.size() < OpNum+FTy->getNumParams())
3064 return Error("Invalid record");
3066 SmallVector<Value*, 16> Ops;
3067 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3068 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3069 FTy->getParamType(i)));
3071 return Error("Invalid record");
3074 if (!FTy->isVarArg()) {
3075 if (Record.size() != OpNum)
3076 return Error("Invalid record");
3078 // Read type/value pairs for varargs params.
3079 while (OpNum != Record.size()) {
3081 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3082 return Error("Invalid record");
3087 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3088 InstructionList.push_back(I);
3089 cast<InvokeInst>(I)->setCallingConv(
3090 static_cast<CallingConv::ID>(CCInfo));
3091 cast<InvokeInst>(I)->setAttributes(PAL);
3094 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3096 Value *Val = nullptr;
3097 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3098 return Error("Invalid record");
3099 I = ResumeInst::Create(Val);
3100 InstructionList.push_back(I);
3103 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3104 I = new UnreachableInst(Context);
3105 InstructionList.push_back(I);
3107 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3108 if (Record.size() < 1 || ((Record.size()-1)&1))
3109 return Error("Invalid record");
3110 Type *Ty = getTypeByID(Record[0]);
3112 return Error("Invalid record");
3114 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3115 InstructionList.push_back(PN);
3117 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3119 // With the new function encoding, it is possible that operands have
3120 // negative IDs (for forward references). Use a signed VBR
3121 // representation to keep the encoding small.
3123 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3125 V = getValue(Record, 1+i, NextValueNo, Ty);
3126 BasicBlock *BB = getBasicBlock(Record[2+i]);
3128 return Error("Invalid record");
3129 PN->addIncoming(V, BB);
3135 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3136 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3138 if (Record.size() < 4)
3139 return Error("Invalid record");
3140 Type *Ty = getTypeByID(Record[Idx++]);
3142 return Error("Invalid record");
3143 Value *PersFn = nullptr;
3144 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3145 return Error("Invalid record");
3147 bool IsCleanup = !!Record[Idx++];
3148 unsigned NumClauses = Record[Idx++];
3149 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3150 LP->setCleanup(IsCleanup);
3151 for (unsigned J = 0; J != NumClauses; ++J) {
3152 LandingPadInst::ClauseType CT =
3153 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3156 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3158 return Error("Invalid record");
3161 assert((CT != LandingPadInst::Catch ||
3162 !isa<ArrayType>(Val->getType())) &&
3163 "Catch clause has a invalid type!");
3164 assert((CT != LandingPadInst::Filter ||
3165 isa<ArrayType>(Val->getType())) &&
3166 "Filter clause has invalid type!");
3167 LP->addClause(cast<Constant>(Val));
3171 InstructionList.push_back(I);
3175 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3176 if (Record.size() != 4)
3177 return Error("Invalid record");
3179 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3180 Type *OpTy = getTypeByID(Record[1]);
3181 Value *Size = getFnValueByID(Record[2], OpTy);
3182 unsigned AlignRecord = Record[3];
3183 bool InAlloca = AlignRecord & (1 << 5);
3184 unsigned Align = AlignRecord & ((1 << 5) - 1);
3186 return Error("Invalid record");
3187 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3188 AI->setUsedWithInAlloca(InAlloca);
3190 InstructionList.push_back(I);
3193 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3196 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3197 OpNum+2 != Record.size())
3198 return Error("Invalid record");
3200 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3201 InstructionList.push_back(I);
3204 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3205 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3208 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3209 OpNum+4 != Record.size())
3210 return Error("Invalid record");
3212 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3213 if (Ordering == NotAtomic || Ordering == Release ||
3214 Ordering == AcquireRelease)
3215 return Error("Invalid record");
3216 if (Ordering != NotAtomic && Record[OpNum] == 0)
3217 return Error("Invalid record");
3218 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3220 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3221 Ordering, SynchScope);
3222 InstructionList.push_back(I);
3225 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3228 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3229 popValue(Record, OpNum, NextValueNo,
3230 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3231 OpNum+2 != Record.size())
3232 return Error("Invalid record");
3234 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3235 InstructionList.push_back(I);
3238 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3239 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3242 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3243 popValue(Record, OpNum, NextValueNo,
3244 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3245 OpNum+4 != Record.size())
3246 return Error("Invalid record");
3248 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3249 if (Ordering == NotAtomic || Ordering == Acquire ||
3250 Ordering == AcquireRelease)
3251 return Error("Invalid record");
3252 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3253 if (Ordering != NotAtomic && Record[OpNum] == 0)
3254 return Error("Invalid record");
3256 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3257 Ordering, SynchScope);
3258 InstructionList.push_back(I);
3261 case bitc::FUNC_CODE_INST_CMPXCHG: {
3262 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3263 // failureordering?, isweak?]
3265 Value *Ptr, *Cmp, *New;
3266 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3267 popValue(Record, OpNum, NextValueNo,
3268 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3269 popValue(Record, OpNum, NextValueNo,
3270 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3271 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3272 return Error("Invalid record");
3273 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3274 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3275 return Error("Invalid record");
3276 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3278 AtomicOrdering FailureOrdering;
3279 if (Record.size() < 7)
3281 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3283 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3285 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3287 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3289 if (Record.size() < 8) {
3290 // Before weak cmpxchgs existed, the instruction simply returned the
3291 // value loaded from memory, so bitcode files from that era will be
3292 // expecting the first component of a modern cmpxchg.
3293 CurBB->getInstList().push_back(I);
3294 I = ExtractValueInst::Create(I, 0);
3296 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3299 InstructionList.push_back(I);
3302 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3303 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3306 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3307 popValue(Record, OpNum, NextValueNo,
3308 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3309 OpNum+4 != Record.size())
3310 return Error("Invalid record");
3311 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3312 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3313 Operation > AtomicRMWInst::LAST_BINOP)
3314 return Error("Invalid record");
3315 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3316 if (Ordering == NotAtomic || Ordering == Unordered)
3317 return Error("Invalid record");
3318 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3319 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3320 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3321 InstructionList.push_back(I);
3324 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3325 if (2 != Record.size())
3326 return Error("Invalid record");
3327 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3328 if (Ordering == NotAtomic || Ordering == Unordered ||
3329 Ordering == Monotonic)
3330 return Error("Invalid record");
3331 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3332 I = new FenceInst(Context, Ordering, SynchScope);
3333 InstructionList.push_back(I);
3336 case bitc::FUNC_CODE_INST_CALL: {
3337 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3338 if (Record.size() < 3)
3339 return Error("Invalid record");
3341 AttributeSet PAL = getAttributes(Record[0]);
3342 unsigned CCInfo = Record[1];
3346 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3347 return Error("Invalid record");
3349 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3350 FunctionType *FTy = nullptr;
3351 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3352 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3353 return Error("Invalid record");
3355 SmallVector<Value*, 16> Args;
3356 // Read the fixed params.
3357 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3358 if (FTy->getParamType(i)->isLabelTy())
3359 Args.push_back(getBasicBlock(Record[OpNum]));
3361 Args.push_back(getValue(Record, OpNum, NextValueNo,
3362 FTy->getParamType(i)));
3364 return Error("Invalid record");
3367 // Read type/value pairs for varargs params.
3368 if (!FTy->isVarArg()) {
3369 if (OpNum != Record.size())
3370 return Error("Invalid record");
3372 while (OpNum != Record.size()) {
3374 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3375 return Error("Invalid record");
3380 I = CallInst::Create(Callee, Args);
3381 InstructionList.push_back(I);
3382 cast<CallInst>(I)->setCallingConv(
3383 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3384 CallInst::TailCallKind TCK = CallInst::TCK_None;
3386 TCK = CallInst::TCK_Tail;
3387 if (CCInfo & (1 << 14))
3388 TCK = CallInst::TCK_MustTail;
3389 cast<CallInst>(I)->setTailCallKind(TCK);
3390 cast<CallInst>(I)->setAttributes(PAL);
3393 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3394 if (Record.size() < 3)
3395 return Error("Invalid record");
3396 Type *OpTy = getTypeByID(Record[0]);
3397 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3398 Type *ResTy = getTypeByID(Record[2]);
3399 if (!OpTy || !Op || !ResTy)
3400 return Error("Invalid record");
3401 I = new VAArgInst(Op, ResTy);
3402 InstructionList.push_back(I);
3407 // Add instruction to end of current BB. If there is no current BB, reject
3411 return Error("Invalid instruction with no BB");
3413 CurBB->getInstList().push_back(I);
3415 // If this was a terminator instruction, move to the next block.
3416 if (isa<TerminatorInst>(I)) {
3418 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3421 // Non-void values get registered in the value table for future use.
3422 if (I && !I->getType()->isVoidTy())
3423 ValueList.AssignValue(I, NextValueNo++);
3428 // Check the function list for unresolved values.
3429 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3430 if (!A->getParent()) {
3431 // We found at least one unresolved value. Nuke them all to avoid leaks.
3432 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3433 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3434 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3438 return Error("Never resolved value found in function");
3442 // FIXME: Check for unresolved forward-declared metadata references
3443 // and clean up leaks.
3445 // Trim the value list down to the size it was before we parsed this function.
3446 ValueList.shrinkTo(ModuleValueListSize);
3447 MDValueList.shrinkTo(ModuleMDValueListSize);
3448 std::vector<BasicBlock*>().swap(FunctionBBs);
3449 return std::error_code();
3452 /// Find the function body in the bitcode stream
3453 std::error_code BitcodeReader::FindFunctionInStream(
3455 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3456 while (DeferredFunctionInfoIterator->second == 0) {
3457 if (Stream.AtEndOfStream())
3458 return Error("Could not find function in stream");
3459 // ParseModule will parse the next body in the stream and set its
3460 // position in the DeferredFunctionInfo map.
3461 if (std::error_code EC = ParseModule(true))
3464 return std::error_code();
3467 //===----------------------------------------------------------------------===//
3468 // GVMaterializer implementation
3469 //===----------------------------------------------------------------------===//
3471 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3473 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3474 Function *F = dyn_cast<Function>(GV);
3475 // If it's not a function or is already material, ignore the request.
3476 if (!F || !F->isMaterializable())
3477 return std::error_code();
3479 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3480 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3481 // If its position is recorded as 0, its body is somewhere in the stream
3482 // but we haven't seen it yet.
3483 if (DFII->second == 0 && LazyStreamer)
3484 if (std::error_code EC = FindFunctionInStream(F, DFII))
3487 // Move the bit stream to the saved position of the deferred function body.
3488 Stream.JumpToBit(DFII->second);
3490 if (std::error_code EC = ParseFunctionBody(F))
3492 F->setIsMaterializable(false);
3494 // Upgrade any old intrinsic calls in the function.
3495 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3496 E = UpgradedIntrinsics.end(); I != E; ++I) {
3497 if (I->first != I->second) {
3498 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3500 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3501 UpgradeIntrinsicCall(CI, I->second);
3506 // Bring in any functions that this function forward-referenced via
3508 return materializeForwardReferencedFunctions();
3511 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3512 const Function *F = dyn_cast<Function>(GV);
3513 if (!F || F->isDeclaration())
3516 // Dematerializing F would leave dangling references that wouldn't be
3517 // reconnected on re-materialization.
3518 if (BlockAddressesTaken.count(F))
3521 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3524 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3525 Function *F = dyn_cast<Function>(GV);
3526 // If this function isn't dematerializable, this is a noop.
3527 if (!F || !isDematerializable(F))
3530 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3532 // Just forget the function body, we can remat it later.
3533 F->dropAllReferences();
3534 F->setIsMaterializable(true);
3537 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3538 assert(M == TheModule &&
3539 "Can only Materialize the Module this BitcodeReader is attached to.");
3541 // Promise to materialize all forward references.
3542 WillMaterializeAllForwardRefs = true;
3544 // Iterate over the module, deserializing any functions that are still on
3546 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3548 if (std::error_code EC = materialize(F))
3551 // At this point, if there are any function bodies, the current bit is
3552 // pointing to the END_BLOCK record after them. Now make sure the rest
3553 // of the bits in the module have been read.
3557 // Check that all block address forward references got resolved (as we
3559 if (!BasicBlockFwdRefs.empty())
3560 return Error("Never resolved function from blockaddress");
3562 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3563 // delete the old functions to clean up. We can't do this unless the entire
3564 // module is materialized because there could always be another function body
3565 // with calls to the old function.
3566 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3567 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3568 if (I->first != I->second) {
3569 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3571 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3572 UpgradeIntrinsicCall(CI, I->second);
3574 if (!I->first->use_empty())
3575 I->first->replaceAllUsesWith(I->second);
3576 I->first->eraseFromParent();
3579 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3581 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3582 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3584 UpgradeDebugInfo(*M);
3585 return std::error_code();
3588 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3589 return IdentifiedStructTypes;
3592 std::error_code BitcodeReader::InitStream() {
3594 return InitLazyStream();
3595 return InitStreamFromBuffer();
3598 std::error_code BitcodeReader::InitStreamFromBuffer() {
3599 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3600 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3602 if (Buffer->getBufferSize() & 3)
3603 return Error("Invalid bitcode signature");
3605 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3606 // The magic number is 0x0B17C0DE stored in little endian.
3607 if (isBitcodeWrapper(BufPtr, BufEnd))
3608 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3609 return Error("Invalid bitcode wrapper header");
3611 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3612 Stream.init(&*StreamFile);
3614 return std::error_code();
3617 std::error_code BitcodeReader::InitLazyStream() {
3618 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3620 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3621 StreamingMemoryObject &Bytes = *OwnedBytes;
3622 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3623 Stream.init(&*StreamFile);
3625 unsigned char buf[16];
3626 if (Bytes.readBytes(buf, 16, 0) != 16)
3627 return Error("Invalid bitcode signature");
3629 if (!isBitcode(buf, buf + 16))
3630 return Error("Invalid bitcode signature");
3632 if (isBitcodeWrapper(buf, buf + 4)) {
3633 const unsigned char *bitcodeStart = buf;
3634 const unsigned char *bitcodeEnd = buf + 16;
3635 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3636 Bytes.dropLeadingBytes(bitcodeStart - buf);
3637 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3639 return std::error_code();
3643 class BitcodeErrorCategoryType : public std::error_category {
3644 const char *name() const LLVM_NOEXCEPT override {
3645 return "llvm.bitcode";
3647 std::string message(int IE) const override {
3648 BitcodeError E = static_cast<BitcodeError>(IE);
3650 case BitcodeError::InvalidBitcodeSignature:
3651 return "Invalid bitcode signature";
3652 case BitcodeError::CorruptedBitcode:
3653 return "Corrupted bitcode";
3655 llvm_unreachable("Unknown error type!");
3660 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3662 const std::error_category &llvm::BitcodeErrorCategory() {
3663 return *ErrorCategory;
3666 //===----------------------------------------------------------------------===//
3667 // External interface
3668 //===----------------------------------------------------------------------===//
3670 /// \brief Get a lazy one-at-time loading module from bitcode.
3672 /// This isn't always used in a lazy context. In particular, it's also used by
3673 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3674 /// in forward-referenced functions from block address references.
3676 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3677 /// materialize everything -- in particular, if this isn't truly lazy.
3678 static ErrorOr<Module *>
3679 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3680 LLVMContext &Context, bool WillMaterializeAll,
3681 DiagnosticHandlerFunction DiagnosticHandler) {
3682 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3684 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3685 M->setMaterializer(R);
3687 auto cleanupOnError = [&](std::error_code EC) {
3688 R->releaseBuffer(); // Never take ownership on error.
3689 delete M; // Also deletes R.
3693 if (std::error_code EC = R->ParseBitcodeInto(M))
3694 return cleanupOnError(EC);
3696 if (!WillMaterializeAll)
3697 // Resolve forward references from blockaddresses.
3698 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3699 return cleanupOnError(EC);
3701 Buffer.release(); // The BitcodeReader owns it now.
3706 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3707 LLVMContext &Context,
3708 DiagnosticHandlerFunction DiagnosticHandler) {
3709 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3713 ErrorOr<std::unique_ptr<Module>>
3714 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3715 LLVMContext &Context,
3716 DiagnosticHandlerFunction DiagnosticHandler) {
3717 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3718 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
3719 M->setMaterializer(R);
3720 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3722 return std::move(M);
3726 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3727 DiagnosticHandlerFunction DiagnosticHandler) {
3728 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3729 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3730 std::move(Buf), Context, true, DiagnosticHandler);
3733 Module *M = ModuleOrErr.get();
3734 // Read in the entire module, and destroy the BitcodeReader.
3735 if (std::error_code EC = M->materializeAllPermanently()) {
3740 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3741 // written. We must defer until the Module has been fully materialized.
3747 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3748 DiagnosticHandlerFunction DiagnosticHandler) {
3749 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3750 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3752 ErrorOr<std::string> Triple = R->parseTriple();
3753 if (Triple.getError())
3755 return Triple.get();