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/ADT/Triple.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DebugInfoMetadata.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/OperandTraits.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Support/DataStream.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
36 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
39 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
40 DiagnosticSeverity Severity,
42 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
44 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
46 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
47 std::error_code EC, const Twine &Message) {
48 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
49 DiagnosticHandler(DI);
53 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
55 return Error(DiagnosticHandler, EC, EC.message());
58 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
59 return ::Error(DiagnosticHandler, make_error_code(E), Message);
62 std::error_code BitcodeReader::Error(const Twine &Message) {
63 return ::Error(DiagnosticHandler,
64 make_error_code(BitcodeError::CorruptedBitcode), Message);
67 std::error_code BitcodeReader::Error(BitcodeError E) {
68 return ::Error(DiagnosticHandler, make_error_code(E));
71 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
75 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
78 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
79 DiagnosticHandlerFunction DiagnosticHandler)
80 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
81 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
82 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
83 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
84 WillMaterializeAllForwardRefs(false) {}
86 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
87 DiagnosticHandlerFunction DiagnosticHandler)
88 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
89 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
90 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
91 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
92 WillMaterializeAllForwardRefs(false) {}
94 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
95 if (WillMaterializeAllForwardRefs)
96 return std::error_code();
99 WillMaterializeAllForwardRefs = true;
101 while (!BasicBlockFwdRefQueue.empty()) {
102 Function *F = BasicBlockFwdRefQueue.front();
103 BasicBlockFwdRefQueue.pop_front();
104 assert(F && "Expected valid function");
105 if (!BasicBlockFwdRefs.count(F))
106 // Already materialized.
109 // Check for a function that isn't materializable to prevent an infinite
110 // loop. When parsing a blockaddress stored in a global variable, there
111 // isn't a trivial way to check if a function will have a body without a
112 // linear search through FunctionsWithBodies, so just check it here.
113 if (!F->isMaterializable())
114 return Error("Never resolved function from blockaddress");
116 // Try to materialize F.
117 if (std::error_code EC = materialize(F))
120 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
123 WillMaterializeAllForwardRefs = false;
124 return std::error_code();
127 void BitcodeReader::FreeState() {
129 std::vector<Type*>().swap(TypeList);
132 std::vector<Comdat *>().swap(ComdatList);
134 std::vector<AttributeSet>().swap(MAttributes);
135 std::vector<BasicBlock*>().swap(FunctionBBs);
136 std::vector<Function*>().swap(FunctionsWithBodies);
137 DeferredFunctionInfo.clear();
140 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
141 BasicBlockFwdRefQueue.clear();
144 //===----------------------------------------------------------------------===//
145 // Helper functions to implement forward reference resolution, etc.
146 //===----------------------------------------------------------------------===//
148 /// ConvertToString - Convert a string from a record into an std::string, return
150 template<typename StrTy>
151 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
153 if (Idx > Record.size())
156 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
157 Result += (char)Record[i];
161 static bool hasImplicitComdat(size_t Val) {
165 case 1: // Old WeakAnyLinkage
166 case 4: // Old LinkOnceAnyLinkage
167 case 10: // Old WeakODRLinkage
168 case 11: // Old LinkOnceODRLinkage
173 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
175 default: // Map unknown/new linkages to external
177 return GlobalValue::ExternalLinkage;
179 return GlobalValue::AppendingLinkage;
181 return GlobalValue::InternalLinkage;
183 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
185 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
187 return GlobalValue::ExternalWeakLinkage;
189 return GlobalValue::CommonLinkage;
191 return GlobalValue::PrivateLinkage;
193 return GlobalValue::AvailableExternallyLinkage;
195 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
197 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
199 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
200 case 1: // Old value with implicit comdat.
202 return GlobalValue::WeakAnyLinkage;
203 case 10: // Old value with implicit comdat.
205 return GlobalValue::WeakODRLinkage;
206 case 4: // Old value with implicit comdat.
208 return GlobalValue::LinkOnceAnyLinkage;
209 case 11: // Old value with implicit comdat.
211 return GlobalValue::LinkOnceODRLinkage;
215 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
217 default: // Map unknown visibilities to default.
218 case 0: return GlobalValue::DefaultVisibility;
219 case 1: return GlobalValue::HiddenVisibility;
220 case 2: return GlobalValue::ProtectedVisibility;
224 static GlobalValue::DLLStorageClassTypes
225 GetDecodedDLLStorageClass(unsigned Val) {
227 default: // Map unknown values to default.
228 case 0: return GlobalValue::DefaultStorageClass;
229 case 1: return GlobalValue::DLLImportStorageClass;
230 case 2: return GlobalValue::DLLExportStorageClass;
234 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
236 case 0: return GlobalVariable::NotThreadLocal;
237 default: // Map unknown non-zero value to general dynamic.
238 case 1: return GlobalVariable::GeneralDynamicTLSModel;
239 case 2: return GlobalVariable::LocalDynamicTLSModel;
240 case 3: return GlobalVariable::InitialExecTLSModel;
241 case 4: return GlobalVariable::LocalExecTLSModel;
245 static int GetDecodedCastOpcode(unsigned Val) {
248 case bitc::CAST_TRUNC : return Instruction::Trunc;
249 case bitc::CAST_ZEXT : return Instruction::ZExt;
250 case bitc::CAST_SEXT : return Instruction::SExt;
251 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
252 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
253 case bitc::CAST_UITOFP : return Instruction::UIToFP;
254 case bitc::CAST_SITOFP : return Instruction::SIToFP;
255 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
256 case bitc::CAST_FPEXT : return Instruction::FPExt;
257 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
258 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
259 case bitc::CAST_BITCAST : return Instruction::BitCast;
260 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
263 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
266 case bitc::BINOP_ADD:
267 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
268 case bitc::BINOP_SUB:
269 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
270 case bitc::BINOP_MUL:
271 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
272 case bitc::BINOP_UDIV: return Instruction::UDiv;
273 case bitc::BINOP_SDIV:
274 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
275 case bitc::BINOP_UREM: return Instruction::URem;
276 case bitc::BINOP_SREM:
277 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
278 case bitc::BINOP_SHL: return Instruction::Shl;
279 case bitc::BINOP_LSHR: return Instruction::LShr;
280 case bitc::BINOP_ASHR: return Instruction::AShr;
281 case bitc::BINOP_AND: return Instruction::And;
282 case bitc::BINOP_OR: return Instruction::Or;
283 case bitc::BINOP_XOR: return Instruction::Xor;
287 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
289 default: return AtomicRMWInst::BAD_BINOP;
290 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
291 case bitc::RMW_ADD: return AtomicRMWInst::Add;
292 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
293 case bitc::RMW_AND: return AtomicRMWInst::And;
294 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
295 case bitc::RMW_OR: return AtomicRMWInst::Or;
296 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
297 case bitc::RMW_MAX: return AtomicRMWInst::Max;
298 case bitc::RMW_MIN: return AtomicRMWInst::Min;
299 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
300 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
304 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
306 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
307 case bitc::ORDERING_UNORDERED: return Unordered;
308 case bitc::ORDERING_MONOTONIC: return Monotonic;
309 case bitc::ORDERING_ACQUIRE: return Acquire;
310 case bitc::ORDERING_RELEASE: return Release;
311 case bitc::ORDERING_ACQREL: return AcquireRelease;
312 default: // Map unknown orderings to sequentially-consistent.
313 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
317 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
319 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
320 default: // Map unknown scopes to cross-thread.
321 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
325 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
327 default: // Map unknown selection kinds to any.
328 case bitc::COMDAT_SELECTION_KIND_ANY:
330 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
331 return Comdat::ExactMatch;
332 case bitc::COMDAT_SELECTION_KIND_LARGEST:
333 return Comdat::Largest;
334 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
335 return Comdat::NoDuplicates;
336 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
337 return Comdat::SameSize;
341 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
343 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
344 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
350 /// @brief A class for maintaining the slot number definition
351 /// as a placeholder for the actual definition for forward constants defs.
352 class ConstantPlaceHolder : public ConstantExpr {
353 void operator=(const ConstantPlaceHolder &) = delete;
355 // allocate space for exactly one operand
356 void *operator new(size_t s) {
357 return User::operator new(s, 1);
359 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
360 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
361 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
364 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
365 static bool classof(const Value *V) {
366 return isa<ConstantExpr>(V) &&
367 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
371 /// Provide fast operand accessors
372 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
376 // FIXME: can we inherit this from ConstantExpr?
378 struct OperandTraits<ConstantPlaceHolder> :
379 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
381 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
385 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
394 WeakVH &OldV = ValuePtrs[Idx];
400 // Handle constants and non-constants (e.g. instrs) differently for
402 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
403 ResolveConstants.push_back(std::make_pair(PHC, Idx));
406 // If there was a forward reference to this value, replace it.
407 Value *PrevVal = OldV;
408 OldV->replaceAllUsesWith(V);
414 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
419 if (Value *V = ValuePtrs[Idx]) {
420 assert(Ty == V->getType() && "Type mismatch in constant table!");
421 return cast<Constant>(V);
424 // Create and return a placeholder, which will later be RAUW'd.
425 Constant *C = new ConstantPlaceHolder(Ty, Context);
430 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
434 if (Value *V = ValuePtrs[Idx]) {
435 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
439 // No type specified, must be invalid reference.
440 if (!Ty) return nullptr;
442 // Create and return a placeholder, which will later be RAUW'd.
443 Value *V = new Argument(Ty);
448 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
449 /// resolves any forward references. The idea behind this is that we sometimes
450 /// get constants (such as large arrays) which reference *many* forward ref
451 /// constants. Replacing each of these causes a lot of thrashing when
452 /// building/reuniquing the constant. Instead of doing this, we look at all the
453 /// uses and rewrite all the place holders at once for any constant that uses
455 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
456 // Sort the values by-pointer so that they are efficient to look up with a
458 std::sort(ResolveConstants.begin(), ResolveConstants.end());
460 SmallVector<Constant*, 64> NewOps;
462 while (!ResolveConstants.empty()) {
463 Value *RealVal = operator[](ResolveConstants.back().second);
464 Constant *Placeholder = ResolveConstants.back().first;
465 ResolveConstants.pop_back();
467 // Loop over all users of the placeholder, updating them to reference the
468 // new value. If they reference more than one placeholder, update them all
470 while (!Placeholder->use_empty()) {
471 auto UI = Placeholder->user_begin();
474 // If the using object isn't uniqued, just update the operands. This
475 // handles instructions and initializers for global variables.
476 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
477 UI.getUse().set(RealVal);
481 // Otherwise, we have a constant that uses the placeholder. Replace that
482 // constant with a new constant that has *all* placeholder uses updated.
483 Constant *UserC = cast<Constant>(U);
484 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
487 if (!isa<ConstantPlaceHolder>(*I)) {
488 // Not a placeholder reference.
490 } else if (*I == Placeholder) {
491 // Common case is that it just references this one placeholder.
494 // Otherwise, look up the placeholder in ResolveConstants.
495 ResolveConstantsTy::iterator It =
496 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
497 std::pair<Constant*, unsigned>(cast<Constant>(*I),
499 assert(It != ResolveConstants.end() && It->first == *I);
500 NewOp = operator[](It->second);
503 NewOps.push_back(cast<Constant>(NewOp));
506 // Make the new constant.
508 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
509 NewC = ConstantArray::get(UserCA->getType(), NewOps);
510 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
511 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
512 } else if (isa<ConstantVector>(UserC)) {
513 NewC = ConstantVector::get(NewOps);
515 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
516 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
519 UserC->replaceAllUsesWith(NewC);
520 UserC->destroyConstant();
524 // Update all ValueHandles, they should be the only users at this point.
525 Placeholder->replaceAllUsesWith(RealVal);
530 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
539 TrackingMDRef &OldMD = MDValuePtrs[Idx];
545 // If there was a forward reference to this value, replace it.
546 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
547 PrevMD->replaceAllUsesWith(MD);
551 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
555 if (Metadata *MD = MDValuePtrs[Idx])
558 // Track forward refs to be resolved later.
560 MinFwdRef = std::min(MinFwdRef, Idx);
561 MaxFwdRef = std::max(MaxFwdRef, Idx);
564 MinFwdRef = MaxFwdRef = Idx;
568 // Create and return a placeholder, which will later be RAUW'd.
569 Metadata *MD = MDNode::getTemporary(Context, None).release();
570 MDValuePtrs[Idx].reset(MD);
574 void BitcodeReaderMDValueList::tryToResolveCycles() {
580 // Still forward references... can't resolve cycles.
583 // Resolve any cycles.
584 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
585 auto &MD = MDValuePtrs[I];
586 auto *N = dyn_cast_or_null<MDNode>(MD);
590 assert(!N->isTemporary() && "Unexpected forward reference");
594 // Make sure we return early again until there's another forward ref.
598 Type *BitcodeReader::getTypeByID(unsigned ID) {
599 // The type table size is always specified correctly.
600 if (ID >= TypeList.size())
603 if (Type *Ty = TypeList[ID])
606 // If we have a forward reference, the only possible case is when it is to a
607 // named struct. Just create a placeholder for now.
608 return TypeList[ID] = createIdentifiedStructType(Context);
611 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
613 auto *Ret = StructType::create(Context, Name);
614 IdentifiedStructTypes.push_back(Ret);
618 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
619 auto *Ret = StructType::create(Context);
620 IdentifiedStructTypes.push_back(Ret);
625 //===----------------------------------------------------------------------===//
626 // Functions for parsing blocks from the bitcode file
627 //===----------------------------------------------------------------------===//
630 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
631 /// been decoded from the given integer. This function must stay in sync with
632 /// 'encodeLLVMAttributesForBitcode'.
633 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
634 uint64_t EncodedAttrs) {
635 // FIXME: Remove in 4.0.
637 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
638 // the bits above 31 down by 11 bits.
639 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
640 assert((!Alignment || isPowerOf2_32(Alignment)) &&
641 "Alignment must be a power of two.");
644 B.addAlignmentAttr(Alignment);
645 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
646 (EncodedAttrs & 0xffff));
649 std::error_code BitcodeReader::ParseAttributeBlock() {
650 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
651 return Error("Invalid record");
653 if (!MAttributes.empty())
654 return Error("Invalid multiple blocks");
656 SmallVector<uint64_t, 64> Record;
658 SmallVector<AttributeSet, 8> Attrs;
660 // Read all the records.
662 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
664 switch (Entry.Kind) {
665 case BitstreamEntry::SubBlock: // Handled for us already.
666 case BitstreamEntry::Error:
667 return Error("Malformed block");
668 case BitstreamEntry::EndBlock:
669 return std::error_code();
670 case BitstreamEntry::Record:
671 // The interesting case.
677 switch (Stream.readRecord(Entry.ID, Record)) {
678 default: // Default behavior: ignore.
680 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
681 // FIXME: Remove in 4.0.
682 if (Record.size() & 1)
683 return Error("Invalid record");
685 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
687 decodeLLVMAttributesForBitcode(B, Record[i+1]);
688 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
691 MAttributes.push_back(AttributeSet::get(Context, Attrs));
695 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
696 for (unsigned i = 0, e = Record.size(); i != e; ++i)
697 Attrs.push_back(MAttributeGroups[Record[i]]);
699 MAttributes.push_back(AttributeSet::get(Context, Attrs));
707 // Returns Attribute::None on unrecognized codes.
708 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
711 return Attribute::None;
712 case bitc::ATTR_KIND_ALIGNMENT:
713 return Attribute::Alignment;
714 case bitc::ATTR_KIND_ALWAYS_INLINE:
715 return Attribute::AlwaysInline;
716 case bitc::ATTR_KIND_BUILTIN:
717 return Attribute::Builtin;
718 case bitc::ATTR_KIND_BY_VAL:
719 return Attribute::ByVal;
720 case bitc::ATTR_KIND_IN_ALLOCA:
721 return Attribute::InAlloca;
722 case bitc::ATTR_KIND_COLD:
723 return Attribute::Cold;
724 case bitc::ATTR_KIND_INLINE_HINT:
725 return Attribute::InlineHint;
726 case bitc::ATTR_KIND_IN_REG:
727 return Attribute::InReg;
728 case bitc::ATTR_KIND_JUMP_TABLE:
729 return Attribute::JumpTable;
730 case bitc::ATTR_KIND_MIN_SIZE:
731 return Attribute::MinSize;
732 case bitc::ATTR_KIND_NAKED:
733 return Attribute::Naked;
734 case bitc::ATTR_KIND_NEST:
735 return Attribute::Nest;
736 case bitc::ATTR_KIND_NO_ALIAS:
737 return Attribute::NoAlias;
738 case bitc::ATTR_KIND_NO_BUILTIN:
739 return Attribute::NoBuiltin;
740 case bitc::ATTR_KIND_NO_CAPTURE:
741 return Attribute::NoCapture;
742 case bitc::ATTR_KIND_NO_DUPLICATE:
743 return Attribute::NoDuplicate;
744 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
745 return Attribute::NoImplicitFloat;
746 case bitc::ATTR_KIND_NO_INLINE:
747 return Attribute::NoInline;
748 case bitc::ATTR_KIND_NON_LAZY_BIND:
749 return Attribute::NonLazyBind;
750 case bitc::ATTR_KIND_NON_NULL:
751 return Attribute::NonNull;
752 case bitc::ATTR_KIND_DEREFERENCEABLE:
753 return Attribute::Dereferenceable;
754 case bitc::ATTR_KIND_NO_RED_ZONE:
755 return Attribute::NoRedZone;
756 case bitc::ATTR_KIND_NO_RETURN:
757 return Attribute::NoReturn;
758 case bitc::ATTR_KIND_NO_UNWIND:
759 return Attribute::NoUnwind;
760 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
761 return Attribute::OptimizeForSize;
762 case bitc::ATTR_KIND_OPTIMIZE_NONE:
763 return Attribute::OptimizeNone;
764 case bitc::ATTR_KIND_READ_NONE:
765 return Attribute::ReadNone;
766 case bitc::ATTR_KIND_READ_ONLY:
767 return Attribute::ReadOnly;
768 case bitc::ATTR_KIND_RETURNED:
769 return Attribute::Returned;
770 case bitc::ATTR_KIND_RETURNS_TWICE:
771 return Attribute::ReturnsTwice;
772 case bitc::ATTR_KIND_S_EXT:
773 return Attribute::SExt;
774 case bitc::ATTR_KIND_STACK_ALIGNMENT:
775 return Attribute::StackAlignment;
776 case bitc::ATTR_KIND_STACK_PROTECT:
777 return Attribute::StackProtect;
778 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
779 return Attribute::StackProtectReq;
780 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
781 return Attribute::StackProtectStrong;
782 case bitc::ATTR_KIND_STRUCT_RET:
783 return Attribute::StructRet;
784 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
785 return Attribute::SanitizeAddress;
786 case bitc::ATTR_KIND_SANITIZE_THREAD:
787 return Attribute::SanitizeThread;
788 case bitc::ATTR_KIND_SANITIZE_MEMORY:
789 return Attribute::SanitizeMemory;
790 case bitc::ATTR_KIND_UW_TABLE:
791 return Attribute::UWTable;
792 case bitc::ATTR_KIND_Z_EXT:
793 return Attribute::ZExt;
797 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
798 Attribute::AttrKind *Kind) {
799 *Kind = GetAttrFromCode(Code);
800 if (*Kind == Attribute::None)
801 return Error(BitcodeError::CorruptedBitcode,
802 "Unknown attribute kind (" + Twine(Code) + ")");
803 return std::error_code();
806 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
807 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
808 return Error("Invalid record");
810 if (!MAttributeGroups.empty())
811 return Error("Invalid multiple blocks");
813 SmallVector<uint64_t, 64> Record;
815 // Read all the records.
817 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
819 switch (Entry.Kind) {
820 case BitstreamEntry::SubBlock: // Handled for us already.
821 case BitstreamEntry::Error:
822 return Error("Malformed block");
823 case BitstreamEntry::EndBlock:
824 return std::error_code();
825 case BitstreamEntry::Record:
826 // The interesting case.
832 switch (Stream.readRecord(Entry.ID, Record)) {
833 default: // Default behavior: ignore.
835 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
836 if (Record.size() < 3)
837 return Error("Invalid record");
839 uint64_t GrpID = Record[0];
840 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
843 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
844 if (Record[i] == 0) { // Enum attribute
845 Attribute::AttrKind Kind;
846 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
849 B.addAttribute(Kind);
850 } else if (Record[i] == 1) { // Integer attribute
851 Attribute::AttrKind Kind;
852 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
854 if (Kind == Attribute::Alignment)
855 B.addAlignmentAttr(Record[++i]);
856 else if (Kind == Attribute::StackAlignment)
857 B.addStackAlignmentAttr(Record[++i]);
858 else if (Kind == Attribute::Dereferenceable)
859 B.addDereferenceableAttr(Record[++i]);
860 } else { // String attribute
861 assert((Record[i] == 3 || Record[i] == 4) &&
862 "Invalid attribute group entry");
863 bool HasValue = (Record[i++] == 4);
864 SmallString<64> KindStr;
865 SmallString<64> ValStr;
867 while (Record[i] != 0 && i != e)
868 KindStr += Record[i++];
869 assert(Record[i] == 0 && "Kind string not null terminated");
872 // Has a value associated with it.
873 ++i; // Skip the '0' that terminates the "kind" string.
874 while (Record[i] != 0 && i != e)
875 ValStr += Record[i++];
876 assert(Record[i] == 0 && "Value string not null terminated");
879 B.addAttribute(KindStr.str(), ValStr.str());
883 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
890 std::error_code BitcodeReader::ParseTypeTable() {
891 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
892 return Error("Invalid record");
894 return ParseTypeTableBody();
897 std::error_code BitcodeReader::ParseTypeTableBody() {
898 if (!TypeList.empty())
899 return Error("Invalid multiple blocks");
901 SmallVector<uint64_t, 64> Record;
902 unsigned NumRecords = 0;
904 SmallString<64> TypeName;
906 // Read all the records for this type table.
908 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
910 switch (Entry.Kind) {
911 case BitstreamEntry::SubBlock: // Handled for us already.
912 case BitstreamEntry::Error:
913 return Error("Malformed block");
914 case BitstreamEntry::EndBlock:
915 if (NumRecords != TypeList.size())
916 return Error("Malformed block");
917 return std::error_code();
918 case BitstreamEntry::Record:
919 // The interesting case.
925 Type *ResultTy = nullptr;
926 switch (Stream.readRecord(Entry.ID, Record)) {
928 return Error("Invalid value");
929 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
930 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
931 // type list. This allows us to reserve space.
932 if (Record.size() < 1)
933 return Error("Invalid record");
934 TypeList.resize(Record[0]);
936 case bitc::TYPE_CODE_VOID: // VOID
937 ResultTy = Type::getVoidTy(Context);
939 case bitc::TYPE_CODE_HALF: // HALF
940 ResultTy = Type::getHalfTy(Context);
942 case bitc::TYPE_CODE_FLOAT: // FLOAT
943 ResultTy = Type::getFloatTy(Context);
945 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
946 ResultTy = Type::getDoubleTy(Context);
948 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
949 ResultTy = Type::getX86_FP80Ty(Context);
951 case bitc::TYPE_CODE_FP128: // FP128
952 ResultTy = Type::getFP128Ty(Context);
954 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
955 ResultTy = Type::getPPC_FP128Ty(Context);
957 case bitc::TYPE_CODE_LABEL: // LABEL
958 ResultTy = Type::getLabelTy(Context);
960 case bitc::TYPE_CODE_METADATA: // METADATA
961 ResultTy = Type::getMetadataTy(Context);
963 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
964 ResultTy = Type::getX86_MMXTy(Context);
966 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
967 if (Record.size() < 1)
968 return Error("Invalid record");
970 uint64_t NumBits = Record[0];
971 if (NumBits < IntegerType::MIN_INT_BITS ||
972 NumBits > IntegerType::MAX_INT_BITS)
973 return Error("Bitwidth for integer type out of range");
974 ResultTy = IntegerType::get(Context, NumBits);
977 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
978 // [pointee type, address space]
979 if (Record.size() < 1)
980 return Error("Invalid record");
981 unsigned AddressSpace = 0;
982 if (Record.size() == 2)
983 AddressSpace = Record[1];
984 ResultTy = getTypeByID(Record[0]);
986 return Error("Invalid type");
987 ResultTy = PointerType::get(ResultTy, AddressSpace);
990 case bitc::TYPE_CODE_FUNCTION_OLD: {
991 // FIXME: attrid is dead, remove it in LLVM 4.0
992 // FUNCTION: [vararg, attrid, retty, paramty x N]
993 if (Record.size() < 3)
994 return Error("Invalid record");
995 SmallVector<Type*, 8> ArgTys;
996 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
997 if (Type *T = getTypeByID(Record[i]))
1003 ResultTy = getTypeByID(Record[2]);
1004 if (!ResultTy || ArgTys.size() < Record.size()-3)
1005 return Error("Invalid type");
1007 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1010 case bitc::TYPE_CODE_FUNCTION: {
1011 // FUNCTION: [vararg, retty, paramty x N]
1012 if (Record.size() < 2)
1013 return Error("Invalid record");
1014 SmallVector<Type*, 8> ArgTys;
1015 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1016 if (Type *T = getTypeByID(Record[i]))
1017 ArgTys.push_back(T);
1022 ResultTy = getTypeByID(Record[1]);
1023 if (!ResultTy || ArgTys.size() < Record.size()-2)
1024 return Error("Invalid type");
1026 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1029 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1030 if (Record.size() < 1)
1031 return Error("Invalid record");
1032 SmallVector<Type*, 8> EltTys;
1033 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1034 if (Type *T = getTypeByID(Record[i]))
1035 EltTys.push_back(T);
1039 if (EltTys.size() != Record.size()-1)
1040 return Error("Invalid type");
1041 ResultTy = StructType::get(Context, EltTys, Record[0]);
1044 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1045 if (ConvertToString(Record, 0, TypeName))
1046 return Error("Invalid record");
1049 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1050 if (Record.size() < 1)
1051 return Error("Invalid record");
1053 if (NumRecords >= TypeList.size())
1054 return Error("Invalid TYPE table");
1056 // Check to see if this was forward referenced, if so fill in the temp.
1057 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1059 Res->setName(TypeName);
1060 TypeList[NumRecords] = nullptr;
1061 } else // Otherwise, create a new struct.
1062 Res = createIdentifiedStructType(Context, TypeName);
1065 SmallVector<Type*, 8> EltTys;
1066 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1067 if (Type *T = getTypeByID(Record[i]))
1068 EltTys.push_back(T);
1072 if (EltTys.size() != Record.size()-1)
1073 return Error("Invalid record");
1074 Res->setBody(EltTys, Record[0]);
1078 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1079 if (Record.size() != 1)
1080 return Error("Invalid record");
1082 if (NumRecords >= TypeList.size())
1083 return Error("Invalid TYPE table");
1085 // Check to see if this was forward referenced, if so fill in the temp.
1086 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1088 Res->setName(TypeName);
1089 TypeList[NumRecords] = nullptr;
1090 } else // Otherwise, create a new struct with no body.
1091 Res = createIdentifiedStructType(Context, TypeName);
1096 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1097 if (Record.size() < 2)
1098 return Error("Invalid record");
1099 if ((ResultTy = getTypeByID(Record[1])))
1100 ResultTy = ArrayType::get(ResultTy, Record[0]);
1102 return Error("Invalid type");
1104 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1105 if (Record.size() < 2)
1106 return Error("Invalid record");
1107 if ((ResultTy = getTypeByID(Record[1])))
1108 ResultTy = VectorType::get(ResultTy, Record[0]);
1110 return Error("Invalid type");
1114 if (NumRecords >= TypeList.size())
1115 return Error("Invalid TYPE table");
1116 if (TypeList[NumRecords])
1118 "Invalid TYPE table: Only named structs can be forward referenced");
1119 assert(ResultTy && "Didn't read a type?");
1120 TypeList[NumRecords++] = ResultTy;
1124 std::error_code BitcodeReader::ParseValueSymbolTable() {
1125 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1126 return Error("Invalid record");
1128 SmallVector<uint64_t, 64> Record;
1130 Triple TT(TheModule->getTargetTriple());
1132 // Read all the records for this value table.
1133 SmallString<128> ValueName;
1135 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1137 switch (Entry.Kind) {
1138 case BitstreamEntry::SubBlock: // Handled for us already.
1139 case BitstreamEntry::Error:
1140 return Error("Malformed block");
1141 case BitstreamEntry::EndBlock:
1142 return std::error_code();
1143 case BitstreamEntry::Record:
1144 // The interesting case.
1150 switch (Stream.readRecord(Entry.ID, Record)) {
1151 default: // Default behavior: unknown type.
1153 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1154 if (ConvertToString(Record, 1, ValueName))
1155 return Error("Invalid record");
1156 unsigned ValueID = Record[0];
1157 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1158 return Error("Invalid record");
1159 Value *V = ValueList[ValueID];
1161 V->setName(StringRef(ValueName.data(), ValueName.size()));
1162 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1163 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1164 if (TT.isOSBinFormatMachO())
1165 GO->setComdat(nullptr);
1167 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1173 case bitc::VST_CODE_BBENTRY: {
1174 if (ConvertToString(Record, 1, ValueName))
1175 return Error("Invalid record");
1176 BasicBlock *BB = getBasicBlock(Record[0]);
1178 return Error("Invalid record");
1180 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1188 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1190 std::error_code BitcodeReader::ParseMetadata() {
1191 unsigned NextMDValueNo = MDValueList.size();
1193 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1194 return Error("Invalid record");
1196 SmallVector<uint64_t, 64> Record;
1199 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1200 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1202 return getMD(ID - 1);
1205 auto getMDString = [&](unsigned ID) -> MDString *{
1206 // This requires that the ID is not really a forward reference. In
1207 // particular, the MDString must already have been resolved.
1208 return cast_or_null<MDString>(getMDOrNull(ID));
1211 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1212 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1214 // Read all the records.
1216 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1218 switch (Entry.Kind) {
1219 case BitstreamEntry::SubBlock: // Handled for us already.
1220 case BitstreamEntry::Error:
1221 return Error("Malformed block");
1222 case BitstreamEntry::EndBlock:
1223 MDValueList.tryToResolveCycles();
1224 return std::error_code();
1225 case BitstreamEntry::Record:
1226 // The interesting case.
1232 unsigned Code = Stream.readRecord(Entry.ID, Record);
1233 bool IsDistinct = false;
1235 default: // Default behavior: ignore.
1237 case bitc::METADATA_NAME: {
1238 // Read name of the named metadata.
1239 SmallString<8> Name(Record.begin(), Record.end());
1241 Code = Stream.ReadCode();
1243 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1244 unsigned NextBitCode = Stream.readRecord(Code, Record);
1245 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1247 // Read named metadata elements.
1248 unsigned Size = Record.size();
1249 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1250 for (unsigned i = 0; i != Size; ++i) {
1251 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1253 return Error("Invalid record");
1254 NMD->addOperand(MD);
1258 case bitc::METADATA_OLD_FN_NODE: {
1259 // FIXME: Remove in 4.0.
1260 // This is a LocalAsMetadata record, the only type of function-local
1262 if (Record.size() % 2 == 1)
1263 return Error("Invalid record");
1265 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1266 // to be legal, but there's no upgrade path.
1267 auto dropRecord = [&] {
1268 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1270 if (Record.size() != 2) {
1275 Type *Ty = getTypeByID(Record[0]);
1276 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1281 MDValueList.AssignValue(
1282 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1286 case bitc::METADATA_OLD_NODE: {
1287 // FIXME: Remove in 4.0.
1288 if (Record.size() % 2 == 1)
1289 return Error("Invalid record");
1291 unsigned Size = Record.size();
1292 SmallVector<Metadata *, 8> Elts;
1293 for (unsigned i = 0; i != Size; i += 2) {
1294 Type *Ty = getTypeByID(Record[i]);
1296 return Error("Invalid record");
1297 if (Ty->isMetadataTy())
1298 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1299 else if (!Ty->isVoidTy()) {
1301 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1302 assert(isa<ConstantAsMetadata>(MD) &&
1303 "Expected non-function-local metadata");
1306 Elts.push_back(nullptr);
1308 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1311 case bitc::METADATA_VALUE: {
1312 if (Record.size() != 2)
1313 return Error("Invalid record");
1315 Type *Ty = getTypeByID(Record[0]);
1316 if (Ty->isMetadataTy() || Ty->isVoidTy())
1317 return Error("Invalid record");
1319 MDValueList.AssignValue(
1320 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1324 case bitc::METADATA_DISTINCT_NODE:
1327 case bitc::METADATA_NODE: {
1328 SmallVector<Metadata *, 8> Elts;
1329 Elts.reserve(Record.size());
1330 for (unsigned ID : Record)
1331 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1332 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1333 : MDNode::get(Context, Elts),
1337 case bitc::METADATA_LOCATION: {
1338 if (Record.size() != 5)
1339 return Error("Invalid record");
1341 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1342 unsigned Line = Record[1];
1343 unsigned Column = Record[2];
1344 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1345 Metadata *InlinedAt =
1346 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1347 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1351 case bitc::METADATA_GENERIC_DEBUG: {
1352 if (Record.size() < 4)
1353 return Error("Invalid record");
1355 unsigned Tag = Record[1];
1356 unsigned Version = Record[2];
1358 if (Tag >= 1u << 16 || Version != 0)
1359 return Error("Invalid record");
1361 auto *Header = getMDString(Record[3]);
1362 SmallVector<Metadata *, 8> DwarfOps;
1363 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1364 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1366 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1367 (Context, Tag, Header, DwarfOps)),
1371 case bitc::METADATA_SUBRANGE: {
1372 if (Record.size() != 3)
1373 return Error("Invalid record");
1375 MDValueList.AssignValue(
1376 GET_OR_DISTINCT(MDSubrange, Record[0],
1377 (Context, Record[1], unrotateSign(Record[2]))),
1381 case bitc::METADATA_ENUMERATOR: {
1382 if (Record.size() != 3)
1383 return Error("Invalid record");
1385 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1386 (Context, unrotateSign(Record[1]),
1387 getMDString(Record[2]))),
1391 case bitc::METADATA_BASIC_TYPE: {
1392 if (Record.size() != 6)
1393 return Error("Invalid record");
1395 MDValueList.AssignValue(
1396 GET_OR_DISTINCT(MDBasicType, Record[0],
1397 (Context, Record[1], getMDString(Record[2]),
1398 Record[3], Record[4], Record[5])),
1402 case bitc::METADATA_DERIVED_TYPE: {
1403 if (Record.size() != 12)
1404 return Error("Invalid record");
1406 MDValueList.AssignValue(
1407 GET_OR_DISTINCT(MDDerivedType, Record[0],
1408 (Context, Record[1], getMDString(Record[2]),
1409 getMDOrNull(Record[3]), Record[4],
1410 getMDOrNull(Record[5]), getMD(Record[6]), Record[7],
1411 Record[8], Record[9], Record[10],
1412 getMDOrNull(Record[11]))),
1416 case bitc::METADATA_COMPOSITE_TYPE: {
1417 if (Record.size() != 16)
1418 return Error("Invalid record");
1420 MDValueList.AssignValue(
1421 GET_OR_DISTINCT(MDCompositeType, Record[0],
1422 (Context, Record[1], getMDString(Record[2]),
1423 getMDOrNull(Record[3]), Record[4],
1424 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1425 Record[7], Record[8], Record[9], Record[10],
1426 getMDOrNull(Record[11]), Record[12],
1427 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1428 getMDString(Record[15]))),
1432 case bitc::METADATA_SUBROUTINE_TYPE: {
1433 if (Record.size() != 3)
1434 return Error("Invalid record");
1436 MDValueList.AssignValue(
1437 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1438 (Context, Record[1], getMDOrNull(Record[2]))),
1442 case bitc::METADATA_FILE: {
1443 if (Record.size() != 3)
1444 return Error("Invalid record");
1446 MDValueList.AssignValue(
1447 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1448 getMDString(Record[2]))),
1452 case bitc::METADATA_COMPILE_UNIT: {
1453 if (Record.size() != 14)
1454 return Error("Invalid record");
1456 MDValueList.AssignValue(
1458 MDCompileUnit, Record[0],
1459 (Context, Record[1], getMD(Record[2]), getMDString(Record[3]),
1460 Record[4], getMDString(Record[5]), Record[6],
1461 getMDString(Record[7]), Record[8], getMDOrNull(Record[9]),
1462 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1463 getMDOrNull(Record[12]), getMDOrNull(Record[13]))),
1467 case bitc::METADATA_SUBPROGRAM: {
1468 if (Record.size() != 19)
1469 return Error("Invalid record");
1471 MDValueList.AssignValue(
1473 MDSubprogram, Record[0],
1474 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1475 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1476 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1477 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1478 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1479 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1483 case bitc::METADATA_LEXICAL_BLOCK: {
1484 if (Record.size() != 5)
1485 return Error("Invalid record");
1487 MDValueList.AssignValue(
1488 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1489 (Context, getMDOrNull(Record[1]),
1490 getMDOrNull(Record[2]), Record[3], Record[4])),
1494 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1495 if (Record.size() != 4)
1496 return Error("Invalid record");
1498 MDValueList.AssignValue(
1499 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1500 (Context, getMDOrNull(Record[1]),
1501 getMDOrNull(Record[2]), Record[3])),
1505 case bitc::METADATA_NAMESPACE: {
1506 if (Record.size() != 5)
1507 return Error("Invalid record");
1509 MDValueList.AssignValue(
1510 GET_OR_DISTINCT(MDNamespace, Record[0],
1511 (Context, getMDOrNull(Record[1]),
1512 getMDOrNull(Record[2]), getMDString(Record[3]),
1517 case bitc::METADATA_TEMPLATE_TYPE: {
1518 if (Record.size() != 3)
1519 return Error("Invalid record");
1521 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1523 (Context, getMDString(Record[1]),
1524 getMDOrNull(Record[2]))),
1528 case bitc::METADATA_TEMPLATE_VALUE: {
1529 if (Record.size() != 5)
1530 return Error("Invalid record");
1532 MDValueList.AssignValue(
1533 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1534 (Context, Record[1], getMDString(Record[2]),
1535 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1539 case bitc::METADATA_GLOBAL_VAR: {
1540 if (Record.size() != 11)
1541 return Error("Invalid record");
1543 MDValueList.AssignValue(
1544 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1545 (Context, getMDOrNull(Record[1]),
1546 getMDString(Record[2]), getMDString(Record[3]),
1547 getMDOrNull(Record[4]), Record[5],
1548 getMDOrNull(Record[6]), Record[7], Record[8],
1549 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1553 case bitc::METADATA_LOCAL_VAR: {
1554 if (Record.size() != 10)
1555 return Error("Invalid record");
1557 MDValueList.AssignValue(
1558 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1559 (Context, Record[1], getMDOrNull(Record[2]),
1560 getMDString(Record[3]), getMDOrNull(Record[4]),
1561 Record[5], getMDOrNull(Record[6]), Record[7],
1562 Record[8], getMDOrNull(Record[9]))),
1566 case bitc::METADATA_EXPRESSION: {
1567 if (Record.size() < 1)
1568 return Error("Invalid record");
1570 MDValueList.AssignValue(
1571 GET_OR_DISTINCT(MDExpression, Record[0],
1572 (Context, makeArrayRef(Record).slice(1))),
1576 case bitc::METADATA_OBJC_PROPERTY: {
1577 if (Record.size() != 8)
1578 return Error("Invalid record");
1580 MDValueList.AssignValue(
1581 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1582 (Context, getMDString(Record[1]),
1583 getMDOrNull(Record[2]), Record[3],
1584 getMDString(Record[4]), getMDString(Record[5]),
1585 Record[6], getMDOrNull(Record[7]))),
1589 case bitc::METADATA_IMPORTED_ENTITY: {
1590 if (Record.size() != 6)
1591 return Error("Invalid record");
1593 MDValueList.AssignValue(
1594 GET_OR_DISTINCT(MDImportedEntity, Record[0],
1595 (Context, Record[1], getMDOrNull(Record[2]),
1596 getMDOrNull(Record[3]), Record[4],
1597 getMDString(Record[5]))),
1601 case bitc::METADATA_STRING: {
1602 std::string String(Record.begin(), Record.end());
1603 llvm::UpgradeMDStringConstant(String);
1604 Metadata *MD = MDString::get(Context, String);
1605 MDValueList.AssignValue(MD, NextMDValueNo++);
1608 case bitc::METADATA_KIND: {
1609 if (Record.size() < 2)
1610 return Error("Invalid record");
1612 unsigned Kind = Record[0];
1613 SmallString<8> Name(Record.begin()+1, Record.end());
1615 unsigned NewKind = TheModule->getMDKindID(Name.str());
1616 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1617 return Error("Conflicting METADATA_KIND records");
1622 #undef GET_OR_DISTINCT
1625 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1626 /// the LSB for dense VBR encoding.
1627 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1632 // There is no such thing as -0 with integers. "-0" really means MININT.
1636 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1637 /// values and aliases that we can.
1638 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1639 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1640 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1641 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1642 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1644 GlobalInitWorklist.swap(GlobalInits);
1645 AliasInitWorklist.swap(AliasInits);
1646 FunctionPrefixWorklist.swap(FunctionPrefixes);
1647 FunctionPrologueWorklist.swap(FunctionPrologues);
1649 while (!GlobalInitWorklist.empty()) {
1650 unsigned ValID = GlobalInitWorklist.back().second;
1651 if (ValID >= ValueList.size()) {
1652 // Not ready to resolve this yet, it requires something later in the file.
1653 GlobalInits.push_back(GlobalInitWorklist.back());
1655 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1656 GlobalInitWorklist.back().first->setInitializer(C);
1658 return Error("Expected a constant");
1660 GlobalInitWorklist.pop_back();
1663 while (!AliasInitWorklist.empty()) {
1664 unsigned ValID = AliasInitWorklist.back().second;
1665 if (ValID >= ValueList.size()) {
1666 AliasInits.push_back(AliasInitWorklist.back());
1668 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1669 AliasInitWorklist.back().first->setAliasee(C);
1671 return Error("Expected a constant");
1673 AliasInitWorklist.pop_back();
1676 while (!FunctionPrefixWorklist.empty()) {
1677 unsigned ValID = FunctionPrefixWorklist.back().second;
1678 if (ValID >= ValueList.size()) {
1679 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1681 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1682 FunctionPrefixWorklist.back().first->setPrefixData(C);
1684 return Error("Expected a constant");
1686 FunctionPrefixWorklist.pop_back();
1689 while (!FunctionPrologueWorklist.empty()) {
1690 unsigned ValID = FunctionPrologueWorklist.back().second;
1691 if (ValID >= ValueList.size()) {
1692 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1694 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1695 FunctionPrologueWorklist.back().first->setPrologueData(C);
1697 return Error("Expected a constant");
1699 FunctionPrologueWorklist.pop_back();
1702 return std::error_code();
1705 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1706 SmallVector<uint64_t, 8> Words(Vals.size());
1707 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1708 BitcodeReader::decodeSignRotatedValue);
1710 return APInt(TypeBits, Words);
1713 std::error_code BitcodeReader::ParseConstants() {
1714 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1715 return Error("Invalid record");
1717 SmallVector<uint64_t, 64> Record;
1719 // Read all the records for this value table.
1720 Type *CurTy = Type::getInt32Ty(Context);
1721 unsigned NextCstNo = ValueList.size();
1723 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1725 switch (Entry.Kind) {
1726 case BitstreamEntry::SubBlock: // Handled for us already.
1727 case BitstreamEntry::Error:
1728 return Error("Malformed block");
1729 case BitstreamEntry::EndBlock:
1730 if (NextCstNo != ValueList.size())
1731 return Error("Invalid ronstant reference");
1733 // Once all the constants have been read, go through and resolve forward
1735 ValueList.ResolveConstantForwardRefs();
1736 return std::error_code();
1737 case BitstreamEntry::Record:
1738 // The interesting case.
1745 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1747 default: // Default behavior: unknown constant
1748 case bitc::CST_CODE_UNDEF: // UNDEF
1749 V = UndefValue::get(CurTy);
1751 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1753 return Error("Invalid record");
1754 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1755 return Error("Invalid record");
1756 CurTy = TypeList[Record[0]];
1757 continue; // Skip the ValueList manipulation.
1758 case bitc::CST_CODE_NULL: // NULL
1759 V = Constant::getNullValue(CurTy);
1761 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1762 if (!CurTy->isIntegerTy() || Record.empty())
1763 return Error("Invalid record");
1764 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1766 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1767 if (!CurTy->isIntegerTy() || Record.empty())
1768 return Error("Invalid record");
1770 APInt VInt = ReadWideAPInt(Record,
1771 cast<IntegerType>(CurTy)->getBitWidth());
1772 V = ConstantInt::get(Context, VInt);
1776 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1778 return Error("Invalid record");
1779 if (CurTy->isHalfTy())
1780 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1781 APInt(16, (uint16_t)Record[0])));
1782 else if (CurTy->isFloatTy())
1783 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1784 APInt(32, (uint32_t)Record[0])));
1785 else if (CurTy->isDoubleTy())
1786 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1787 APInt(64, Record[0])));
1788 else if (CurTy->isX86_FP80Ty()) {
1789 // Bits are not stored the same way as a normal i80 APInt, compensate.
1790 uint64_t Rearrange[2];
1791 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1792 Rearrange[1] = Record[0] >> 48;
1793 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1794 APInt(80, Rearrange)));
1795 } else if (CurTy->isFP128Ty())
1796 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1797 APInt(128, Record)));
1798 else if (CurTy->isPPC_FP128Ty())
1799 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1800 APInt(128, Record)));
1802 V = UndefValue::get(CurTy);
1806 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1808 return Error("Invalid record");
1810 unsigned Size = Record.size();
1811 SmallVector<Constant*, 16> Elts;
1813 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1814 for (unsigned i = 0; i != Size; ++i)
1815 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1816 STy->getElementType(i)));
1817 V = ConstantStruct::get(STy, Elts);
1818 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1819 Type *EltTy = ATy->getElementType();
1820 for (unsigned i = 0; i != Size; ++i)
1821 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1822 V = ConstantArray::get(ATy, Elts);
1823 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1824 Type *EltTy = VTy->getElementType();
1825 for (unsigned i = 0; i != Size; ++i)
1826 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1827 V = ConstantVector::get(Elts);
1829 V = UndefValue::get(CurTy);
1833 case bitc::CST_CODE_STRING: // STRING: [values]
1834 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1836 return Error("Invalid record");
1838 SmallString<16> Elts(Record.begin(), Record.end());
1839 V = ConstantDataArray::getString(Context, Elts,
1840 BitCode == bitc::CST_CODE_CSTRING);
1843 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1845 return Error("Invalid record");
1847 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1848 unsigned Size = Record.size();
1850 if (EltTy->isIntegerTy(8)) {
1851 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1852 if (isa<VectorType>(CurTy))
1853 V = ConstantDataVector::get(Context, Elts);
1855 V = ConstantDataArray::get(Context, Elts);
1856 } else if (EltTy->isIntegerTy(16)) {
1857 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1858 if (isa<VectorType>(CurTy))
1859 V = ConstantDataVector::get(Context, Elts);
1861 V = ConstantDataArray::get(Context, Elts);
1862 } else if (EltTy->isIntegerTy(32)) {
1863 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1864 if (isa<VectorType>(CurTy))
1865 V = ConstantDataVector::get(Context, Elts);
1867 V = ConstantDataArray::get(Context, Elts);
1868 } else if (EltTy->isIntegerTy(64)) {
1869 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1870 if (isa<VectorType>(CurTy))
1871 V = ConstantDataVector::get(Context, Elts);
1873 V = ConstantDataArray::get(Context, Elts);
1874 } else if (EltTy->isFloatTy()) {
1875 SmallVector<float, 16> Elts(Size);
1876 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1877 if (isa<VectorType>(CurTy))
1878 V = ConstantDataVector::get(Context, Elts);
1880 V = ConstantDataArray::get(Context, Elts);
1881 } else if (EltTy->isDoubleTy()) {
1882 SmallVector<double, 16> Elts(Size);
1883 std::transform(Record.begin(), Record.end(), Elts.begin(),
1885 if (isa<VectorType>(CurTy))
1886 V = ConstantDataVector::get(Context, Elts);
1888 V = ConstantDataArray::get(Context, Elts);
1890 return Error("Invalid type for value");
1895 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1896 if (Record.size() < 3)
1897 return Error("Invalid record");
1898 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1900 V = UndefValue::get(CurTy); // Unknown binop.
1902 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1903 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1905 if (Record.size() >= 4) {
1906 if (Opc == Instruction::Add ||
1907 Opc == Instruction::Sub ||
1908 Opc == Instruction::Mul ||
1909 Opc == Instruction::Shl) {
1910 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1911 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1912 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1913 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1914 } else if (Opc == Instruction::SDiv ||
1915 Opc == Instruction::UDiv ||
1916 Opc == Instruction::LShr ||
1917 Opc == Instruction::AShr) {
1918 if (Record[3] & (1 << bitc::PEO_EXACT))
1919 Flags |= SDivOperator::IsExact;
1922 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1926 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1927 if (Record.size() < 3)
1928 return Error("Invalid record");
1929 int Opc = GetDecodedCastOpcode(Record[0]);
1931 V = UndefValue::get(CurTy); // Unknown cast.
1933 Type *OpTy = getTypeByID(Record[1]);
1935 return Error("Invalid record");
1936 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1937 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1938 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1942 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1943 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1944 if (Record.size() & 1)
1945 return Error("Invalid record");
1946 SmallVector<Constant*, 16> Elts;
1947 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1948 Type *ElTy = getTypeByID(Record[i]);
1950 return Error("Invalid record");
1951 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1953 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1954 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1956 bitc::CST_CODE_CE_INBOUNDS_GEP);
1959 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1960 if (Record.size() < 3)
1961 return Error("Invalid record");
1963 Type *SelectorTy = Type::getInt1Ty(Context);
1965 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1966 // vector. Otherwise, it must be a single bit.
1967 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1968 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1969 VTy->getNumElements());
1971 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1973 ValueList.getConstantFwdRef(Record[1],CurTy),
1974 ValueList.getConstantFwdRef(Record[2],CurTy));
1977 case bitc::CST_CODE_CE_EXTRACTELT
1978 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1979 if (Record.size() < 3)
1980 return Error("Invalid record");
1982 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1984 return Error("Invalid record");
1985 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1986 Constant *Op1 = nullptr;
1987 if (Record.size() == 4) {
1988 Type *IdxTy = getTypeByID(Record[2]);
1990 return Error("Invalid record");
1991 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1992 } else // TODO: Remove with llvm 4.0
1993 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1995 return Error("Invalid record");
1996 V = ConstantExpr::getExtractElement(Op0, Op1);
1999 case bitc::CST_CODE_CE_INSERTELT
2000 : { // CE_INSERTELT: [opval, opval, opty, opval]
2001 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2002 if (Record.size() < 3 || !OpTy)
2003 return Error("Invalid record");
2004 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2005 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2006 OpTy->getElementType());
2007 Constant *Op2 = nullptr;
2008 if (Record.size() == 4) {
2009 Type *IdxTy = getTypeByID(Record[2]);
2011 return Error("Invalid record");
2012 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2013 } else // TODO: Remove with llvm 4.0
2014 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2016 return Error("Invalid record");
2017 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2020 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2021 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2022 if (Record.size() < 3 || !OpTy)
2023 return Error("Invalid record");
2024 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2025 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2026 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2027 OpTy->getNumElements());
2028 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2029 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2032 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2033 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2035 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2036 if (Record.size() < 4 || !RTy || !OpTy)
2037 return Error("Invalid record");
2038 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2039 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2040 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2041 RTy->getNumElements());
2042 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2043 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2046 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2047 if (Record.size() < 4)
2048 return Error("Invalid record");
2049 Type *OpTy = getTypeByID(Record[0]);
2051 return Error("Invalid record");
2052 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2053 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2055 if (OpTy->isFPOrFPVectorTy())
2056 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2058 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2061 // This maintains backward compatibility, pre-asm dialect keywords.
2062 // FIXME: Remove with the 4.0 release.
2063 case bitc::CST_CODE_INLINEASM_OLD: {
2064 if (Record.size() < 2)
2065 return Error("Invalid record");
2066 std::string AsmStr, ConstrStr;
2067 bool HasSideEffects = Record[0] & 1;
2068 bool IsAlignStack = Record[0] >> 1;
2069 unsigned AsmStrSize = Record[1];
2070 if (2+AsmStrSize >= Record.size())
2071 return Error("Invalid record");
2072 unsigned ConstStrSize = Record[2+AsmStrSize];
2073 if (3+AsmStrSize+ConstStrSize > Record.size())
2074 return Error("Invalid record");
2076 for (unsigned i = 0; i != AsmStrSize; ++i)
2077 AsmStr += (char)Record[2+i];
2078 for (unsigned i = 0; i != ConstStrSize; ++i)
2079 ConstrStr += (char)Record[3+AsmStrSize+i];
2080 PointerType *PTy = cast<PointerType>(CurTy);
2081 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2082 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2085 // This version adds support for the asm dialect keywords (e.g.,
2087 case bitc::CST_CODE_INLINEASM: {
2088 if (Record.size() < 2)
2089 return Error("Invalid record");
2090 std::string AsmStr, ConstrStr;
2091 bool HasSideEffects = Record[0] & 1;
2092 bool IsAlignStack = (Record[0] >> 1) & 1;
2093 unsigned AsmDialect = Record[0] >> 2;
2094 unsigned AsmStrSize = Record[1];
2095 if (2+AsmStrSize >= Record.size())
2096 return Error("Invalid record");
2097 unsigned ConstStrSize = Record[2+AsmStrSize];
2098 if (3+AsmStrSize+ConstStrSize > Record.size())
2099 return Error("Invalid record");
2101 for (unsigned i = 0; i != AsmStrSize; ++i)
2102 AsmStr += (char)Record[2+i];
2103 for (unsigned i = 0; i != ConstStrSize; ++i)
2104 ConstrStr += (char)Record[3+AsmStrSize+i];
2105 PointerType *PTy = cast<PointerType>(CurTy);
2106 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2107 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2108 InlineAsm::AsmDialect(AsmDialect));
2111 case bitc::CST_CODE_BLOCKADDRESS:{
2112 if (Record.size() < 3)
2113 return Error("Invalid record");
2114 Type *FnTy = getTypeByID(Record[0]);
2116 return Error("Invalid record");
2118 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2120 return Error("Invalid record");
2122 // Don't let Fn get dematerialized.
2123 BlockAddressesTaken.insert(Fn);
2125 // If the function is already parsed we can insert the block address right
2128 unsigned BBID = Record[2];
2130 // Invalid reference to entry block.
2131 return Error("Invalid ID");
2133 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2134 for (size_t I = 0, E = BBID; I != E; ++I) {
2136 return Error("Invalid ID");
2141 // Otherwise insert a placeholder and remember it so it can be inserted
2142 // when the function is parsed.
2143 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2145 BasicBlockFwdRefQueue.push_back(Fn);
2146 if (FwdBBs.size() < BBID + 1)
2147 FwdBBs.resize(BBID + 1);
2149 FwdBBs[BBID] = BasicBlock::Create(Context);
2152 V = BlockAddress::get(Fn, BB);
2157 ValueList.AssignValue(V, NextCstNo);
2162 std::error_code BitcodeReader::ParseUseLists() {
2163 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2164 return Error("Invalid record");
2166 // Read all the records.
2167 SmallVector<uint64_t, 64> Record;
2169 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2171 switch (Entry.Kind) {
2172 case BitstreamEntry::SubBlock: // Handled for us already.
2173 case BitstreamEntry::Error:
2174 return Error("Malformed block");
2175 case BitstreamEntry::EndBlock:
2176 return std::error_code();
2177 case BitstreamEntry::Record:
2178 // The interesting case.
2182 // Read a use list record.
2185 switch (Stream.readRecord(Entry.ID, Record)) {
2186 default: // Default behavior: unknown type.
2188 case bitc::USELIST_CODE_BB:
2191 case bitc::USELIST_CODE_DEFAULT: {
2192 unsigned RecordLength = Record.size();
2193 if (RecordLength < 3)
2194 // Records should have at least an ID and two indexes.
2195 return Error("Invalid record");
2196 unsigned ID = Record.back();
2201 assert(ID < FunctionBBs.size() && "Basic block not found");
2202 V = FunctionBBs[ID];
2205 unsigned NumUses = 0;
2206 SmallDenseMap<const Use *, unsigned, 16> Order;
2207 for (const Use &U : V->uses()) {
2208 if (++NumUses > Record.size())
2210 Order[&U] = Record[NumUses - 1];
2212 if (Order.size() != Record.size() || NumUses > Record.size())
2213 // Mismatches can happen if the functions are being materialized lazily
2214 // (out-of-order), or a value has been upgraded.
2217 V->sortUseList([&](const Use &L, const Use &R) {
2218 return Order.lookup(&L) < Order.lookup(&R);
2226 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2227 /// remember where it is and then skip it. This lets us lazily deserialize the
2229 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2230 // Get the function we are talking about.
2231 if (FunctionsWithBodies.empty())
2232 return Error("Insufficient function protos");
2234 Function *Fn = FunctionsWithBodies.back();
2235 FunctionsWithBodies.pop_back();
2237 // Save the current stream state.
2238 uint64_t CurBit = Stream.GetCurrentBitNo();
2239 DeferredFunctionInfo[Fn] = CurBit;
2241 // Skip over the function block for now.
2242 if (Stream.SkipBlock())
2243 return Error("Invalid record");
2244 return std::error_code();
2247 std::error_code BitcodeReader::GlobalCleanup() {
2248 // Patch the initializers for globals and aliases up.
2249 ResolveGlobalAndAliasInits();
2250 if (!GlobalInits.empty() || !AliasInits.empty())
2251 return Error("Malformed global initializer set");
2253 // Look for intrinsic functions which need to be upgraded at some point
2254 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2257 if (UpgradeIntrinsicFunction(FI, NewFn))
2258 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2261 // Look for global variables which need to be renamed.
2262 for (Module::global_iterator
2263 GI = TheModule->global_begin(), GE = TheModule->global_end();
2265 GlobalVariable *GV = GI++;
2266 UpgradeGlobalVariable(GV);
2269 // Force deallocation of memory for these vectors to favor the client that
2270 // want lazy deserialization.
2271 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2272 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2273 return std::error_code();
2276 std::error_code BitcodeReader::ParseModule(bool Resume) {
2278 Stream.JumpToBit(NextUnreadBit);
2279 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2280 return Error("Invalid record");
2282 SmallVector<uint64_t, 64> Record;
2283 std::vector<std::string> SectionTable;
2284 std::vector<std::string> GCTable;
2286 // Read all the records for this module.
2288 BitstreamEntry Entry = Stream.advance();
2290 switch (Entry.Kind) {
2291 case BitstreamEntry::Error:
2292 return Error("Malformed block");
2293 case BitstreamEntry::EndBlock:
2294 return GlobalCleanup();
2296 case BitstreamEntry::SubBlock:
2298 default: // Skip unknown content.
2299 if (Stream.SkipBlock())
2300 return Error("Invalid record");
2302 case bitc::BLOCKINFO_BLOCK_ID:
2303 if (Stream.ReadBlockInfoBlock())
2304 return Error("Malformed block");
2306 case bitc::PARAMATTR_BLOCK_ID:
2307 if (std::error_code EC = ParseAttributeBlock())
2310 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2311 if (std::error_code EC = ParseAttributeGroupBlock())
2314 case bitc::TYPE_BLOCK_ID_NEW:
2315 if (std::error_code EC = ParseTypeTable())
2318 case bitc::VALUE_SYMTAB_BLOCK_ID:
2319 if (std::error_code EC = ParseValueSymbolTable())
2321 SeenValueSymbolTable = true;
2323 case bitc::CONSTANTS_BLOCK_ID:
2324 if (std::error_code EC = ParseConstants())
2326 if (std::error_code EC = ResolveGlobalAndAliasInits())
2329 case bitc::METADATA_BLOCK_ID:
2330 if (std::error_code EC = ParseMetadata())
2333 case bitc::FUNCTION_BLOCK_ID:
2334 // If this is the first function body we've seen, reverse the
2335 // FunctionsWithBodies list.
2336 if (!SeenFirstFunctionBody) {
2337 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2338 if (std::error_code EC = GlobalCleanup())
2340 SeenFirstFunctionBody = true;
2343 if (std::error_code EC = RememberAndSkipFunctionBody())
2345 // For streaming bitcode, suspend parsing when we reach the function
2346 // bodies. Subsequent materialization calls will resume it when
2347 // necessary. For streaming, the function bodies must be at the end of
2348 // the bitcode. If the bitcode file is old, the symbol table will be
2349 // at the end instead and will not have been seen yet. In this case,
2350 // just finish the parse now.
2351 if (LazyStreamer && SeenValueSymbolTable) {
2352 NextUnreadBit = Stream.GetCurrentBitNo();
2353 return std::error_code();
2356 case bitc::USELIST_BLOCK_ID:
2357 if (std::error_code EC = ParseUseLists())
2363 case BitstreamEntry::Record:
2364 // The interesting case.
2370 switch (Stream.readRecord(Entry.ID, Record)) {
2371 default: break; // Default behavior, ignore unknown content.
2372 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2373 if (Record.size() < 1)
2374 return Error("Invalid record");
2375 // Only version #0 and #1 are supported so far.
2376 unsigned module_version = Record[0];
2377 switch (module_version) {
2379 return Error("Invalid value");
2381 UseRelativeIDs = false;
2384 UseRelativeIDs = true;
2389 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2391 if (ConvertToString(Record, 0, S))
2392 return Error("Invalid record");
2393 TheModule->setTargetTriple(S);
2396 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2398 if (ConvertToString(Record, 0, S))
2399 return Error("Invalid record");
2400 TheModule->setDataLayout(S);
2403 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2405 if (ConvertToString(Record, 0, S))
2406 return Error("Invalid record");
2407 TheModule->setModuleInlineAsm(S);
2410 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2411 // FIXME: Remove in 4.0.
2413 if (ConvertToString(Record, 0, S))
2414 return Error("Invalid record");
2418 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2420 if (ConvertToString(Record, 0, S))
2421 return Error("Invalid record");
2422 SectionTable.push_back(S);
2425 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2427 if (ConvertToString(Record, 0, S))
2428 return Error("Invalid record");
2429 GCTable.push_back(S);
2432 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2433 if (Record.size() < 2)
2434 return Error("Invalid record");
2435 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2436 unsigned ComdatNameSize = Record[1];
2437 std::string ComdatName;
2438 ComdatName.reserve(ComdatNameSize);
2439 for (unsigned i = 0; i != ComdatNameSize; ++i)
2440 ComdatName += (char)Record[2 + i];
2441 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2442 C->setSelectionKind(SK);
2443 ComdatList.push_back(C);
2446 // GLOBALVAR: [pointer type, isconst, initid,
2447 // linkage, alignment, section, visibility, threadlocal,
2448 // unnamed_addr, externally_initialized, dllstorageclass,
2450 case bitc::MODULE_CODE_GLOBALVAR: {
2451 if (Record.size() < 6)
2452 return Error("Invalid record");
2453 Type *Ty = getTypeByID(Record[0]);
2455 return Error("Invalid record");
2456 if (!Ty->isPointerTy())
2457 return Error("Invalid type for value");
2458 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2459 Ty = cast<PointerType>(Ty)->getElementType();
2461 bool isConstant = Record[1];
2462 uint64_t RawLinkage = Record[3];
2463 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2464 unsigned Alignment = (1 << Record[4]) >> 1;
2465 std::string Section;
2467 if (Record[5]-1 >= SectionTable.size())
2468 return Error("Invalid ID");
2469 Section = SectionTable[Record[5]-1];
2471 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2472 // Local linkage must have default visibility.
2473 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2474 // FIXME: Change to an error if non-default in 4.0.
2475 Visibility = GetDecodedVisibility(Record[6]);
2477 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2478 if (Record.size() > 7)
2479 TLM = GetDecodedThreadLocalMode(Record[7]);
2481 bool UnnamedAddr = false;
2482 if (Record.size() > 8)
2483 UnnamedAddr = Record[8];
2485 bool ExternallyInitialized = false;
2486 if (Record.size() > 9)
2487 ExternallyInitialized = Record[9];
2489 GlobalVariable *NewGV =
2490 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2491 TLM, AddressSpace, ExternallyInitialized);
2492 NewGV->setAlignment(Alignment);
2493 if (!Section.empty())
2494 NewGV->setSection(Section);
2495 NewGV->setVisibility(Visibility);
2496 NewGV->setUnnamedAddr(UnnamedAddr);
2498 if (Record.size() > 10)
2499 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2501 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2503 ValueList.push_back(NewGV);
2505 // Remember which value to use for the global initializer.
2506 if (unsigned InitID = Record[2])
2507 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2509 if (Record.size() > 11) {
2510 if (unsigned ComdatID = Record[11]) {
2511 assert(ComdatID <= ComdatList.size());
2512 NewGV->setComdat(ComdatList[ComdatID - 1]);
2514 } else if (hasImplicitComdat(RawLinkage)) {
2515 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2519 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2520 // alignment, section, visibility, gc, unnamed_addr,
2521 // prologuedata, dllstorageclass, comdat, prefixdata]
2522 case bitc::MODULE_CODE_FUNCTION: {
2523 if (Record.size() < 8)
2524 return Error("Invalid record");
2525 Type *Ty = getTypeByID(Record[0]);
2527 return Error("Invalid record");
2528 if (!Ty->isPointerTy())
2529 return Error("Invalid type for value");
2531 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2533 return Error("Invalid type for value");
2535 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2538 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2539 bool isProto = Record[2];
2540 uint64_t RawLinkage = Record[3];
2541 Func->setLinkage(getDecodedLinkage(RawLinkage));
2542 Func->setAttributes(getAttributes(Record[4]));
2544 Func->setAlignment((1 << Record[5]) >> 1);
2546 if (Record[6]-1 >= SectionTable.size())
2547 return Error("Invalid ID");
2548 Func->setSection(SectionTable[Record[6]-1]);
2550 // Local linkage must have default visibility.
2551 if (!Func->hasLocalLinkage())
2552 // FIXME: Change to an error if non-default in 4.0.
2553 Func->setVisibility(GetDecodedVisibility(Record[7]));
2554 if (Record.size() > 8 && Record[8]) {
2555 if (Record[8]-1 > GCTable.size())
2556 return Error("Invalid ID");
2557 Func->setGC(GCTable[Record[8]-1].c_str());
2559 bool UnnamedAddr = false;
2560 if (Record.size() > 9)
2561 UnnamedAddr = Record[9];
2562 Func->setUnnamedAddr(UnnamedAddr);
2563 if (Record.size() > 10 && Record[10] != 0)
2564 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2566 if (Record.size() > 11)
2567 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2569 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2571 if (Record.size() > 12) {
2572 if (unsigned ComdatID = Record[12]) {
2573 assert(ComdatID <= ComdatList.size());
2574 Func->setComdat(ComdatList[ComdatID - 1]);
2576 } else if (hasImplicitComdat(RawLinkage)) {
2577 Func->setComdat(reinterpret_cast<Comdat *>(1));
2580 if (Record.size() > 13 && Record[13] != 0)
2581 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2583 ValueList.push_back(Func);
2585 // If this is a function with a body, remember the prototype we are
2586 // creating now, so that we can match up the body with them later.
2588 Func->setIsMaterializable(true);
2589 FunctionsWithBodies.push_back(Func);
2591 DeferredFunctionInfo[Func] = 0;
2595 // ALIAS: [alias type, aliasee val#, linkage]
2596 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2597 case bitc::MODULE_CODE_ALIAS: {
2598 if (Record.size() < 3)
2599 return Error("Invalid record");
2600 Type *Ty = getTypeByID(Record[0]);
2602 return Error("Invalid record");
2603 auto *PTy = dyn_cast<PointerType>(Ty);
2605 return Error("Invalid type for value");
2608 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2609 getDecodedLinkage(Record[2]), "", TheModule);
2610 // Old bitcode files didn't have visibility field.
2611 // Local linkage must have default visibility.
2612 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2613 // FIXME: Change to an error if non-default in 4.0.
2614 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2615 if (Record.size() > 4)
2616 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2618 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2619 if (Record.size() > 5)
2620 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2621 if (Record.size() > 6)
2622 NewGA->setUnnamedAddr(Record[6]);
2623 ValueList.push_back(NewGA);
2624 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2627 /// MODULE_CODE_PURGEVALS: [numvals]
2628 case bitc::MODULE_CODE_PURGEVALS:
2629 // Trim down the value list to the specified size.
2630 if (Record.size() < 1 || Record[0] > ValueList.size())
2631 return Error("Invalid record");
2632 ValueList.shrinkTo(Record[0]);
2639 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2640 TheModule = nullptr;
2642 if (std::error_code EC = InitStream())
2645 // Sniff for the signature.
2646 if (Stream.Read(8) != 'B' ||
2647 Stream.Read(8) != 'C' ||
2648 Stream.Read(4) != 0x0 ||
2649 Stream.Read(4) != 0xC ||
2650 Stream.Read(4) != 0xE ||
2651 Stream.Read(4) != 0xD)
2652 return Error("Invalid bitcode signature");
2654 // We expect a number of well-defined blocks, though we don't necessarily
2655 // need to understand them all.
2657 if (Stream.AtEndOfStream())
2658 return std::error_code();
2660 BitstreamEntry Entry =
2661 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2663 switch (Entry.Kind) {
2664 case BitstreamEntry::Error:
2665 return Error("Malformed block");
2666 case BitstreamEntry::EndBlock:
2667 return std::error_code();
2669 case BitstreamEntry::SubBlock:
2671 case bitc::BLOCKINFO_BLOCK_ID:
2672 if (Stream.ReadBlockInfoBlock())
2673 return Error("Malformed block");
2675 case bitc::MODULE_BLOCK_ID:
2676 // Reject multiple MODULE_BLOCK's in a single bitstream.
2678 return Error("Invalid multiple blocks");
2680 if (std::error_code EC = ParseModule(false))
2683 return std::error_code();
2686 if (Stream.SkipBlock())
2687 return Error("Invalid record");
2691 case BitstreamEntry::Record:
2692 // There should be no records in the top-level of blocks.
2694 // The ranlib in Xcode 4 will align archive members by appending newlines
2695 // to the end of them. If this file size is a multiple of 4 but not 8, we
2696 // have to read and ignore these final 4 bytes :-(
2697 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2698 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2699 Stream.AtEndOfStream())
2700 return std::error_code();
2702 return Error("Invalid record");
2707 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2708 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2709 return Error("Invalid record");
2711 SmallVector<uint64_t, 64> Record;
2714 // Read all the records for this module.
2716 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2718 switch (Entry.Kind) {
2719 case BitstreamEntry::SubBlock: // Handled for us already.
2720 case BitstreamEntry::Error:
2721 return Error("Malformed block");
2722 case BitstreamEntry::EndBlock:
2724 case BitstreamEntry::Record:
2725 // The interesting case.
2730 switch (Stream.readRecord(Entry.ID, Record)) {
2731 default: break; // Default behavior, ignore unknown content.
2732 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2734 if (ConvertToString(Record, 0, S))
2735 return Error("Invalid record");
2742 llvm_unreachable("Exit infinite loop");
2745 ErrorOr<std::string> BitcodeReader::parseTriple() {
2746 if (std::error_code EC = InitStream())
2749 // Sniff for the signature.
2750 if (Stream.Read(8) != 'B' ||
2751 Stream.Read(8) != 'C' ||
2752 Stream.Read(4) != 0x0 ||
2753 Stream.Read(4) != 0xC ||
2754 Stream.Read(4) != 0xE ||
2755 Stream.Read(4) != 0xD)
2756 return Error("Invalid bitcode signature");
2758 // We expect a number of well-defined blocks, though we don't necessarily
2759 // need to understand them all.
2761 BitstreamEntry Entry = Stream.advance();
2763 switch (Entry.Kind) {
2764 case BitstreamEntry::Error:
2765 return Error("Malformed block");
2766 case BitstreamEntry::EndBlock:
2767 return std::error_code();
2769 case BitstreamEntry::SubBlock:
2770 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2771 return parseModuleTriple();
2773 // Ignore other sub-blocks.
2774 if (Stream.SkipBlock())
2775 return Error("Malformed block");
2778 case BitstreamEntry::Record:
2779 Stream.skipRecord(Entry.ID);
2785 /// ParseMetadataAttachment - Parse metadata attachments.
2786 std::error_code BitcodeReader::ParseMetadataAttachment() {
2787 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2788 return Error("Invalid record");
2790 SmallVector<uint64_t, 64> Record;
2792 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2794 switch (Entry.Kind) {
2795 case BitstreamEntry::SubBlock: // Handled for us already.
2796 case BitstreamEntry::Error:
2797 return Error("Malformed block");
2798 case BitstreamEntry::EndBlock:
2799 return std::error_code();
2800 case BitstreamEntry::Record:
2801 // The interesting case.
2805 // Read a metadata attachment record.
2807 switch (Stream.readRecord(Entry.ID, Record)) {
2808 default: // Default behavior: ignore.
2810 case bitc::METADATA_ATTACHMENT: {
2811 unsigned RecordLength = Record.size();
2812 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2813 return Error("Invalid record");
2814 Instruction *Inst = InstructionList[Record[0]];
2815 for (unsigned i = 1; i != RecordLength; i = i+2) {
2816 unsigned Kind = Record[i];
2817 DenseMap<unsigned, unsigned>::iterator I =
2818 MDKindMap.find(Kind);
2819 if (I == MDKindMap.end())
2820 return Error("Invalid ID");
2821 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2822 if (isa<LocalAsMetadata>(Node))
2823 // Drop the attachment. This used to be legal, but there's no
2826 Inst->setMetadata(I->second, cast<MDNode>(Node));
2827 if (I->second == LLVMContext::MD_tbaa)
2828 InstsWithTBAATag.push_back(Inst);
2836 /// ParseFunctionBody - Lazily parse the specified function body block.
2837 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2838 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2839 return Error("Invalid record");
2841 InstructionList.clear();
2842 unsigned ModuleValueListSize = ValueList.size();
2843 unsigned ModuleMDValueListSize = MDValueList.size();
2845 // Add all the function arguments to the value table.
2846 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2847 ValueList.push_back(I);
2849 unsigned NextValueNo = ValueList.size();
2850 BasicBlock *CurBB = nullptr;
2851 unsigned CurBBNo = 0;
2854 auto getLastInstruction = [&]() -> Instruction * {
2855 if (CurBB && !CurBB->empty())
2856 return &CurBB->back();
2857 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2858 !FunctionBBs[CurBBNo - 1]->empty())
2859 return &FunctionBBs[CurBBNo - 1]->back();
2863 // Read all the records.
2864 SmallVector<uint64_t, 64> Record;
2866 BitstreamEntry Entry = Stream.advance();
2868 switch (Entry.Kind) {
2869 case BitstreamEntry::Error:
2870 return Error("Malformed block");
2871 case BitstreamEntry::EndBlock:
2872 goto OutOfRecordLoop;
2874 case BitstreamEntry::SubBlock:
2876 default: // Skip unknown content.
2877 if (Stream.SkipBlock())
2878 return Error("Invalid record");
2880 case bitc::CONSTANTS_BLOCK_ID:
2881 if (std::error_code EC = ParseConstants())
2883 NextValueNo = ValueList.size();
2885 case bitc::VALUE_SYMTAB_BLOCK_ID:
2886 if (std::error_code EC = ParseValueSymbolTable())
2889 case bitc::METADATA_ATTACHMENT_ID:
2890 if (std::error_code EC = ParseMetadataAttachment())
2893 case bitc::METADATA_BLOCK_ID:
2894 if (std::error_code EC = ParseMetadata())
2897 case bitc::USELIST_BLOCK_ID:
2898 if (std::error_code EC = ParseUseLists())
2904 case BitstreamEntry::Record:
2905 // The interesting case.
2911 Instruction *I = nullptr;
2912 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2914 default: // Default behavior: reject
2915 return Error("Invalid value");
2916 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2917 if (Record.size() < 1 || Record[0] == 0)
2918 return Error("Invalid record");
2919 // Create all the basic blocks for the function.
2920 FunctionBBs.resize(Record[0]);
2922 // See if anything took the address of blocks in this function.
2923 auto BBFRI = BasicBlockFwdRefs.find(F);
2924 if (BBFRI == BasicBlockFwdRefs.end()) {
2925 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2926 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2928 auto &BBRefs = BBFRI->second;
2929 // Check for invalid basic block references.
2930 if (BBRefs.size() > FunctionBBs.size())
2931 return Error("Invalid ID");
2932 assert(!BBRefs.empty() && "Unexpected empty array");
2933 assert(!BBRefs.front() && "Invalid reference to entry block");
2934 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2936 if (I < RE && BBRefs[I]) {
2937 BBRefs[I]->insertInto(F);
2938 FunctionBBs[I] = BBRefs[I];
2940 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2943 // Erase from the table.
2944 BasicBlockFwdRefs.erase(BBFRI);
2947 CurBB = FunctionBBs[0];
2951 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2952 // This record indicates that the last instruction is at the same
2953 // location as the previous instruction with a location.
2954 I = getLastInstruction();
2957 return Error("Invalid record");
2958 I->setDebugLoc(LastLoc);
2962 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2963 I = getLastInstruction();
2964 if (!I || Record.size() < 4)
2965 return Error("Invalid record");
2967 unsigned Line = Record[0], Col = Record[1];
2968 unsigned ScopeID = Record[2], IAID = Record[3];
2970 MDNode *Scope = nullptr, *IA = nullptr;
2971 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2972 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2973 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2974 I->setDebugLoc(LastLoc);
2979 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2982 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2983 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2984 OpNum+1 > Record.size())
2985 return Error("Invalid record");
2987 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2989 return Error("Invalid record");
2990 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2991 InstructionList.push_back(I);
2992 if (OpNum < Record.size()) {
2993 if (Opc == Instruction::Add ||
2994 Opc == Instruction::Sub ||
2995 Opc == Instruction::Mul ||
2996 Opc == Instruction::Shl) {
2997 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2998 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2999 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3000 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3001 } else if (Opc == Instruction::SDiv ||
3002 Opc == Instruction::UDiv ||
3003 Opc == Instruction::LShr ||
3004 Opc == Instruction::AShr) {
3005 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3006 cast<BinaryOperator>(I)->setIsExact(true);
3007 } else if (isa<FPMathOperator>(I)) {
3009 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3010 FMF.setUnsafeAlgebra();
3011 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3013 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3015 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3016 FMF.setNoSignedZeros();
3017 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3018 FMF.setAllowReciprocal();
3020 I->setFastMathFlags(FMF);
3026 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3029 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3030 OpNum+2 != Record.size())
3031 return Error("Invalid record");
3033 Type *ResTy = getTypeByID(Record[OpNum]);
3034 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3035 if (Opc == -1 || !ResTy)
3036 return Error("Invalid record");
3037 Instruction *Temp = nullptr;
3038 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3040 InstructionList.push_back(Temp);
3041 CurBB->getInstList().push_back(Temp);
3044 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3046 InstructionList.push_back(I);
3049 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
3050 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
3053 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3054 return Error("Invalid record");
3056 SmallVector<Value*, 16> GEPIdx;
3057 while (OpNum != Record.size()) {
3059 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3060 return Error("Invalid record");
3061 GEPIdx.push_back(Op);
3064 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
3065 InstructionList.push_back(I);
3066 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
3067 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3071 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3072 // EXTRACTVAL: [opty, opval, n x indices]
3075 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3076 return Error("Invalid record");
3078 SmallVector<unsigned, 4> EXTRACTVALIdx;
3079 Type *CurTy = Agg->getType();
3080 for (unsigned RecSize = Record.size();
3081 OpNum != RecSize; ++OpNum) {
3082 bool IsArray = CurTy->isArrayTy();
3083 bool IsStruct = CurTy->isStructTy();
3084 uint64_t Index = Record[OpNum];
3086 if (!IsStruct && !IsArray)
3087 return Error("EXTRACTVAL: Invalid type");
3088 if ((unsigned)Index != Index)
3089 return Error("Invalid value");
3090 if (IsStruct && Index >= CurTy->subtypes().size())
3091 return Error("EXTRACTVAL: Invalid struct index");
3092 if (IsArray && Index >= CurTy->getArrayNumElements())
3093 return Error("EXTRACTVAL: Invalid array index");
3094 EXTRACTVALIdx.push_back((unsigned)Index);
3097 CurTy = CurTy->subtypes()[Index];
3099 CurTy = CurTy->subtypes()[0];
3102 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3103 InstructionList.push_back(I);
3107 case bitc::FUNC_CODE_INST_INSERTVAL: {
3108 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3111 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3112 return Error("Invalid record");
3114 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3115 return Error("Invalid record");
3117 SmallVector<unsigned, 4> INSERTVALIdx;
3118 Type *CurTy = Agg->getType();
3119 for (unsigned RecSize = Record.size();
3120 OpNum != RecSize; ++OpNum) {
3121 bool IsArray = CurTy->isArrayTy();
3122 bool IsStruct = CurTy->isStructTy();
3123 uint64_t Index = Record[OpNum];
3125 if (!IsStruct && !IsArray)
3126 return Error("INSERTVAL: Invalid type");
3127 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3128 return Error("Invalid type");
3129 if ((unsigned)Index != Index)
3130 return Error("Invalid value");
3131 if (IsStruct && Index >= CurTy->subtypes().size())
3132 return Error("INSERTVAL: Invalid struct index");
3133 if (IsArray && Index >= CurTy->getArrayNumElements())
3134 return Error("INSERTVAL: Invalid array index");
3136 INSERTVALIdx.push_back((unsigned)Index);
3138 CurTy = CurTy->subtypes()[Index];
3140 CurTy = CurTy->subtypes()[0];
3143 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3144 InstructionList.push_back(I);
3148 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3149 // obsolete form of select
3150 // handles select i1 ... in old bitcode
3152 Value *TrueVal, *FalseVal, *Cond;
3153 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3154 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3155 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3156 return Error("Invalid record");
3158 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3159 InstructionList.push_back(I);
3163 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3164 // new form of select
3165 // handles select i1 or select [N x i1]
3167 Value *TrueVal, *FalseVal, *Cond;
3168 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3169 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3170 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3171 return Error("Invalid record");
3173 // select condition can be either i1 or [N x i1]
3174 if (VectorType* vector_type =
3175 dyn_cast<VectorType>(Cond->getType())) {
3177 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3178 return Error("Invalid type for value");
3181 if (Cond->getType() != Type::getInt1Ty(Context))
3182 return Error("Invalid type for value");
3185 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3186 InstructionList.push_back(I);
3190 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3193 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3194 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3195 return Error("Invalid record");
3196 I = ExtractElementInst::Create(Vec, Idx);
3197 InstructionList.push_back(I);
3201 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3203 Value *Vec, *Elt, *Idx;
3204 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3205 popValue(Record, OpNum, NextValueNo,
3206 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3207 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3208 return Error("Invalid record");
3209 I = InsertElementInst::Create(Vec, Elt, Idx);
3210 InstructionList.push_back(I);
3214 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3216 Value *Vec1, *Vec2, *Mask;
3217 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3218 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3219 return Error("Invalid record");
3221 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3222 return Error("Invalid record");
3223 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3224 InstructionList.push_back(I);
3228 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3229 // Old form of ICmp/FCmp returning bool
3230 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3231 // both legal on vectors but had different behaviour.
3232 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3233 // FCmp/ICmp returning bool or vector of bool
3237 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3238 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3239 OpNum+1 != Record.size())
3240 return Error("Invalid record");
3242 if (LHS->getType()->isFPOrFPVectorTy())
3243 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3245 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3246 InstructionList.push_back(I);
3250 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3252 unsigned Size = Record.size();
3254 I = ReturnInst::Create(Context);
3255 InstructionList.push_back(I);
3260 Value *Op = nullptr;
3261 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3262 return Error("Invalid record");
3263 if (OpNum != Record.size())
3264 return Error("Invalid record");
3266 I = ReturnInst::Create(Context, Op);
3267 InstructionList.push_back(I);
3270 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3271 if (Record.size() != 1 && Record.size() != 3)
3272 return Error("Invalid record");
3273 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3275 return Error("Invalid record");
3277 if (Record.size() == 1) {
3278 I = BranchInst::Create(TrueDest);
3279 InstructionList.push_back(I);
3282 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3283 Value *Cond = getValue(Record, 2, NextValueNo,
3284 Type::getInt1Ty(Context));
3285 if (!FalseDest || !Cond)
3286 return Error("Invalid record");
3287 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3288 InstructionList.push_back(I);
3292 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3294 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3295 // "New" SwitchInst format with case ranges. The changes to write this
3296 // format were reverted but we still recognize bitcode that uses it.
3297 // Hopefully someday we will have support for case ranges and can use
3298 // this format again.
3300 Type *OpTy = getTypeByID(Record[1]);
3301 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3303 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3304 BasicBlock *Default = getBasicBlock(Record[3]);
3305 if (!OpTy || !Cond || !Default)
3306 return Error("Invalid record");
3308 unsigned NumCases = Record[4];
3310 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3311 InstructionList.push_back(SI);
3313 unsigned CurIdx = 5;
3314 for (unsigned i = 0; i != NumCases; ++i) {
3315 SmallVector<ConstantInt*, 1> CaseVals;
3316 unsigned NumItems = Record[CurIdx++];
3317 for (unsigned ci = 0; ci != NumItems; ++ci) {
3318 bool isSingleNumber = Record[CurIdx++];
3321 unsigned ActiveWords = 1;
3322 if (ValueBitWidth > 64)
3323 ActiveWords = Record[CurIdx++];
3324 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3326 CurIdx += ActiveWords;
3328 if (!isSingleNumber) {
3330 if (ValueBitWidth > 64)
3331 ActiveWords = Record[CurIdx++];
3333 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3335 CurIdx += ActiveWords;
3337 // FIXME: It is not clear whether values in the range should be
3338 // compared as signed or unsigned values. The partially
3339 // implemented changes that used this format in the past used
3340 // unsigned comparisons.
3341 for ( ; Low.ule(High); ++Low)
3342 CaseVals.push_back(ConstantInt::get(Context, Low));
3344 CaseVals.push_back(ConstantInt::get(Context, Low));
3346 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3347 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3348 cve = CaseVals.end(); cvi != cve; ++cvi)
3349 SI->addCase(*cvi, DestBB);
3355 // Old SwitchInst format without case ranges.
3357 if (Record.size() < 3 || (Record.size() & 1) == 0)
3358 return Error("Invalid record");
3359 Type *OpTy = getTypeByID(Record[0]);
3360 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3361 BasicBlock *Default = getBasicBlock(Record[2]);
3362 if (!OpTy || !Cond || !Default)
3363 return Error("Invalid record");
3364 unsigned NumCases = (Record.size()-3)/2;
3365 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3366 InstructionList.push_back(SI);
3367 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3368 ConstantInt *CaseVal =
3369 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3370 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3371 if (!CaseVal || !DestBB) {
3373 return Error("Invalid record");
3375 SI->addCase(CaseVal, DestBB);
3380 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3381 if (Record.size() < 2)
3382 return Error("Invalid record");
3383 Type *OpTy = getTypeByID(Record[0]);
3384 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3385 if (!OpTy || !Address)
3386 return Error("Invalid record");
3387 unsigned NumDests = Record.size()-2;
3388 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3389 InstructionList.push_back(IBI);
3390 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3391 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3392 IBI->addDestination(DestBB);
3395 return Error("Invalid record");
3402 case bitc::FUNC_CODE_INST_INVOKE: {
3403 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3404 if (Record.size() < 4)
3405 return Error("Invalid record");
3406 AttributeSet PAL = getAttributes(Record[0]);
3407 unsigned CCInfo = Record[1];
3408 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3409 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3413 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3414 return Error("Invalid record");
3416 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3417 FunctionType *FTy = !CalleeTy ? nullptr :
3418 dyn_cast<FunctionType>(CalleeTy->getElementType());
3420 // Check that the right number of fixed parameters are here.
3421 if (!FTy || !NormalBB || !UnwindBB ||
3422 Record.size() < OpNum+FTy->getNumParams())
3423 return Error("Invalid record");
3425 SmallVector<Value*, 16> Ops;
3426 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3427 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3428 FTy->getParamType(i)));
3430 return Error("Invalid record");
3433 if (!FTy->isVarArg()) {
3434 if (Record.size() != OpNum)
3435 return Error("Invalid record");
3437 // Read type/value pairs for varargs params.
3438 while (OpNum != Record.size()) {
3440 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3441 return Error("Invalid record");
3446 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3447 InstructionList.push_back(I);
3448 cast<InvokeInst>(I)->setCallingConv(
3449 static_cast<CallingConv::ID>(CCInfo));
3450 cast<InvokeInst>(I)->setAttributes(PAL);
3453 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3455 Value *Val = nullptr;
3456 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3457 return Error("Invalid record");
3458 I = ResumeInst::Create(Val);
3459 InstructionList.push_back(I);
3462 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3463 I = new UnreachableInst(Context);
3464 InstructionList.push_back(I);
3466 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3467 if (Record.size() < 1 || ((Record.size()-1)&1))
3468 return Error("Invalid record");
3469 Type *Ty = getTypeByID(Record[0]);
3471 return Error("Invalid record");
3473 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3474 InstructionList.push_back(PN);
3476 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3478 // With the new function encoding, it is possible that operands have
3479 // negative IDs (for forward references). Use a signed VBR
3480 // representation to keep the encoding small.
3482 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3484 V = getValue(Record, 1+i, NextValueNo, Ty);
3485 BasicBlock *BB = getBasicBlock(Record[2+i]);
3487 return Error("Invalid record");
3488 PN->addIncoming(V, BB);
3494 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3495 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3497 if (Record.size() < 4)
3498 return Error("Invalid record");
3499 Type *Ty = getTypeByID(Record[Idx++]);
3501 return Error("Invalid record");
3502 Value *PersFn = nullptr;
3503 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3504 return Error("Invalid record");
3506 bool IsCleanup = !!Record[Idx++];
3507 unsigned NumClauses = Record[Idx++];
3508 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3509 LP->setCleanup(IsCleanup);
3510 for (unsigned J = 0; J != NumClauses; ++J) {
3511 LandingPadInst::ClauseType CT =
3512 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3515 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3517 return Error("Invalid record");
3520 assert((CT != LandingPadInst::Catch ||
3521 !isa<ArrayType>(Val->getType())) &&
3522 "Catch clause has a invalid type!");
3523 assert((CT != LandingPadInst::Filter ||
3524 isa<ArrayType>(Val->getType())) &&
3525 "Filter clause has invalid type!");
3526 LP->addClause(cast<Constant>(Val));
3530 InstructionList.push_back(I);
3534 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3535 if (Record.size() != 4)
3536 return Error("Invalid record");
3538 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3539 Type *OpTy = getTypeByID(Record[1]);
3540 Value *Size = getFnValueByID(Record[2], OpTy);
3541 unsigned AlignRecord = Record[3];
3542 bool InAlloca = AlignRecord & (1 << 5);
3543 unsigned Align = AlignRecord & ((1 << 5) - 1);
3545 return Error("Invalid record");
3546 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3547 AI->setUsedWithInAlloca(InAlloca);
3549 InstructionList.push_back(I);
3552 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3555 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3556 OpNum+2 != Record.size())
3557 return Error("Invalid record");
3559 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3560 InstructionList.push_back(I);
3563 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3564 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3567 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3568 OpNum+4 != Record.size())
3569 return Error("Invalid record");
3571 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3572 if (Ordering == NotAtomic || Ordering == Release ||
3573 Ordering == AcquireRelease)
3574 return Error("Invalid record");
3575 if (Ordering != NotAtomic && Record[OpNum] == 0)
3576 return Error("Invalid record");
3577 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3579 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3580 Ordering, SynchScope);
3581 InstructionList.push_back(I);
3584 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3587 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3588 popValue(Record, OpNum, NextValueNo,
3589 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3590 OpNum+2 != Record.size())
3591 return Error("Invalid record");
3593 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3594 InstructionList.push_back(I);
3597 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3598 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3601 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3602 popValue(Record, OpNum, NextValueNo,
3603 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3604 OpNum+4 != Record.size())
3605 return Error("Invalid record");
3607 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3608 if (Ordering == NotAtomic || Ordering == Acquire ||
3609 Ordering == AcquireRelease)
3610 return Error("Invalid record");
3611 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3612 if (Ordering != NotAtomic && Record[OpNum] == 0)
3613 return Error("Invalid record");
3615 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3616 Ordering, SynchScope);
3617 InstructionList.push_back(I);
3620 case bitc::FUNC_CODE_INST_CMPXCHG: {
3621 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3622 // failureordering?, isweak?]
3624 Value *Ptr, *Cmp, *New;
3625 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3626 popValue(Record, OpNum, NextValueNo,
3627 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3628 popValue(Record, OpNum, NextValueNo,
3629 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3630 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3631 return Error("Invalid record");
3632 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3633 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3634 return Error("Invalid record");
3635 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3637 AtomicOrdering FailureOrdering;
3638 if (Record.size() < 7)
3640 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3642 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3644 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3646 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3648 if (Record.size() < 8) {
3649 // Before weak cmpxchgs existed, the instruction simply returned the
3650 // value loaded from memory, so bitcode files from that era will be
3651 // expecting the first component of a modern cmpxchg.
3652 CurBB->getInstList().push_back(I);
3653 I = ExtractValueInst::Create(I, 0);
3655 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3658 InstructionList.push_back(I);
3661 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3662 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3665 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3666 popValue(Record, OpNum, NextValueNo,
3667 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3668 OpNum+4 != Record.size())
3669 return Error("Invalid record");
3670 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3671 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3672 Operation > AtomicRMWInst::LAST_BINOP)
3673 return Error("Invalid record");
3674 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3675 if (Ordering == NotAtomic || Ordering == Unordered)
3676 return Error("Invalid record");
3677 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3678 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3679 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3680 InstructionList.push_back(I);
3683 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3684 if (2 != Record.size())
3685 return Error("Invalid record");
3686 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3687 if (Ordering == NotAtomic || Ordering == Unordered ||
3688 Ordering == Monotonic)
3689 return Error("Invalid record");
3690 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3691 I = new FenceInst(Context, Ordering, SynchScope);
3692 InstructionList.push_back(I);
3695 case bitc::FUNC_CODE_INST_CALL: {
3696 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3697 if (Record.size() < 3)
3698 return Error("Invalid record");
3700 AttributeSet PAL = getAttributes(Record[0]);
3701 unsigned CCInfo = Record[1];
3705 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3706 return Error("Invalid record");
3708 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3709 FunctionType *FTy = nullptr;
3710 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3711 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3712 return Error("Invalid record");
3714 SmallVector<Value*, 16> Args;
3715 // Read the fixed params.
3716 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3717 if (FTy->getParamType(i)->isLabelTy())
3718 Args.push_back(getBasicBlock(Record[OpNum]));
3720 Args.push_back(getValue(Record, OpNum, NextValueNo,
3721 FTy->getParamType(i)));
3723 return Error("Invalid record");
3726 // Read type/value pairs for varargs params.
3727 if (!FTy->isVarArg()) {
3728 if (OpNum != Record.size())
3729 return Error("Invalid record");
3731 while (OpNum != Record.size()) {
3733 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3734 return Error("Invalid record");
3739 I = CallInst::Create(Callee, Args);
3740 InstructionList.push_back(I);
3741 cast<CallInst>(I)->setCallingConv(
3742 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3743 CallInst::TailCallKind TCK = CallInst::TCK_None;
3745 TCK = CallInst::TCK_Tail;
3746 if (CCInfo & (1 << 14))
3747 TCK = CallInst::TCK_MustTail;
3748 cast<CallInst>(I)->setTailCallKind(TCK);
3749 cast<CallInst>(I)->setAttributes(PAL);
3752 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3753 if (Record.size() < 3)
3754 return Error("Invalid record");
3755 Type *OpTy = getTypeByID(Record[0]);
3756 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3757 Type *ResTy = getTypeByID(Record[2]);
3758 if (!OpTy || !Op || !ResTy)
3759 return Error("Invalid record");
3760 I = new VAArgInst(Op, ResTy);
3761 InstructionList.push_back(I);
3766 // Add instruction to end of current BB. If there is no current BB, reject
3770 return Error("Invalid instruction with no BB");
3772 CurBB->getInstList().push_back(I);
3774 // If this was a terminator instruction, move to the next block.
3775 if (isa<TerminatorInst>(I)) {
3777 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3780 // Non-void values get registered in the value table for future use.
3781 if (I && !I->getType()->isVoidTy())
3782 ValueList.AssignValue(I, NextValueNo++);
3787 // Check the function list for unresolved values.
3788 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3789 if (!A->getParent()) {
3790 // We found at least one unresolved value. Nuke them all to avoid leaks.
3791 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3792 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3793 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3797 return Error("Never resolved value found in function");
3801 // FIXME: Check for unresolved forward-declared metadata references
3802 // and clean up leaks.
3804 // Trim the value list down to the size it was before we parsed this function.
3805 ValueList.shrinkTo(ModuleValueListSize);
3806 MDValueList.shrinkTo(ModuleMDValueListSize);
3807 std::vector<BasicBlock*>().swap(FunctionBBs);
3808 return std::error_code();
3811 /// Find the function body in the bitcode stream
3812 std::error_code BitcodeReader::FindFunctionInStream(
3814 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3815 while (DeferredFunctionInfoIterator->second == 0) {
3816 if (Stream.AtEndOfStream())
3817 return Error("Could not find function in stream");
3818 // ParseModule will parse the next body in the stream and set its
3819 // position in the DeferredFunctionInfo map.
3820 if (std::error_code EC = ParseModule(true))
3823 return std::error_code();
3826 //===----------------------------------------------------------------------===//
3827 // GVMaterializer implementation
3828 //===----------------------------------------------------------------------===//
3830 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3832 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3833 Function *F = dyn_cast<Function>(GV);
3834 // If it's not a function or is already material, ignore the request.
3835 if (!F || !F->isMaterializable())
3836 return std::error_code();
3838 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3839 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3840 // If its position is recorded as 0, its body is somewhere in the stream
3841 // but we haven't seen it yet.
3842 if (DFII->second == 0 && LazyStreamer)
3843 if (std::error_code EC = FindFunctionInStream(F, DFII))
3846 // Move the bit stream to the saved position of the deferred function body.
3847 Stream.JumpToBit(DFII->second);
3849 if (std::error_code EC = ParseFunctionBody(F))
3851 F->setIsMaterializable(false);
3853 // Upgrade any old intrinsic calls in the function.
3854 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3855 E = UpgradedIntrinsics.end(); I != E; ++I) {
3856 if (I->first != I->second) {
3857 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3859 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3860 UpgradeIntrinsicCall(CI, I->second);
3865 // Bring in any functions that this function forward-referenced via
3867 return materializeForwardReferencedFunctions();
3870 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3871 const Function *F = dyn_cast<Function>(GV);
3872 if (!F || F->isDeclaration())
3875 // Dematerializing F would leave dangling references that wouldn't be
3876 // reconnected on re-materialization.
3877 if (BlockAddressesTaken.count(F))
3880 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3883 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3884 Function *F = dyn_cast<Function>(GV);
3885 // If this function isn't dematerializable, this is a noop.
3886 if (!F || !isDematerializable(F))
3889 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3891 // Just forget the function body, we can remat it later.
3892 F->dropAllReferences();
3893 F->setIsMaterializable(true);
3896 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3897 assert(M == TheModule &&
3898 "Can only Materialize the Module this BitcodeReader is attached to.");
3900 // Promise to materialize all forward references.
3901 WillMaterializeAllForwardRefs = true;
3903 // Iterate over the module, deserializing any functions that are still on
3905 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3907 if (std::error_code EC = materialize(F))
3910 // At this point, if there are any function bodies, the current bit is
3911 // pointing to the END_BLOCK record after them. Now make sure the rest
3912 // of the bits in the module have been read.
3916 // Check that all block address forward references got resolved (as we
3918 if (!BasicBlockFwdRefs.empty())
3919 return Error("Never resolved function from blockaddress");
3921 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3922 // delete the old functions to clean up. We can't do this unless the entire
3923 // module is materialized because there could always be another function body
3924 // with calls to the old function.
3925 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3926 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3927 if (I->first != I->second) {
3928 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3930 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3931 UpgradeIntrinsicCall(CI, I->second);
3933 if (!I->first->use_empty())
3934 I->first->replaceAllUsesWith(I->second);
3935 I->first->eraseFromParent();
3938 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3940 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3941 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3943 UpgradeDebugInfo(*M);
3944 return std::error_code();
3947 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3948 return IdentifiedStructTypes;
3951 std::error_code BitcodeReader::InitStream() {
3953 return InitLazyStream();
3954 return InitStreamFromBuffer();
3957 std::error_code BitcodeReader::InitStreamFromBuffer() {
3958 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3959 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3961 if (Buffer->getBufferSize() & 3)
3962 return Error("Invalid bitcode signature");
3964 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3965 // The magic number is 0x0B17C0DE stored in little endian.
3966 if (isBitcodeWrapper(BufPtr, BufEnd))
3967 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3968 return Error("Invalid bitcode wrapper header");
3970 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3971 Stream.init(&*StreamFile);
3973 return std::error_code();
3976 std::error_code BitcodeReader::InitLazyStream() {
3977 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3979 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3980 StreamingMemoryObject &Bytes = *OwnedBytes;
3981 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3982 Stream.init(&*StreamFile);
3984 unsigned char buf[16];
3985 if (Bytes.readBytes(buf, 16, 0) != 16)
3986 return Error("Invalid bitcode signature");
3988 if (!isBitcode(buf, buf + 16))
3989 return Error("Invalid bitcode signature");
3991 if (isBitcodeWrapper(buf, buf + 4)) {
3992 const unsigned char *bitcodeStart = buf;
3993 const unsigned char *bitcodeEnd = buf + 16;
3994 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3995 Bytes.dropLeadingBytes(bitcodeStart - buf);
3996 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3998 return std::error_code();
4002 class BitcodeErrorCategoryType : public std::error_category {
4003 const char *name() const LLVM_NOEXCEPT override {
4004 return "llvm.bitcode";
4006 std::string message(int IE) const override {
4007 BitcodeError E = static_cast<BitcodeError>(IE);
4009 case BitcodeError::InvalidBitcodeSignature:
4010 return "Invalid bitcode signature";
4011 case BitcodeError::CorruptedBitcode:
4012 return "Corrupted bitcode";
4014 llvm_unreachable("Unknown error type!");
4019 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4021 const std::error_category &llvm::BitcodeErrorCategory() {
4022 return *ErrorCategory;
4025 //===----------------------------------------------------------------------===//
4026 // External interface
4027 //===----------------------------------------------------------------------===//
4029 /// \brief Get a lazy one-at-time loading module from bitcode.
4031 /// This isn't always used in a lazy context. In particular, it's also used by
4032 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4033 /// in forward-referenced functions from block address references.
4035 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4036 /// materialize everything -- in particular, if this isn't truly lazy.
4037 static ErrorOr<Module *>
4038 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4039 LLVMContext &Context, bool WillMaterializeAll,
4040 DiagnosticHandlerFunction DiagnosticHandler) {
4041 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4043 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4044 M->setMaterializer(R);
4046 auto cleanupOnError = [&](std::error_code EC) {
4047 R->releaseBuffer(); // Never take ownership on error.
4048 delete M; // Also deletes R.
4052 if (std::error_code EC = R->ParseBitcodeInto(M))
4053 return cleanupOnError(EC);
4055 if (!WillMaterializeAll)
4056 // Resolve forward references from blockaddresses.
4057 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4058 return cleanupOnError(EC);
4060 Buffer.release(); // The BitcodeReader owns it now.
4065 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4066 LLVMContext &Context,
4067 DiagnosticHandlerFunction DiagnosticHandler) {
4068 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4072 ErrorOr<std::unique_ptr<Module>>
4073 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4074 LLVMContext &Context,
4075 DiagnosticHandlerFunction DiagnosticHandler) {
4076 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4077 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4078 M->setMaterializer(R);
4079 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4081 return std::move(M);
4085 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4086 DiagnosticHandlerFunction DiagnosticHandler) {
4087 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4088 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4089 std::move(Buf), Context, true, DiagnosticHandler);
4092 Module *M = ModuleOrErr.get();
4093 // Read in the entire module, and destroy the BitcodeReader.
4094 if (std::error_code EC = M->materializeAllPermanently()) {
4099 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4100 // written. We must defer until the Module has been fully materialized.
4106 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4107 DiagnosticHandlerFunction DiagnosticHandler) {
4108 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4109 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4111 ErrorOr<std::string> Triple = R->parseTriple();
4112 if (Triple.getError())
4114 return Triple.get();