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 "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/DataStream.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/raw_ostream.h"
41 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
44 class BitcodeReaderValueList {
45 std::vector<WeakVH> ValuePtrs;
47 /// As we resolve forward-referenced constants, we add information about them
48 /// to this vector. This allows us to resolve them in bulk instead of
49 /// resolving each reference at a time. See the code in
50 /// ResolveConstantForwardRefs for more information about this.
52 /// The key of this vector is the placeholder constant, the value is the slot
53 /// number that holds the resolved value.
54 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
55 ResolveConstantsTy ResolveConstants;
58 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
59 ~BitcodeReaderValueList() {
60 assert(ResolveConstants.empty() && "Constants not resolved?");
63 // vector compatibility methods
64 unsigned size() const { return ValuePtrs.size(); }
65 void resize(unsigned N) { ValuePtrs.resize(N); }
66 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
69 assert(ResolveConstants.empty() && "Constants not resolved?");
73 Value *operator[](unsigned i) const {
74 assert(i < ValuePtrs.size());
78 Value *back() const { return ValuePtrs.back(); }
79 void pop_back() { ValuePtrs.pop_back(); }
80 bool empty() const { return ValuePtrs.empty(); }
81 void shrinkTo(unsigned N) {
82 assert(N <= size() && "Invalid shrinkTo request!");
86 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
87 Value *getValueFwdRef(unsigned Idx, Type *Ty);
89 void assignValue(Value *V, unsigned Idx);
91 /// Once all constants are read, this method bulk resolves any forward
93 void resolveConstantForwardRefs();
96 class BitcodeReaderMDValueList {
101 std::vector<TrackingMDRef> MDValuePtrs;
103 LLVMContext &Context;
105 BitcodeReaderMDValueList(LLVMContext &C)
106 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
108 // vector compatibility methods
109 unsigned size() const { return MDValuePtrs.size(); }
110 void resize(unsigned N) { MDValuePtrs.resize(N); }
111 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
112 void clear() { MDValuePtrs.clear(); }
113 Metadata *back() const { return MDValuePtrs.back(); }
114 void pop_back() { MDValuePtrs.pop_back(); }
115 bool empty() const { return MDValuePtrs.empty(); }
117 Metadata *operator[](unsigned i) const {
118 assert(i < MDValuePtrs.size());
119 return MDValuePtrs[i];
122 void shrinkTo(unsigned N) {
123 assert(N <= size() && "Invalid shrinkTo request!");
124 MDValuePtrs.resize(N);
127 Metadata *getValueFwdRef(unsigned Idx);
128 void assignValue(Metadata *MD, unsigned Idx);
129 void tryToResolveCycles();
132 class BitcodeReader : public GVMaterializer {
133 LLVMContext &Context;
134 DiagnosticHandlerFunction DiagnosticHandler;
135 Module *TheModule = nullptr;
136 std::unique_ptr<MemoryBuffer> Buffer;
137 std::unique_ptr<BitstreamReader> StreamFile;
138 BitstreamCursor Stream;
139 uint64_t NextUnreadBit = 0;
140 bool SeenValueSymbolTable = false;
142 std::vector<Type*> TypeList;
143 BitcodeReaderValueList ValueList;
144 BitcodeReaderMDValueList MDValueList;
145 std::vector<Comdat *> ComdatList;
146 SmallVector<Instruction *, 64> InstructionList;
148 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
149 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
150 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
151 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
152 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
154 SmallVector<Instruction*, 64> InstsWithTBAATag;
156 /// The set of attributes by index. Index zero in the file is for null, and
157 /// is thus not represented here. As such all indices are off by one.
158 std::vector<AttributeSet> MAttributes;
160 /// \brief The set of attribute groups.
161 std::map<unsigned, AttributeSet> MAttributeGroups;
163 /// While parsing a function body, this is a list of the basic blocks for the
165 std::vector<BasicBlock*> FunctionBBs;
167 // When reading the module header, this list is populated with functions that
168 // have bodies later in the file.
169 std::vector<Function*> FunctionsWithBodies;
171 // When intrinsic functions are encountered which require upgrading they are
172 // stored here with their replacement function.
173 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
174 UpgradedIntrinsicMap UpgradedIntrinsics;
176 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
177 DenseMap<unsigned, unsigned> MDKindMap;
179 // Several operations happen after the module header has been read, but
180 // before function bodies are processed. This keeps track of whether
181 // we've done this yet.
182 bool SeenFirstFunctionBody = false;
184 /// When function bodies are initially scanned, this map contains info about
185 /// where to find deferred function body in the stream.
186 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
188 /// When Metadata block is initially scanned when parsing the module, we may
189 /// choose to defer parsing of the metadata. This vector contains info about
190 /// which Metadata blocks are deferred.
191 std::vector<uint64_t> DeferredMetadataInfo;
193 /// These are basic blocks forward-referenced by block addresses. They are
194 /// inserted lazily into functions when they're loaded. The basic block ID is
195 /// its index into the vector.
196 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
197 std::deque<Function *> BasicBlockFwdRefQueue;
199 /// Indicates that we are using a new encoding for instruction operands where
200 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
201 /// instruction number, for a more compact encoding. Some instruction
202 /// operands are not relative to the instruction ID: basic block numbers, and
203 /// types. Once the old style function blocks have been phased out, we would
204 /// not need this flag.
205 bool UseRelativeIDs = false;
207 /// True if all functions will be materialized, negating the need to process
208 /// (e.g.) blockaddress forward references.
209 bool WillMaterializeAllForwardRefs = false;
211 /// Functions that have block addresses taken. This is usually empty.
212 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
214 /// True if any Metadata block has been materialized.
215 bool IsMetadataMaterialized = false;
217 bool StripDebugInfo = false;
220 std::error_code error(BitcodeError E, const Twine &Message);
221 std::error_code error(BitcodeError E);
222 std::error_code error(const Twine &Message);
224 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
225 DiagnosticHandlerFunction DiagnosticHandler);
226 BitcodeReader(LLVMContext &Context,
227 DiagnosticHandlerFunction DiagnosticHandler);
228 ~BitcodeReader() override { freeState(); }
230 std::error_code materializeForwardReferencedFunctions();
234 void releaseBuffer();
236 bool isDematerializable(const GlobalValue *GV) const override;
237 std::error_code materialize(GlobalValue *GV) override;
238 std::error_code materializeModule(Module *M) override;
239 std::vector<StructType *> getIdentifiedStructTypes() const override;
240 void dematerialize(GlobalValue *GV) override;
242 /// \brief Main interface to parsing a bitcode buffer.
243 /// \returns true if an error occurred.
244 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
246 bool ShouldLazyLoadMetadata = false);
248 /// \brief Cheap mechanism to just extract module triple
249 /// \returns true if an error occurred.
250 ErrorOr<std::string> parseTriple();
252 static uint64_t decodeSignRotatedValue(uint64_t V);
254 /// Materialize any deferred Metadata block.
255 std::error_code materializeMetadata() override;
257 void setStripDebugInfo() override;
260 std::vector<StructType *> IdentifiedStructTypes;
261 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
262 StructType *createIdentifiedStructType(LLVMContext &Context);
264 Type *getTypeByID(unsigned ID);
265 Value *getFnValueByID(unsigned ID, Type *Ty) {
266 if (Ty && Ty->isMetadataTy())
267 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
268 return ValueList.getValueFwdRef(ID, Ty);
270 Metadata *getFnMetadataByID(unsigned ID) {
271 return MDValueList.getValueFwdRef(ID);
273 BasicBlock *getBasicBlock(unsigned ID) const {
274 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
275 return FunctionBBs[ID];
277 AttributeSet getAttributes(unsigned i) const {
278 if (i-1 < MAttributes.size())
279 return MAttributes[i-1];
280 return AttributeSet();
283 /// Read a value/type pair out of the specified record from slot 'Slot'.
284 /// Increment Slot past the number of slots used in the record. Return true on
286 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
287 unsigned InstNum, Value *&ResVal) {
288 if (Slot == Record.size()) return true;
289 unsigned ValNo = (unsigned)Record[Slot++];
290 // Adjust the ValNo, if it was encoded relative to the InstNum.
292 ValNo = InstNum - ValNo;
293 if (ValNo < InstNum) {
294 // If this is not a forward reference, just return the value we already
296 ResVal = getFnValueByID(ValNo, nullptr);
297 return ResVal == nullptr;
299 if (Slot == Record.size())
302 unsigned TypeNo = (unsigned)Record[Slot++];
303 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
304 return ResVal == nullptr;
307 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
308 /// past the number of slots used by the value in the record. Return true if
309 /// there is an error.
310 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
311 unsigned InstNum, Type *Ty, Value *&ResVal) {
312 if (getValue(Record, Slot, InstNum, Ty, ResVal))
314 // All values currently take a single record slot.
319 /// Like popValue, but does not increment the Slot number.
320 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
321 unsigned InstNum, Type *Ty, Value *&ResVal) {
322 ResVal = getValue(Record, Slot, InstNum, Ty);
323 return ResVal == nullptr;
326 /// Version of getValue that returns ResVal directly, or 0 if there is an
328 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
329 unsigned InstNum, Type *Ty) {
330 if (Slot == Record.size()) return nullptr;
331 unsigned ValNo = (unsigned)Record[Slot];
332 // Adjust the ValNo, if it was encoded relative to the InstNum.
334 ValNo = InstNum - ValNo;
335 return getFnValueByID(ValNo, Ty);
338 /// Like getValue, but decodes signed VBRs.
339 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
340 unsigned InstNum, Type *Ty) {
341 if (Slot == Record.size()) return nullptr;
342 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
343 // Adjust the ValNo, if it was encoded relative to the InstNum.
345 ValNo = InstNum - ValNo;
346 return getFnValueByID(ValNo, Ty);
349 /// Converts alignment exponent (i.e. power of two (or zero)) to the
350 /// corresponding alignment to use. If alignment is too large, returns
351 /// a corresponding error code.
352 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
353 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
354 std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
355 std::error_code parseAttributeBlock();
356 std::error_code parseAttributeGroupBlock();
357 std::error_code parseTypeTable();
358 std::error_code parseTypeTableBody();
360 std::error_code parseValueSymbolTable();
361 std::error_code parseConstants();
362 std::error_code rememberAndSkipFunctionBody();
363 /// Save the positions of the Metadata blocks and skip parsing the blocks.
364 std::error_code rememberAndSkipMetadata();
365 std::error_code parseFunctionBody(Function *F);
366 std::error_code globalCleanup();
367 std::error_code resolveGlobalAndAliasInits();
368 std::error_code parseMetadata();
369 std::error_code parseMetadataAttachment(Function &F);
370 ErrorOr<std::string> parseModuleTriple();
371 std::error_code parseUseLists();
372 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
373 std::error_code initStreamFromBuffer();
374 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
375 std::error_code findFunctionInStream(
377 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
381 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
382 DiagnosticSeverity Severity,
384 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
386 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
388 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
389 std::error_code EC, const Twine &Message) {
390 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
391 DiagnosticHandler(DI);
395 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
396 std::error_code EC) {
397 return error(DiagnosticHandler, EC, EC.message());
400 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
401 const Twine &Message) {
402 return error(DiagnosticHandler,
403 make_error_code(BitcodeError::CorruptedBitcode), Message);
406 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
407 return ::error(DiagnosticHandler, make_error_code(E), Message);
410 std::error_code BitcodeReader::error(const Twine &Message) {
411 return ::error(DiagnosticHandler,
412 make_error_code(BitcodeError::CorruptedBitcode), Message);
415 std::error_code BitcodeReader::error(BitcodeError E) {
416 return ::error(DiagnosticHandler, make_error_code(E));
419 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
423 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
426 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
427 DiagnosticHandlerFunction DiagnosticHandler)
429 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
430 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
432 BitcodeReader::BitcodeReader(LLVMContext &Context,
433 DiagnosticHandlerFunction DiagnosticHandler)
435 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
436 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
438 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
439 if (WillMaterializeAllForwardRefs)
440 return std::error_code();
442 // Prevent recursion.
443 WillMaterializeAllForwardRefs = true;
445 while (!BasicBlockFwdRefQueue.empty()) {
446 Function *F = BasicBlockFwdRefQueue.front();
447 BasicBlockFwdRefQueue.pop_front();
448 assert(F && "Expected valid function");
449 if (!BasicBlockFwdRefs.count(F))
450 // Already materialized.
453 // Check for a function that isn't materializable to prevent an infinite
454 // loop. When parsing a blockaddress stored in a global variable, there
455 // isn't a trivial way to check if a function will have a body without a
456 // linear search through FunctionsWithBodies, so just check it here.
457 if (!F->isMaterializable())
458 return error("Never resolved function from blockaddress");
460 // Try to materialize F.
461 if (std::error_code EC = materialize(F))
464 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
467 WillMaterializeAllForwardRefs = false;
468 return std::error_code();
471 void BitcodeReader::freeState() {
473 std::vector<Type*>().swap(TypeList);
476 std::vector<Comdat *>().swap(ComdatList);
478 std::vector<AttributeSet>().swap(MAttributes);
479 std::vector<BasicBlock*>().swap(FunctionBBs);
480 std::vector<Function*>().swap(FunctionsWithBodies);
481 DeferredFunctionInfo.clear();
482 DeferredMetadataInfo.clear();
485 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
486 BasicBlockFwdRefQueue.clear();
489 //===----------------------------------------------------------------------===//
490 // Helper functions to implement forward reference resolution, etc.
491 //===----------------------------------------------------------------------===//
493 /// Convert a string from a record into an std::string, return true on failure.
494 template <typename StrTy>
495 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
497 if (Idx > Record.size())
500 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
501 Result += (char)Record[i];
505 static bool hasImplicitComdat(size_t Val) {
509 case 1: // Old WeakAnyLinkage
510 case 4: // Old LinkOnceAnyLinkage
511 case 10: // Old WeakODRLinkage
512 case 11: // Old LinkOnceODRLinkage
517 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
519 default: // Map unknown/new linkages to external
521 return GlobalValue::ExternalLinkage;
523 return GlobalValue::AppendingLinkage;
525 return GlobalValue::InternalLinkage;
527 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
529 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
531 return GlobalValue::ExternalWeakLinkage;
533 return GlobalValue::CommonLinkage;
535 return GlobalValue::PrivateLinkage;
537 return GlobalValue::AvailableExternallyLinkage;
539 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
541 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
543 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
544 case 1: // Old value with implicit comdat.
546 return GlobalValue::WeakAnyLinkage;
547 case 10: // Old value with implicit comdat.
549 return GlobalValue::WeakODRLinkage;
550 case 4: // Old value with implicit comdat.
552 return GlobalValue::LinkOnceAnyLinkage;
553 case 11: // Old value with implicit comdat.
555 return GlobalValue::LinkOnceODRLinkage;
559 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
561 default: // Map unknown visibilities to default.
562 case 0: return GlobalValue::DefaultVisibility;
563 case 1: return GlobalValue::HiddenVisibility;
564 case 2: return GlobalValue::ProtectedVisibility;
568 static GlobalValue::DLLStorageClassTypes
569 getDecodedDLLStorageClass(unsigned Val) {
571 default: // Map unknown values to default.
572 case 0: return GlobalValue::DefaultStorageClass;
573 case 1: return GlobalValue::DLLImportStorageClass;
574 case 2: return GlobalValue::DLLExportStorageClass;
578 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
580 case 0: return GlobalVariable::NotThreadLocal;
581 default: // Map unknown non-zero value to general dynamic.
582 case 1: return GlobalVariable::GeneralDynamicTLSModel;
583 case 2: return GlobalVariable::LocalDynamicTLSModel;
584 case 3: return GlobalVariable::InitialExecTLSModel;
585 case 4: return GlobalVariable::LocalExecTLSModel;
589 static int getDecodedCastOpcode(unsigned Val) {
592 case bitc::CAST_TRUNC : return Instruction::Trunc;
593 case bitc::CAST_ZEXT : return Instruction::ZExt;
594 case bitc::CAST_SEXT : return Instruction::SExt;
595 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
596 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
597 case bitc::CAST_UITOFP : return Instruction::UIToFP;
598 case bitc::CAST_SITOFP : return Instruction::SIToFP;
599 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
600 case bitc::CAST_FPEXT : return Instruction::FPExt;
601 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
602 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
603 case bitc::CAST_BITCAST : return Instruction::BitCast;
604 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
608 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
609 bool IsFP = Ty->isFPOrFPVectorTy();
610 // BinOps are only valid for int/fp or vector of int/fp types
611 if (!IsFP && !Ty->isIntOrIntVectorTy())
617 case bitc::BINOP_ADD:
618 return IsFP ? Instruction::FAdd : Instruction::Add;
619 case bitc::BINOP_SUB:
620 return IsFP ? Instruction::FSub : Instruction::Sub;
621 case bitc::BINOP_MUL:
622 return IsFP ? Instruction::FMul : Instruction::Mul;
623 case bitc::BINOP_UDIV:
624 return IsFP ? -1 : Instruction::UDiv;
625 case bitc::BINOP_SDIV:
626 return IsFP ? Instruction::FDiv : Instruction::SDiv;
627 case bitc::BINOP_UREM:
628 return IsFP ? -1 : Instruction::URem;
629 case bitc::BINOP_SREM:
630 return IsFP ? Instruction::FRem : Instruction::SRem;
631 case bitc::BINOP_SHL:
632 return IsFP ? -1 : Instruction::Shl;
633 case bitc::BINOP_LSHR:
634 return IsFP ? -1 : Instruction::LShr;
635 case bitc::BINOP_ASHR:
636 return IsFP ? -1 : Instruction::AShr;
637 case bitc::BINOP_AND:
638 return IsFP ? -1 : Instruction::And;
640 return IsFP ? -1 : Instruction::Or;
641 case bitc::BINOP_XOR:
642 return IsFP ? -1 : Instruction::Xor;
646 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
648 default: return AtomicRMWInst::BAD_BINOP;
649 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
650 case bitc::RMW_ADD: return AtomicRMWInst::Add;
651 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
652 case bitc::RMW_AND: return AtomicRMWInst::And;
653 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
654 case bitc::RMW_OR: return AtomicRMWInst::Or;
655 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
656 case bitc::RMW_MAX: return AtomicRMWInst::Max;
657 case bitc::RMW_MIN: return AtomicRMWInst::Min;
658 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
659 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
663 static AtomicOrdering getDecodedOrdering(unsigned Val) {
665 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
666 case bitc::ORDERING_UNORDERED: return Unordered;
667 case bitc::ORDERING_MONOTONIC: return Monotonic;
668 case bitc::ORDERING_ACQUIRE: return Acquire;
669 case bitc::ORDERING_RELEASE: return Release;
670 case bitc::ORDERING_ACQREL: return AcquireRelease;
671 default: // Map unknown orderings to sequentially-consistent.
672 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
676 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
678 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
679 default: // Map unknown scopes to cross-thread.
680 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
684 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
686 default: // Map unknown selection kinds to any.
687 case bitc::COMDAT_SELECTION_KIND_ANY:
689 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
690 return Comdat::ExactMatch;
691 case bitc::COMDAT_SELECTION_KIND_LARGEST:
692 return Comdat::Largest;
693 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
694 return Comdat::NoDuplicates;
695 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
696 return Comdat::SameSize;
700 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
702 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
703 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
709 /// \brief A class for maintaining the slot number definition
710 /// as a placeholder for the actual definition for forward constants defs.
711 class ConstantPlaceHolder : public ConstantExpr {
712 void operator=(const ConstantPlaceHolder &) = delete;
715 // allocate space for exactly one operand
716 void *operator new(size_t s) { return User::operator new(s, 1); }
717 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
718 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
719 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
722 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
723 static bool classof(const Value *V) {
724 return isa<ConstantExpr>(V) &&
725 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
728 /// Provide fast operand accessors
729 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
733 // FIXME: can we inherit this from ConstantExpr?
735 struct OperandTraits<ConstantPlaceHolder> :
736 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
738 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
741 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
750 WeakVH &OldV = ValuePtrs[Idx];
756 // Handle constants and non-constants (e.g. instrs) differently for
758 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
759 ResolveConstants.push_back(std::make_pair(PHC, Idx));
762 // If there was a forward reference to this value, replace it.
763 Value *PrevVal = OldV;
764 OldV->replaceAllUsesWith(V);
770 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
775 if (Value *V = ValuePtrs[Idx]) {
776 if (Ty != V->getType())
777 report_fatal_error("Type mismatch in constant table!");
778 return cast<Constant>(V);
781 // Create and return a placeholder, which will later be RAUW'd.
782 Constant *C = new ConstantPlaceHolder(Ty, Context);
787 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
788 // Bail out for a clearly invalid value. This would make us call resize(0)
795 if (Value *V = ValuePtrs[Idx]) {
796 // If the types don't match, it's invalid.
797 if (Ty && Ty != V->getType())
802 // No type specified, must be invalid reference.
803 if (!Ty) return nullptr;
805 // Create and return a placeholder, which will later be RAUW'd.
806 Value *V = new Argument(Ty);
811 /// Once all constants are read, this method bulk resolves any forward
812 /// references. The idea behind this is that we sometimes get constants (such
813 /// as large arrays) which reference *many* forward ref constants. Replacing
814 /// each of these causes a lot of thrashing when building/reuniquing the
815 /// constant. Instead of doing this, we look at all the uses and rewrite all
816 /// the place holders at once for any constant that uses a placeholder.
817 void BitcodeReaderValueList::resolveConstantForwardRefs() {
818 // Sort the values by-pointer so that they are efficient to look up with a
820 std::sort(ResolveConstants.begin(), ResolveConstants.end());
822 SmallVector<Constant*, 64> NewOps;
824 while (!ResolveConstants.empty()) {
825 Value *RealVal = operator[](ResolveConstants.back().second);
826 Constant *Placeholder = ResolveConstants.back().first;
827 ResolveConstants.pop_back();
829 // Loop over all users of the placeholder, updating them to reference the
830 // new value. If they reference more than one placeholder, update them all
832 while (!Placeholder->use_empty()) {
833 auto UI = Placeholder->user_begin();
836 // If the using object isn't uniqued, just update the operands. This
837 // handles instructions and initializers for global variables.
838 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
839 UI.getUse().set(RealVal);
843 // Otherwise, we have a constant that uses the placeholder. Replace that
844 // constant with a new constant that has *all* placeholder uses updated.
845 Constant *UserC = cast<Constant>(U);
846 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
849 if (!isa<ConstantPlaceHolder>(*I)) {
850 // Not a placeholder reference.
852 } else if (*I == Placeholder) {
853 // Common case is that it just references this one placeholder.
856 // Otherwise, look up the placeholder in ResolveConstants.
857 ResolveConstantsTy::iterator It =
858 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
859 std::pair<Constant*, unsigned>(cast<Constant>(*I),
861 assert(It != ResolveConstants.end() && It->first == *I);
862 NewOp = operator[](It->second);
865 NewOps.push_back(cast<Constant>(NewOp));
868 // Make the new constant.
870 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
871 NewC = ConstantArray::get(UserCA->getType(), NewOps);
872 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
873 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
874 } else if (isa<ConstantVector>(UserC)) {
875 NewC = ConstantVector::get(NewOps);
877 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
878 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
881 UserC->replaceAllUsesWith(NewC);
882 UserC->destroyConstant();
886 // Update all ValueHandles, they should be the only users at this point.
887 Placeholder->replaceAllUsesWith(RealVal);
892 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
901 TrackingMDRef &OldMD = MDValuePtrs[Idx];
907 // If there was a forward reference to this value, replace it.
908 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
909 PrevMD->replaceAllUsesWith(MD);
913 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
917 if (Metadata *MD = MDValuePtrs[Idx])
920 // Track forward refs to be resolved later.
922 MinFwdRef = std::min(MinFwdRef, Idx);
923 MaxFwdRef = std::max(MaxFwdRef, Idx);
926 MinFwdRef = MaxFwdRef = Idx;
930 // Create and return a placeholder, which will later be RAUW'd.
931 Metadata *MD = MDNode::getTemporary(Context, None).release();
932 MDValuePtrs[Idx].reset(MD);
936 void BitcodeReaderMDValueList::tryToResolveCycles() {
942 // Still forward references... can't resolve cycles.
945 // Resolve any cycles.
946 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
947 auto &MD = MDValuePtrs[I];
948 auto *N = dyn_cast_or_null<MDNode>(MD);
952 assert(!N->isTemporary() && "Unexpected forward reference");
956 // Make sure we return early again until there's another forward ref.
960 Type *BitcodeReader::getTypeByID(unsigned ID) {
961 // The type table size is always specified correctly.
962 if (ID >= TypeList.size())
965 if (Type *Ty = TypeList[ID])
968 // If we have a forward reference, the only possible case is when it is to a
969 // named struct. Just create a placeholder for now.
970 return TypeList[ID] = createIdentifiedStructType(Context);
973 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
975 auto *Ret = StructType::create(Context, Name);
976 IdentifiedStructTypes.push_back(Ret);
980 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
981 auto *Ret = StructType::create(Context);
982 IdentifiedStructTypes.push_back(Ret);
987 //===----------------------------------------------------------------------===//
988 // Functions for parsing blocks from the bitcode file
989 //===----------------------------------------------------------------------===//
992 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
993 /// been decoded from the given integer. This function must stay in sync with
994 /// 'encodeLLVMAttributesForBitcode'.
995 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
996 uint64_t EncodedAttrs) {
997 // FIXME: Remove in 4.0.
999 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1000 // the bits above 31 down by 11 bits.
1001 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1002 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1003 "Alignment must be a power of two.");
1006 B.addAlignmentAttr(Alignment);
1007 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1008 (EncodedAttrs & 0xffff));
1011 std::error_code BitcodeReader::parseAttributeBlock() {
1012 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1013 return error("Invalid record");
1015 if (!MAttributes.empty())
1016 return error("Invalid multiple blocks");
1018 SmallVector<uint64_t, 64> Record;
1020 SmallVector<AttributeSet, 8> Attrs;
1022 // Read all the records.
1024 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1026 switch (Entry.Kind) {
1027 case BitstreamEntry::SubBlock: // Handled for us already.
1028 case BitstreamEntry::Error:
1029 return error("Malformed block");
1030 case BitstreamEntry::EndBlock:
1031 return std::error_code();
1032 case BitstreamEntry::Record:
1033 // The interesting case.
1039 switch (Stream.readRecord(Entry.ID, Record)) {
1040 default: // Default behavior: ignore.
1042 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1043 // FIXME: Remove in 4.0.
1044 if (Record.size() & 1)
1045 return error("Invalid record");
1047 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1049 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1050 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1053 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1057 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1058 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1059 Attrs.push_back(MAttributeGroups[Record[i]]);
1061 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1069 // Returns Attribute::None on unrecognized codes.
1070 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1073 return Attribute::None;
1074 case bitc::ATTR_KIND_ALIGNMENT:
1075 return Attribute::Alignment;
1076 case bitc::ATTR_KIND_ALWAYS_INLINE:
1077 return Attribute::AlwaysInline;
1078 case bitc::ATTR_KIND_BUILTIN:
1079 return Attribute::Builtin;
1080 case bitc::ATTR_KIND_BY_VAL:
1081 return Attribute::ByVal;
1082 case bitc::ATTR_KIND_IN_ALLOCA:
1083 return Attribute::InAlloca;
1084 case bitc::ATTR_KIND_COLD:
1085 return Attribute::Cold;
1086 case bitc::ATTR_KIND_CONVERGENT:
1087 return Attribute::Convergent;
1088 case bitc::ATTR_KIND_INLINE_HINT:
1089 return Attribute::InlineHint;
1090 case bitc::ATTR_KIND_IN_REG:
1091 return Attribute::InReg;
1092 case bitc::ATTR_KIND_JUMP_TABLE:
1093 return Attribute::JumpTable;
1094 case bitc::ATTR_KIND_MIN_SIZE:
1095 return Attribute::MinSize;
1096 case bitc::ATTR_KIND_NAKED:
1097 return Attribute::Naked;
1098 case bitc::ATTR_KIND_NEST:
1099 return Attribute::Nest;
1100 case bitc::ATTR_KIND_NO_ALIAS:
1101 return Attribute::NoAlias;
1102 case bitc::ATTR_KIND_NO_BUILTIN:
1103 return Attribute::NoBuiltin;
1104 case bitc::ATTR_KIND_NO_CAPTURE:
1105 return Attribute::NoCapture;
1106 case bitc::ATTR_KIND_NO_DUPLICATE:
1107 return Attribute::NoDuplicate;
1108 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1109 return Attribute::NoImplicitFloat;
1110 case bitc::ATTR_KIND_NO_INLINE:
1111 return Attribute::NoInline;
1112 case bitc::ATTR_KIND_NON_LAZY_BIND:
1113 return Attribute::NonLazyBind;
1114 case bitc::ATTR_KIND_NON_NULL:
1115 return Attribute::NonNull;
1116 case bitc::ATTR_KIND_DEREFERENCEABLE:
1117 return Attribute::Dereferenceable;
1118 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1119 return Attribute::DereferenceableOrNull;
1120 case bitc::ATTR_KIND_NO_RED_ZONE:
1121 return Attribute::NoRedZone;
1122 case bitc::ATTR_KIND_NO_RETURN:
1123 return Attribute::NoReturn;
1124 case bitc::ATTR_KIND_NO_UNWIND:
1125 return Attribute::NoUnwind;
1126 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1127 return Attribute::OptimizeForSize;
1128 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1129 return Attribute::OptimizeNone;
1130 case bitc::ATTR_KIND_READ_NONE:
1131 return Attribute::ReadNone;
1132 case bitc::ATTR_KIND_READ_ONLY:
1133 return Attribute::ReadOnly;
1134 case bitc::ATTR_KIND_RETURNED:
1135 return Attribute::Returned;
1136 case bitc::ATTR_KIND_RETURNS_TWICE:
1137 return Attribute::ReturnsTwice;
1138 case bitc::ATTR_KIND_S_EXT:
1139 return Attribute::SExt;
1140 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1141 return Attribute::StackAlignment;
1142 case bitc::ATTR_KIND_STACK_PROTECT:
1143 return Attribute::StackProtect;
1144 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1145 return Attribute::StackProtectReq;
1146 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1147 return Attribute::StackProtectStrong;
1148 case bitc::ATTR_KIND_SAFESTACK:
1149 return Attribute::SafeStack;
1150 case bitc::ATTR_KIND_STRUCT_RET:
1151 return Attribute::StructRet;
1152 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1153 return Attribute::SanitizeAddress;
1154 case bitc::ATTR_KIND_SANITIZE_THREAD:
1155 return Attribute::SanitizeThread;
1156 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1157 return Attribute::SanitizeMemory;
1158 case bitc::ATTR_KIND_UW_TABLE:
1159 return Attribute::UWTable;
1160 case bitc::ATTR_KIND_Z_EXT:
1161 return Attribute::ZExt;
1165 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1166 unsigned &Alignment) {
1167 // Note: Alignment in bitcode files is incremented by 1, so that zero
1168 // can be used for default alignment.
1169 if (Exponent > Value::MaxAlignmentExponent + 1)
1170 return error("Invalid alignment value");
1171 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1172 return std::error_code();
1175 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1176 Attribute::AttrKind *Kind) {
1177 *Kind = getAttrFromCode(Code);
1178 if (*Kind == Attribute::None)
1179 return error(BitcodeError::CorruptedBitcode,
1180 "Unknown attribute kind (" + Twine(Code) + ")");
1181 return std::error_code();
1184 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1185 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1186 return error("Invalid record");
1188 if (!MAttributeGroups.empty())
1189 return error("Invalid multiple blocks");
1191 SmallVector<uint64_t, 64> Record;
1193 // Read all the records.
1195 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1197 switch (Entry.Kind) {
1198 case BitstreamEntry::SubBlock: // Handled for us already.
1199 case BitstreamEntry::Error:
1200 return error("Malformed block");
1201 case BitstreamEntry::EndBlock:
1202 return std::error_code();
1203 case BitstreamEntry::Record:
1204 // The interesting case.
1210 switch (Stream.readRecord(Entry.ID, Record)) {
1211 default: // Default behavior: ignore.
1213 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1214 if (Record.size() < 3)
1215 return error("Invalid record");
1217 uint64_t GrpID = Record[0];
1218 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1221 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1222 if (Record[i] == 0) { // Enum attribute
1223 Attribute::AttrKind Kind;
1224 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1227 B.addAttribute(Kind);
1228 } else if (Record[i] == 1) { // Integer attribute
1229 Attribute::AttrKind Kind;
1230 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1232 if (Kind == Attribute::Alignment)
1233 B.addAlignmentAttr(Record[++i]);
1234 else if (Kind == Attribute::StackAlignment)
1235 B.addStackAlignmentAttr(Record[++i]);
1236 else if (Kind == Attribute::Dereferenceable)
1237 B.addDereferenceableAttr(Record[++i]);
1238 else if (Kind == Attribute::DereferenceableOrNull)
1239 B.addDereferenceableOrNullAttr(Record[++i]);
1240 } else { // String attribute
1241 assert((Record[i] == 3 || Record[i] == 4) &&
1242 "Invalid attribute group entry");
1243 bool HasValue = (Record[i++] == 4);
1244 SmallString<64> KindStr;
1245 SmallString<64> ValStr;
1247 while (Record[i] != 0 && i != e)
1248 KindStr += Record[i++];
1249 assert(Record[i] == 0 && "Kind string not null terminated");
1252 // Has a value associated with it.
1253 ++i; // Skip the '0' that terminates the "kind" string.
1254 while (Record[i] != 0 && i != e)
1255 ValStr += Record[i++];
1256 assert(Record[i] == 0 && "Value string not null terminated");
1259 B.addAttribute(KindStr.str(), ValStr.str());
1263 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1270 std::error_code BitcodeReader::parseTypeTable() {
1271 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1272 return error("Invalid record");
1274 return parseTypeTableBody();
1277 std::error_code BitcodeReader::parseTypeTableBody() {
1278 if (!TypeList.empty())
1279 return error("Invalid multiple blocks");
1281 SmallVector<uint64_t, 64> Record;
1282 unsigned NumRecords = 0;
1284 SmallString<64> TypeName;
1286 // Read all the records for this type table.
1288 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1290 switch (Entry.Kind) {
1291 case BitstreamEntry::SubBlock: // Handled for us already.
1292 case BitstreamEntry::Error:
1293 return error("Malformed block");
1294 case BitstreamEntry::EndBlock:
1295 if (NumRecords != TypeList.size())
1296 return error("Malformed block");
1297 return std::error_code();
1298 case BitstreamEntry::Record:
1299 // The interesting case.
1305 Type *ResultTy = nullptr;
1306 switch (Stream.readRecord(Entry.ID, Record)) {
1308 return error("Invalid value");
1309 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1310 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1311 // type list. This allows us to reserve space.
1312 if (Record.size() < 1)
1313 return error("Invalid record");
1314 TypeList.resize(Record[0]);
1316 case bitc::TYPE_CODE_VOID: // VOID
1317 ResultTy = Type::getVoidTy(Context);
1319 case bitc::TYPE_CODE_HALF: // HALF
1320 ResultTy = Type::getHalfTy(Context);
1322 case bitc::TYPE_CODE_FLOAT: // FLOAT
1323 ResultTy = Type::getFloatTy(Context);
1325 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1326 ResultTy = Type::getDoubleTy(Context);
1328 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1329 ResultTy = Type::getX86_FP80Ty(Context);
1331 case bitc::TYPE_CODE_FP128: // FP128
1332 ResultTy = Type::getFP128Ty(Context);
1334 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1335 ResultTy = Type::getPPC_FP128Ty(Context);
1337 case bitc::TYPE_CODE_LABEL: // LABEL
1338 ResultTy = Type::getLabelTy(Context);
1340 case bitc::TYPE_CODE_METADATA: // METADATA
1341 ResultTy = Type::getMetadataTy(Context);
1343 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1344 ResultTy = Type::getX86_MMXTy(Context);
1346 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1347 if (Record.size() < 1)
1348 return error("Invalid record");
1350 uint64_t NumBits = Record[0];
1351 if (NumBits < IntegerType::MIN_INT_BITS ||
1352 NumBits > IntegerType::MAX_INT_BITS)
1353 return error("Bitwidth for integer type out of range");
1354 ResultTy = IntegerType::get(Context, NumBits);
1357 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1358 // [pointee type, address space]
1359 if (Record.size() < 1)
1360 return error("Invalid record");
1361 unsigned AddressSpace = 0;
1362 if (Record.size() == 2)
1363 AddressSpace = Record[1];
1364 ResultTy = getTypeByID(Record[0]);
1366 !PointerType::isValidElementType(ResultTy))
1367 return error("Invalid type");
1368 ResultTy = PointerType::get(ResultTy, AddressSpace);
1371 case bitc::TYPE_CODE_FUNCTION_OLD: {
1372 // FIXME: attrid is dead, remove it in LLVM 4.0
1373 // FUNCTION: [vararg, attrid, retty, paramty x N]
1374 if (Record.size() < 3)
1375 return error("Invalid record");
1376 SmallVector<Type*, 8> ArgTys;
1377 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1378 if (Type *T = getTypeByID(Record[i]))
1379 ArgTys.push_back(T);
1384 ResultTy = getTypeByID(Record[2]);
1385 if (!ResultTy || ArgTys.size() < Record.size()-3)
1386 return error("Invalid type");
1388 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1391 case bitc::TYPE_CODE_FUNCTION: {
1392 // FUNCTION: [vararg, retty, paramty x N]
1393 if (Record.size() < 2)
1394 return error("Invalid record");
1395 SmallVector<Type*, 8> ArgTys;
1396 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1397 if (Type *T = getTypeByID(Record[i])) {
1398 if (!FunctionType::isValidArgumentType(T))
1399 return error("Invalid function argument type");
1400 ArgTys.push_back(T);
1406 ResultTy = getTypeByID(Record[1]);
1407 if (!ResultTy || ArgTys.size() < Record.size()-2)
1408 return error("Invalid type");
1410 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1413 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1414 if (Record.size() < 1)
1415 return error("Invalid record");
1416 SmallVector<Type*, 8> EltTys;
1417 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1418 if (Type *T = getTypeByID(Record[i]))
1419 EltTys.push_back(T);
1423 if (EltTys.size() != Record.size()-1)
1424 return error("Invalid type");
1425 ResultTy = StructType::get(Context, EltTys, Record[0]);
1428 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1429 if (convertToString(Record, 0, TypeName))
1430 return error("Invalid record");
1433 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1434 if (Record.size() < 1)
1435 return error("Invalid record");
1437 if (NumRecords >= TypeList.size())
1438 return error("Invalid TYPE table");
1440 // Check to see if this was forward referenced, if so fill in the temp.
1441 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1443 Res->setName(TypeName);
1444 TypeList[NumRecords] = nullptr;
1445 } else // Otherwise, create a new struct.
1446 Res = createIdentifiedStructType(Context, TypeName);
1449 SmallVector<Type*, 8> EltTys;
1450 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1451 if (Type *T = getTypeByID(Record[i]))
1452 EltTys.push_back(T);
1456 if (EltTys.size() != Record.size()-1)
1457 return error("Invalid record");
1458 Res->setBody(EltTys, Record[0]);
1462 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1463 if (Record.size() != 1)
1464 return error("Invalid record");
1466 if (NumRecords >= TypeList.size())
1467 return error("Invalid TYPE table");
1469 // Check to see if this was forward referenced, if so fill in the temp.
1470 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1472 Res->setName(TypeName);
1473 TypeList[NumRecords] = nullptr;
1474 } else // Otherwise, create a new struct with no body.
1475 Res = createIdentifiedStructType(Context, TypeName);
1480 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1481 if (Record.size() < 2)
1482 return error("Invalid record");
1483 ResultTy = getTypeByID(Record[1]);
1484 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1485 return error("Invalid type");
1486 ResultTy = ArrayType::get(ResultTy, Record[0]);
1488 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1489 if (Record.size() < 2)
1490 return error("Invalid record");
1492 return error("Invalid vector length");
1493 ResultTy = getTypeByID(Record[1]);
1494 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1495 return error("Invalid type");
1496 ResultTy = VectorType::get(ResultTy, Record[0]);
1500 if (NumRecords >= TypeList.size())
1501 return error("Invalid TYPE table");
1502 if (TypeList[NumRecords])
1504 "Invalid TYPE table: Only named structs can be forward referenced");
1505 assert(ResultTy && "Didn't read a type?");
1506 TypeList[NumRecords++] = ResultTy;
1510 std::error_code BitcodeReader::parseValueSymbolTable() {
1511 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1512 return error("Invalid record");
1514 SmallVector<uint64_t, 64> Record;
1516 Triple TT(TheModule->getTargetTriple());
1518 // Read all the records for this value table.
1519 SmallString<128> ValueName;
1521 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1523 switch (Entry.Kind) {
1524 case BitstreamEntry::SubBlock: // Handled for us already.
1525 case BitstreamEntry::Error:
1526 return error("Malformed block");
1527 case BitstreamEntry::EndBlock:
1528 return std::error_code();
1529 case BitstreamEntry::Record:
1530 // The interesting case.
1536 switch (Stream.readRecord(Entry.ID, Record)) {
1537 default: // Default behavior: unknown type.
1539 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1540 if (convertToString(Record, 1, ValueName))
1541 return error("Invalid record");
1542 unsigned ValueID = Record[0];
1543 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1544 return error("Invalid record");
1545 Value *V = ValueList[ValueID];
1547 V->setName(StringRef(ValueName.data(), ValueName.size()));
1548 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1549 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1550 if (TT.isOSBinFormatMachO())
1551 GO->setComdat(nullptr);
1553 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1559 case bitc::VST_CODE_BBENTRY: {
1560 if (convertToString(Record, 1, ValueName))
1561 return error("Invalid record");
1562 BasicBlock *BB = getBasicBlock(Record[0]);
1564 return error("Invalid record");
1566 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1574 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1576 std::error_code BitcodeReader::parseMetadata() {
1577 IsMetadataMaterialized = true;
1578 unsigned NextMDValueNo = MDValueList.size();
1580 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1581 return error("Invalid record");
1583 SmallVector<uint64_t, 64> Record;
1586 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1587 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1589 return getMD(ID - 1);
1592 auto getMDString = [&](unsigned ID) -> MDString *{
1593 // This requires that the ID is not really a forward reference. In
1594 // particular, the MDString must already have been resolved.
1595 return cast_or_null<MDString>(getMDOrNull(ID));
1598 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1599 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1601 // Read all the records.
1603 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1605 switch (Entry.Kind) {
1606 case BitstreamEntry::SubBlock: // Handled for us already.
1607 case BitstreamEntry::Error:
1608 return error("Malformed block");
1609 case BitstreamEntry::EndBlock:
1610 MDValueList.tryToResolveCycles();
1611 return std::error_code();
1612 case BitstreamEntry::Record:
1613 // The interesting case.
1619 unsigned Code = Stream.readRecord(Entry.ID, Record);
1620 bool IsDistinct = false;
1622 default: // Default behavior: ignore.
1624 case bitc::METADATA_NAME: {
1625 // Read name of the named metadata.
1626 SmallString<8> Name(Record.begin(), Record.end());
1628 Code = Stream.ReadCode();
1630 unsigned NextBitCode = Stream.readRecord(Code, Record);
1631 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1632 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1634 // Read named metadata elements.
1635 unsigned Size = Record.size();
1636 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1637 for (unsigned i = 0; i != Size; ++i) {
1638 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1640 return error("Invalid record");
1641 NMD->addOperand(MD);
1645 case bitc::METADATA_OLD_FN_NODE: {
1646 // FIXME: Remove in 4.0.
1647 // This is a LocalAsMetadata record, the only type of function-local
1649 if (Record.size() % 2 == 1)
1650 return error("Invalid record");
1652 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1653 // to be legal, but there's no upgrade path.
1654 auto dropRecord = [&] {
1655 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1657 if (Record.size() != 2) {
1662 Type *Ty = getTypeByID(Record[0]);
1663 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1668 MDValueList.assignValue(
1669 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1673 case bitc::METADATA_OLD_NODE: {
1674 // FIXME: Remove in 4.0.
1675 if (Record.size() % 2 == 1)
1676 return error("Invalid record");
1678 unsigned Size = Record.size();
1679 SmallVector<Metadata *, 8> Elts;
1680 for (unsigned i = 0; i != Size; i += 2) {
1681 Type *Ty = getTypeByID(Record[i]);
1683 return error("Invalid record");
1684 if (Ty->isMetadataTy())
1685 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1686 else if (!Ty->isVoidTy()) {
1688 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1689 assert(isa<ConstantAsMetadata>(MD) &&
1690 "Expected non-function-local metadata");
1693 Elts.push_back(nullptr);
1695 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1698 case bitc::METADATA_VALUE: {
1699 if (Record.size() != 2)
1700 return error("Invalid record");
1702 Type *Ty = getTypeByID(Record[0]);
1703 if (Ty->isMetadataTy() || Ty->isVoidTy())
1704 return error("Invalid record");
1706 MDValueList.assignValue(
1707 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1711 case bitc::METADATA_DISTINCT_NODE:
1714 case bitc::METADATA_NODE: {
1715 SmallVector<Metadata *, 8> Elts;
1716 Elts.reserve(Record.size());
1717 for (unsigned ID : Record)
1718 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1719 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1720 : MDNode::get(Context, Elts),
1724 case bitc::METADATA_LOCATION: {
1725 if (Record.size() != 5)
1726 return error("Invalid record");
1728 unsigned Line = Record[1];
1729 unsigned Column = Record[2];
1730 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1731 Metadata *InlinedAt =
1732 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1733 MDValueList.assignValue(
1734 GET_OR_DISTINCT(DILocation, Record[0],
1735 (Context, Line, Column, Scope, InlinedAt)),
1739 case bitc::METADATA_GENERIC_DEBUG: {
1740 if (Record.size() < 4)
1741 return error("Invalid record");
1743 unsigned Tag = Record[1];
1744 unsigned Version = Record[2];
1746 if (Tag >= 1u << 16 || Version != 0)
1747 return error("Invalid record");
1749 auto *Header = getMDString(Record[3]);
1750 SmallVector<Metadata *, 8> DwarfOps;
1751 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1752 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1754 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1755 (Context, Tag, Header, DwarfOps)),
1759 case bitc::METADATA_SUBRANGE: {
1760 if (Record.size() != 3)
1761 return error("Invalid record");
1763 MDValueList.assignValue(
1764 GET_OR_DISTINCT(DISubrange, Record[0],
1765 (Context, Record[1], unrotateSign(Record[2]))),
1769 case bitc::METADATA_ENUMERATOR: {
1770 if (Record.size() != 3)
1771 return error("Invalid record");
1773 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1774 (Context, unrotateSign(Record[1]),
1775 getMDString(Record[2]))),
1779 case bitc::METADATA_BASIC_TYPE: {
1780 if (Record.size() != 6)
1781 return error("Invalid record");
1783 MDValueList.assignValue(
1784 GET_OR_DISTINCT(DIBasicType, Record[0],
1785 (Context, Record[1], getMDString(Record[2]),
1786 Record[3], Record[4], Record[5])),
1790 case bitc::METADATA_DERIVED_TYPE: {
1791 if (Record.size() != 12)
1792 return error("Invalid record");
1794 MDValueList.assignValue(
1795 GET_OR_DISTINCT(DIDerivedType, Record[0],
1796 (Context, Record[1], getMDString(Record[2]),
1797 getMDOrNull(Record[3]), Record[4],
1798 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1799 Record[7], Record[8], Record[9], Record[10],
1800 getMDOrNull(Record[11]))),
1804 case bitc::METADATA_COMPOSITE_TYPE: {
1805 if (Record.size() != 16)
1806 return error("Invalid record");
1808 MDValueList.assignValue(
1809 GET_OR_DISTINCT(DICompositeType, Record[0],
1810 (Context, Record[1], getMDString(Record[2]),
1811 getMDOrNull(Record[3]), Record[4],
1812 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1813 Record[7], Record[8], Record[9], Record[10],
1814 getMDOrNull(Record[11]), Record[12],
1815 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1816 getMDString(Record[15]))),
1820 case bitc::METADATA_SUBROUTINE_TYPE: {
1821 if (Record.size() != 3)
1822 return error("Invalid record");
1824 MDValueList.assignValue(
1825 GET_OR_DISTINCT(DISubroutineType, Record[0],
1826 (Context, Record[1], getMDOrNull(Record[2]))),
1830 case bitc::METADATA_FILE: {
1831 if (Record.size() != 3)
1832 return error("Invalid record");
1834 MDValueList.assignValue(
1835 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1836 getMDString(Record[2]))),
1840 case bitc::METADATA_COMPILE_UNIT: {
1841 if (Record.size() < 14 || Record.size() > 15)
1842 return error("Invalid record");
1844 MDValueList.assignValue(
1846 DICompileUnit, Record[0],
1847 (Context, Record[1], getMDOrNull(Record[2]),
1848 getMDString(Record[3]), Record[4], getMDString(Record[5]),
1849 Record[6], getMDString(Record[7]), Record[8],
1850 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1851 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1852 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14])),
1856 case bitc::METADATA_SUBPROGRAM: {
1857 if (Record.size() != 19)
1858 return error("Invalid record");
1860 MDValueList.assignValue(
1862 DISubprogram, Record[0],
1863 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1864 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1865 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1866 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1867 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1868 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1872 case bitc::METADATA_LEXICAL_BLOCK: {
1873 if (Record.size() != 5)
1874 return error("Invalid record");
1876 MDValueList.assignValue(
1877 GET_OR_DISTINCT(DILexicalBlock, Record[0],
1878 (Context, getMDOrNull(Record[1]),
1879 getMDOrNull(Record[2]), Record[3], Record[4])),
1883 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1884 if (Record.size() != 4)
1885 return error("Invalid record");
1887 MDValueList.assignValue(
1888 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1889 (Context, getMDOrNull(Record[1]),
1890 getMDOrNull(Record[2]), Record[3])),
1894 case bitc::METADATA_NAMESPACE: {
1895 if (Record.size() != 5)
1896 return error("Invalid record");
1898 MDValueList.assignValue(
1899 GET_OR_DISTINCT(DINamespace, Record[0],
1900 (Context, getMDOrNull(Record[1]),
1901 getMDOrNull(Record[2]), getMDString(Record[3]),
1906 case bitc::METADATA_TEMPLATE_TYPE: {
1907 if (Record.size() != 3)
1908 return error("Invalid record");
1910 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1912 (Context, getMDString(Record[1]),
1913 getMDOrNull(Record[2]))),
1917 case bitc::METADATA_TEMPLATE_VALUE: {
1918 if (Record.size() != 5)
1919 return error("Invalid record");
1921 MDValueList.assignValue(
1922 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1923 (Context, Record[1], getMDString(Record[2]),
1924 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1928 case bitc::METADATA_GLOBAL_VAR: {
1929 if (Record.size() != 11)
1930 return error("Invalid record");
1932 MDValueList.assignValue(
1933 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1934 (Context, getMDOrNull(Record[1]),
1935 getMDString(Record[2]), getMDString(Record[3]),
1936 getMDOrNull(Record[4]), Record[5],
1937 getMDOrNull(Record[6]), Record[7], Record[8],
1938 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1942 case bitc::METADATA_LOCAL_VAR: {
1943 // 10th field is for the obseleted 'inlinedAt:' field.
1944 if (Record.size() != 9 && Record.size() != 10)
1945 return error("Invalid record");
1947 MDValueList.assignValue(
1948 GET_OR_DISTINCT(DILocalVariable, Record[0],
1949 (Context, Record[1], getMDOrNull(Record[2]),
1950 getMDString(Record[3]), getMDOrNull(Record[4]),
1951 Record[5], getMDOrNull(Record[6]), Record[7],
1956 case bitc::METADATA_EXPRESSION: {
1957 if (Record.size() < 1)
1958 return error("Invalid record");
1960 MDValueList.assignValue(
1961 GET_OR_DISTINCT(DIExpression, Record[0],
1962 (Context, makeArrayRef(Record).slice(1))),
1966 case bitc::METADATA_OBJC_PROPERTY: {
1967 if (Record.size() != 8)
1968 return error("Invalid record");
1970 MDValueList.assignValue(
1971 GET_OR_DISTINCT(DIObjCProperty, Record[0],
1972 (Context, getMDString(Record[1]),
1973 getMDOrNull(Record[2]), Record[3],
1974 getMDString(Record[4]), getMDString(Record[5]),
1975 Record[6], getMDOrNull(Record[7]))),
1979 case bitc::METADATA_IMPORTED_ENTITY: {
1980 if (Record.size() != 6)
1981 return error("Invalid record");
1983 MDValueList.assignValue(
1984 GET_OR_DISTINCT(DIImportedEntity, Record[0],
1985 (Context, Record[1], getMDOrNull(Record[2]),
1986 getMDOrNull(Record[3]), Record[4],
1987 getMDString(Record[5]))),
1991 case bitc::METADATA_STRING: {
1992 std::string String(Record.begin(), Record.end());
1993 llvm::UpgradeMDStringConstant(String);
1994 Metadata *MD = MDString::get(Context, String);
1995 MDValueList.assignValue(MD, NextMDValueNo++);
1998 case bitc::METADATA_KIND: {
1999 if (Record.size() < 2)
2000 return error("Invalid record");
2002 unsigned Kind = Record[0];
2003 SmallString<8> Name(Record.begin()+1, Record.end());
2005 unsigned NewKind = TheModule->getMDKindID(Name.str());
2006 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2007 return error("Conflicting METADATA_KIND records");
2012 #undef GET_OR_DISTINCT
2015 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2017 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2022 // There is no such thing as -0 with integers. "-0" really means MININT.
2026 /// Resolve all of the initializers for global values and aliases that we can.
2027 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2028 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2029 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2030 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2031 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2032 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2034 GlobalInitWorklist.swap(GlobalInits);
2035 AliasInitWorklist.swap(AliasInits);
2036 FunctionPrefixWorklist.swap(FunctionPrefixes);
2037 FunctionPrologueWorklist.swap(FunctionPrologues);
2038 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2040 while (!GlobalInitWorklist.empty()) {
2041 unsigned ValID = GlobalInitWorklist.back().second;
2042 if (ValID >= ValueList.size()) {
2043 // Not ready to resolve this yet, it requires something later in the file.
2044 GlobalInits.push_back(GlobalInitWorklist.back());
2046 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2047 GlobalInitWorklist.back().first->setInitializer(C);
2049 return error("Expected a constant");
2051 GlobalInitWorklist.pop_back();
2054 while (!AliasInitWorklist.empty()) {
2055 unsigned ValID = AliasInitWorklist.back().second;
2056 if (ValID >= ValueList.size()) {
2057 AliasInits.push_back(AliasInitWorklist.back());
2059 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2061 return error("Expected a constant");
2062 GlobalAlias *Alias = AliasInitWorklist.back().first;
2063 if (C->getType() != Alias->getType())
2064 return error("Alias and aliasee types don't match");
2065 Alias->setAliasee(C);
2067 AliasInitWorklist.pop_back();
2070 while (!FunctionPrefixWorklist.empty()) {
2071 unsigned ValID = FunctionPrefixWorklist.back().second;
2072 if (ValID >= ValueList.size()) {
2073 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2075 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2076 FunctionPrefixWorklist.back().first->setPrefixData(C);
2078 return error("Expected a constant");
2080 FunctionPrefixWorklist.pop_back();
2083 while (!FunctionPrologueWorklist.empty()) {
2084 unsigned ValID = FunctionPrologueWorklist.back().second;
2085 if (ValID >= ValueList.size()) {
2086 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2088 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2089 FunctionPrologueWorklist.back().first->setPrologueData(C);
2091 return error("Expected a constant");
2093 FunctionPrologueWorklist.pop_back();
2096 while (!FunctionPersonalityFnWorklist.empty()) {
2097 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2098 if (ValID >= ValueList.size()) {
2099 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2101 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2102 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2104 return error("Expected a constant");
2106 FunctionPersonalityFnWorklist.pop_back();
2109 return std::error_code();
2112 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2113 SmallVector<uint64_t, 8> Words(Vals.size());
2114 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2115 BitcodeReader::decodeSignRotatedValue);
2117 return APInt(TypeBits, Words);
2120 std::error_code BitcodeReader::parseConstants() {
2121 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2122 return error("Invalid record");
2124 SmallVector<uint64_t, 64> Record;
2126 // Read all the records for this value table.
2127 Type *CurTy = Type::getInt32Ty(Context);
2128 unsigned NextCstNo = ValueList.size();
2130 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2132 switch (Entry.Kind) {
2133 case BitstreamEntry::SubBlock: // Handled for us already.
2134 case BitstreamEntry::Error:
2135 return error("Malformed block");
2136 case BitstreamEntry::EndBlock:
2137 if (NextCstNo != ValueList.size())
2138 return error("Invalid ronstant reference");
2140 // Once all the constants have been read, go through and resolve forward
2142 ValueList.resolveConstantForwardRefs();
2143 return std::error_code();
2144 case BitstreamEntry::Record:
2145 // The interesting case.
2152 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2154 default: // Default behavior: unknown constant
2155 case bitc::CST_CODE_UNDEF: // UNDEF
2156 V = UndefValue::get(CurTy);
2158 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2160 return error("Invalid record");
2161 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2162 return error("Invalid record");
2163 CurTy = TypeList[Record[0]];
2164 continue; // Skip the ValueList manipulation.
2165 case bitc::CST_CODE_NULL: // NULL
2166 V = Constant::getNullValue(CurTy);
2168 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2169 if (!CurTy->isIntegerTy() || Record.empty())
2170 return error("Invalid record");
2171 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2173 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2174 if (!CurTy->isIntegerTy() || Record.empty())
2175 return error("Invalid record");
2178 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2179 V = ConstantInt::get(Context, VInt);
2183 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2185 return error("Invalid record");
2186 if (CurTy->isHalfTy())
2187 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2188 APInt(16, (uint16_t)Record[0])));
2189 else if (CurTy->isFloatTy())
2190 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2191 APInt(32, (uint32_t)Record[0])));
2192 else if (CurTy->isDoubleTy())
2193 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2194 APInt(64, Record[0])));
2195 else if (CurTy->isX86_FP80Ty()) {
2196 // Bits are not stored the same way as a normal i80 APInt, compensate.
2197 uint64_t Rearrange[2];
2198 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2199 Rearrange[1] = Record[0] >> 48;
2200 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2201 APInt(80, Rearrange)));
2202 } else if (CurTy->isFP128Ty())
2203 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2204 APInt(128, Record)));
2205 else if (CurTy->isPPC_FP128Ty())
2206 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2207 APInt(128, Record)));
2209 V = UndefValue::get(CurTy);
2213 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2215 return error("Invalid record");
2217 unsigned Size = Record.size();
2218 SmallVector<Constant*, 16> Elts;
2220 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2221 for (unsigned i = 0; i != Size; ++i)
2222 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2223 STy->getElementType(i)));
2224 V = ConstantStruct::get(STy, Elts);
2225 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2226 Type *EltTy = ATy->getElementType();
2227 for (unsigned i = 0; i != Size; ++i)
2228 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2229 V = ConstantArray::get(ATy, Elts);
2230 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2231 Type *EltTy = VTy->getElementType();
2232 for (unsigned i = 0; i != Size; ++i)
2233 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2234 V = ConstantVector::get(Elts);
2236 V = UndefValue::get(CurTy);
2240 case bitc::CST_CODE_STRING: // STRING: [values]
2241 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2243 return error("Invalid record");
2245 SmallString<16> Elts(Record.begin(), Record.end());
2246 V = ConstantDataArray::getString(Context, Elts,
2247 BitCode == bitc::CST_CODE_CSTRING);
2250 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2252 return error("Invalid record");
2254 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2255 unsigned Size = Record.size();
2257 if (EltTy->isIntegerTy(8)) {
2258 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2259 if (isa<VectorType>(CurTy))
2260 V = ConstantDataVector::get(Context, Elts);
2262 V = ConstantDataArray::get(Context, Elts);
2263 } else if (EltTy->isIntegerTy(16)) {
2264 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2265 if (isa<VectorType>(CurTy))
2266 V = ConstantDataVector::get(Context, Elts);
2268 V = ConstantDataArray::get(Context, Elts);
2269 } else if (EltTy->isIntegerTy(32)) {
2270 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2271 if (isa<VectorType>(CurTy))
2272 V = ConstantDataVector::get(Context, Elts);
2274 V = ConstantDataArray::get(Context, Elts);
2275 } else if (EltTy->isIntegerTy(64)) {
2276 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2277 if (isa<VectorType>(CurTy))
2278 V = ConstantDataVector::get(Context, Elts);
2280 V = ConstantDataArray::get(Context, Elts);
2281 } else if (EltTy->isFloatTy()) {
2282 SmallVector<float, 16> Elts(Size);
2283 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2284 if (isa<VectorType>(CurTy))
2285 V = ConstantDataVector::get(Context, Elts);
2287 V = ConstantDataArray::get(Context, Elts);
2288 } else if (EltTy->isDoubleTy()) {
2289 SmallVector<double, 16> Elts(Size);
2290 std::transform(Record.begin(), Record.end(), Elts.begin(),
2292 if (isa<VectorType>(CurTy))
2293 V = ConstantDataVector::get(Context, Elts);
2295 V = ConstantDataArray::get(Context, Elts);
2297 return error("Invalid type for value");
2302 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2303 if (Record.size() < 3)
2304 return error("Invalid record");
2305 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2307 V = UndefValue::get(CurTy); // Unknown binop.
2309 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2310 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2312 if (Record.size() >= 4) {
2313 if (Opc == Instruction::Add ||
2314 Opc == Instruction::Sub ||
2315 Opc == Instruction::Mul ||
2316 Opc == Instruction::Shl) {
2317 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2318 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2319 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2320 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2321 } else if (Opc == Instruction::SDiv ||
2322 Opc == Instruction::UDiv ||
2323 Opc == Instruction::LShr ||
2324 Opc == Instruction::AShr) {
2325 if (Record[3] & (1 << bitc::PEO_EXACT))
2326 Flags |= SDivOperator::IsExact;
2329 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2333 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2334 if (Record.size() < 3)
2335 return error("Invalid record");
2336 int Opc = getDecodedCastOpcode(Record[0]);
2338 V = UndefValue::get(CurTy); // Unknown cast.
2340 Type *OpTy = getTypeByID(Record[1]);
2342 return error("Invalid record");
2343 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2344 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2345 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2349 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2350 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2352 Type *PointeeType = nullptr;
2353 if (Record.size() % 2)
2354 PointeeType = getTypeByID(Record[OpNum++]);
2355 SmallVector<Constant*, 16> Elts;
2356 while (OpNum != Record.size()) {
2357 Type *ElTy = getTypeByID(Record[OpNum++]);
2359 return error("Invalid record");
2360 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2365 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2367 return error("Explicit gep operator type does not match pointee type "
2368 "of pointer operand");
2370 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2371 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2373 bitc::CST_CODE_CE_INBOUNDS_GEP);
2376 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2377 if (Record.size() < 3)
2378 return error("Invalid record");
2380 Type *SelectorTy = Type::getInt1Ty(Context);
2382 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2383 // vector. Otherwise, it must be a single bit.
2384 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2385 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2386 VTy->getNumElements());
2388 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2390 ValueList.getConstantFwdRef(Record[1],CurTy),
2391 ValueList.getConstantFwdRef(Record[2],CurTy));
2394 case bitc::CST_CODE_CE_EXTRACTELT
2395 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2396 if (Record.size() < 3)
2397 return error("Invalid record");
2399 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2401 return error("Invalid record");
2402 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2403 Constant *Op1 = nullptr;
2404 if (Record.size() == 4) {
2405 Type *IdxTy = getTypeByID(Record[2]);
2407 return error("Invalid record");
2408 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2409 } else // TODO: Remove with llvm 4.0
2410 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2412 return error("Invalid record");
2413 V = ConstantExpr::getExtractElement(Op0, Op1);
2416 case bitc::CST_CODE_CE_INSERTELT
2417 : { // CE_INSERTELT: [opval, opval, opty, opval]
2418 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2419 if (Record.size() < 3 || !OpTy)
2420 return error("Invalid record");
2421 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2422 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2423 OpTy->getElementType());
2424 Constant *Op2 = nullptr;
2425 if (Record.size() == 4) {
2426 Type *IdxTy = getTypeByID(Record[2]);
2428 return error("Invalid record");
2429 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2430 } else // TODO: Remove with llvm 4.0
2431 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2433 return error("Invalid record");
2434 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2437 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2438 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2439 if (Record.size() < 3 || !OpTy)
2440 return error("Invalid record");
2441 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2442 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2443 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2444 OpTy->getNumElements());
2445 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2446 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2449 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2450 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2452 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2453 if (Record.size() < 4 || !RTy || !OpTy)
2454 return error("Invalid record");
2455 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2456 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2457 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2458 RTy->getNumElements());
2459 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2460 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2463 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2464 if (Record.size() < 4)
2465 return error("Invalid record");
2466 Type *OpTy = getTypeByID(Record[0]);
2468 return error("Invalid record");
2469 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2470 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2472 if (OpTy->isFPOrFPVectorTy())
2473 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2475 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2478 // This maintains backward compatibility, pre-asm dialect keywords.
2479 // FIXME: Remove with the 4.0 release.
2480 case bitc::CST_CODE_INLINEASM_OLD: {
2481 if (Record.size() < 2)
2482 return error("Invalid record");
2483 std::string AsmStr, ConstrStr;
2484 bool HasSideEffects = Record[0] & 1;
2485 bool IsAlignStack = Record[0] >> 1;
2486 unsigned AsmStrSize = Record[1];
2487 if (2+AsmStrSize >= Record.size())
2488 return error("Invalid record");
2489 unsigned ConstStrSize = Record[2+AsmStrSize];
2490 if (3+AsmStrSize+ConstStrSize > Record.size())
2491 return error("Invalid record");
2493 for (unsigned i = 0; i != AsmStrSize; ++i)
2494 AsmStr += (char)Record[2+i];
2495 for (unsigned i = 0; i != ConstStrSize; ++i)
2496 ConstrStr += (char)Record[3+AsmStrSize+i];
2497 PointerType *PTy = cast<PointerType>(CurTy);
2498 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2499 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2502 // This version adds support for the asm dialect keywords (e.g.,
2504 case bitc::CST_CODE_INLINEASM: {
2505 if (Record.size() < 2)
2506 return error("Invalid record");
2507 std::string AsmStr, ConstrStr;
2508 bool HasSideEffects = Record[0] & 1;
2509 bool IsAlignStack = (Record[0] >> 1) & 1;
2510 unsigned AsmDialect = Record[0] >> 2;
2511 unsigned AsmStrSize = Record[1];
2512 if (2+AsmStrSize >= Record.size())
2513 return error("Invalid record");
2514 unsigned ConstStrSize = Record[2+AsmStrSize];
2515 if (3+AsmStrSize+ConstStrSize > Record.size())
2516 return error("Invalid record");
2518 for (unsigned i = 0; i != AsmStrSize; ++i)
2519 AsmStr += (char)Record[2+i];
2520 for (unsigned i = 0; i != ConstStrSize; ++i)
2521 ConstrStr += (char)Record[3+AsmStrSize+i];
2522 PointerType *PTy = cast<PointerType>(CurTy);
2523 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2524 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2525 InlineAsm::AsmDialect(AsmDialect));
2528 case bitc::CST_CODE_BLOCKADDRESS:{
2529 if (Record.size() < 3)
2530 return error("Invalid record");
2531 Type *FnTy = getTypeByID(Record[0]);
2533 return error("Invalid record");
2535 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2537 return error("Invalid record");
2539 // Don't let Fn get dematerialized.
2540 BlockAddressesTaken.insert(Fn);
2542 // If the function is already parsed we can insert the block address right
2545 unsigned BBID = Record[2];
2547 // Invalid reference to entry block.
2548 return error("Invalid ID");
2550 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2551 for (size_t I = 0, E = BBID; I != E; ++I) {
2553 return error("Invalid ID");
2558 // Otherwise insert a placeholder and remember it so it can be inserted
2559 // when the function is parsed.
2560 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2562 BasicBlockFwdRefQueue.push_back(Fn);
2563 if (FwdBBs.size() < BBID + 1)
2564 FwdBBs.resize(BBID + 1);
2566 FwdBBs[BBID] = BasicBlock::Create(Context);
2569 V = BlockAddress::get(Fn, BB);
2574 ValueList.assignValue(V, NextCstNo);
2579 std::error_code BitcodeReader::parseUseLists() {
2580 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2581 return error("Invalid record");
2583 // Read all the records.
2584 SmallVector<uint64_t, 64> Record;
2586 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2588 switch (Entry.Kind) {
2589 case BitstreamEntry::SubBlock: // Handled for us already.
2590 case BitstreamEntry::Error:
2591 return error("Malformed block");
2592 case BitstreamEntry::EndBlock:
2593 return std::error_code();
2594 case BitstreamEntry::Record:
2595 // The interesting case.
2599 // Read a use list record.
2602 switch (Stream.readRecord(Entry.ID, Record)) {
2603 default: // Default behavior: unknown type.
2605 case bitc::USELIST_CODE_BB:
2608 case bitc::USELIST_CODE_DEFAULT: {
2609 unsigned RecordLength = Record.size();
2610 if (RecordLength < 3)
2611 // Records should have at least an ID and two indexes.
2612 return error("Invalid record");
2613 unsigned ID = Record.back();
2618 assert(ID < FunctionBBs.size() && "Basic block not found");
2619 V = FunctionBBs[ID];
2622 unsigned NumUses = 0;
2623 SmallDenseMap<const Use *, unsigned, 16> Order;
2624 for (const Use &U : V->uses()) {
2625 if (++NumUses > Record.size())
2627 Order[&U] = Record[NumUses - 1];
2629 if (Order.size() != Record.size() || NumUses > Record.size())
2630 // Mismatches can happen if the functions are being materialized lazily
2631 // (out-of-order), or a value has been upgraded.
2634 V->sortUseList([&](const Use &L, const Use &R) {
2635 return Order.lookup(&L) < Order.lookup(&R);
2643 /// When we see the block for metadata, remember where it is and then skip it.
2644 /// This lets us lazily deserialize the metadata.
2645 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2646 // Save the current stream state.
2647 uint64_t CurBit = Stream.GetCurrentBitNo();
2648 DeferredMetadataInfo.push_back(CurBit);
2650 // Skip over the block for now.
2651 if (Stream.SkipBlock())
2652 return error("Invalid record");
2653 return std::error_code();
2656 std::error_code BitcodeReader::materializeMetadata() {
2657 for (uint64_t BitPos : DeferredMetadataInfo) {
2658 // Move the bit stream to the saved position.
2659 Stream.JumpToBit(BitPos);
2660 if (std::error_code EC = parseMetadata())
2663 DeferredMetadataInfo.clear();
2664 return std::error_code();
2667 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2669 /// When we see the block for a function body, remember where it is and then
2670 /// skip it. This lets us lazily deserialize the functions.
2671 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2672 // Get the function we are talking about.
2673 if (FunctionsWithBodies.empty())
2674 return error("Insufficient function protos");
2676 Function *Fn = FunctionsWithBodies.back();
2677 FunctionsWithBodies.pop_back();
2679 // Save the current stream state.
2680 uint64_t CurBit = Stream.GetCurrentBitNo();
2681 DeferredFunctionInfo[Fn] = CurBit;
2683 // Skip over the function block for now.
2684 if (Stream.SkipBlock())
2685 return error("Invalid record");
2686 return std::error_code();
2689 std::error_code BitcodeReader::globalCleanup() {
2690 // Patch the initializers for globals and aliases up.
2691 resolveGlobalAndAliasInits();
2692 if (!GlobalInits.empty() || !AliasInits.empty())
2693 return error("Malformed global initializer set");
2695 // Look for intrinsic functions which need to be upgraded at some point
2696 for (Function &F : *TheModule) {
2698 if (UpgradeIntrinsicFunction(&F, NewFn))
2699 UpgradedIntrinsics.push_back(std::make_pair(&F, NewFn));
2702 // Look for global variables which need to be renamed.
2703 for (GlobalVariable &GV : TheModule->globals())
2704 UpgradeGlobalVariable(&GV);
2706 // Force deallocation of memory for these vectors to favor the client that
2707 // want lazy deserialization.
2708 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2709 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2710 return std::error_code();
2713 std::error_code BitcodeReader::parseModule(bool Resume,
2714 bool ShouldLazyLoadMetadata) {
2716 Stream.JumpToBit(NextUnreadBit);
2717 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2718 return error("Invalid record");
2720 SmallVector<uint64_t, 64> Record;
2721 std::vector<std::string> SectionTable;
2722 std::vector<std::string> GCTable;
2724 // Read all the records for this module.
2726 BitstreamEntry Entry = Stream.advance();
2728 switch (Entry.Kind) {
2729 case BitstreamEntry::Error:
2730 return error("Malformed block");
2731 case BitstreamEntry::EndBlock:
2732 return globalCleanup();
2734 case BitstreamEntry::SubBlock:
2736 default: // Skip unknown content.
2737 if (Stream.SkipBlock())
2738 return error("Invalid record");
2740 case bitc::BLOCKINFO_BLOCK_ID:
2741 if (Stream.ReadBlockInfoBlock())
2742 return error("Malformed block");
2744 case bitc::PARAMATTR_BLOCK_ID:
2745 if (std::error_code EC = parseAttributeBlock())
2748 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2749 if (std::error_code EC = parseAttributeGroupBlock())
2752 case bitc::TYPE_BLOCK_ID_NEW:
2753 if (std::error_code EC = parseTypeTable())
2756 case bitc::VALUE_SYMTAB_BLOCK_ID:
2757 if (std::error_code EC = parseValueSymbolTable())
2759 SeenValueSymbolTable = true;
2761 case bitc::CONSTANTS_BLOCK_ID:
2762 if (std::error_code EC = parseConstants())
2764 if (std::error_code EC = resolveGlobalAndAliasInits())
2767 case bitc::METADATA_BLOCK_ID:
2768 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2769 if (std::error_code EC = rememberAndSkipMetadata())
2773 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2774 if (std::error_code EC = parseMetadata())
2777 case bitc::FUNCTION_BLOCK_ID:
2778 // If this is the first function body we've seen, reverse the
2779 // FunctionsWithBodies list.
2780 if (!SeenFirstFunctionBody) {
2781 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2782 if (std::error_code EC = globalCleanup())
2784 SeenFirstFunctionBody = true;
2787 if (std::error_code EC = rememberAndSkipFunctionBody())
2789 // Suspend parsing when we reach the function bodies. Subsequent
2790 // materialization calls will resume it when necessary. If the bitcode
2791 // file is old, the symbol table will be at the end instead and will not
2792 // have been seen yet. In this case, just finish the parse now.
2793 if (SeenValueSymbolTable) {
2794 NextUnreadBit = Stream.GetCurrentBitNo();
2795 return std::error_code();
2798 case bitc::USELIST_BLOCK_ID:
2799 if (std::error_code EC = parseUseLists())
2805 case BitstreamEntry::Record:
2806 // The interesting case.
2812 switch (Stream.readRecord(Entry.ID, Record)) {
2813 default: break; // Default behavior, ignore unknown content.
2814 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2815 if (Record.size() < 1)
2816 return error("Invalid record");
2817 // Only version #0 and #1 are supported so far.
2818 unsigned module_version = Record[0];
2819 switch (module_version) {
2821 return error("Invalid value");
2823 UseRelativeIDs = false;
2826 UseRelativeIDs = true;
2831 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2833 if (convertToString(Record, 0, S))
2834 return error("Invalid record");
2835 TheModule->setTargetTriple(S);
2838 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2840 if (convertToString(Record, 0, S))
2841 return error("Invalid record");
2842 TheModule->setDataLayout(S);
2845 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2847 if (convertToString(Record, 0, S))
2848 return error("Invalid record");
2849 TheModule->setModuleInlineAsm(S);
2852 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2853 // FIXME: Remove in 4.0.
2855 if (convertToString(Record, 0, S))
2856 return error("Invalid record");
2860 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2862 if (convertToString(Record, 0, S))
2863 return error("Invalid record");
2864 SectionTable.push_back(S);
2867 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2869 if (convertToString(Record, 0, S))
2870 return error("Invalid record");
2871 GCTable.push_back(S);
2874 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2875 if (Record.size() < 2)
2876 return error("Invalid record");
2877 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2878 unsigned ComdatNameSize = Record[1];
2879 std::string ComdatName;
2880 ComdatName.reserve(ComdatNameSize);
2881 for (unsigned i = 0; i != ComdatNameSize; ++i)
2882 ComdatName += (char)Record[2 + i];
2883 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2884 C->setSelectionKind(SK);
2885 ComdatList.push_back(C);
2888 // GLOBALVAR: [pointer type, isconst, initid,
2889 // linkage, alignment, section, visibility, threadlocal,
2890 // unnamed_addr, externally_initialized, dllstorageclass,
2892 case bitc::MODULE_CODE_GLOBALVAR: {
2893 if (Record.size() < 6)
2894 return error("Invalid record");
2895 Type *Ty = getTypeByID(Record[0]);
2897 return error("Invalid record");
2898 bool isConstant = Record[1] & 1;
2899 bool explicitType = Record[1] & 2;
2900 unsigned AddressSpace;
2902 AddressSpace = Record[1] >> 2;
2904 if (!Ty->isPointerTy())
2905 return error("Invalid type for value");
2906 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2907 Ty = cast<PointerType>(Ty)->getElementType();
2910 uint64_t RawLinkage = Record[3];
2911 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2913 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2915 std::string Section;
2917 if (Record[5]-1 >= SectionTable.size())
2918 return error("Invalid ID");
2919 Section = SectionTable[Record[5]-1];
2921 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2922 // Local linkage must have default visibility.
2923 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2924 // FIXME: Change to an error if non-default in 4.0.
2925 Visibility = getDecodedVisibility(Record[6]);
2927 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2928 if (Record.size() > 7)
2929 TLM = getDecodedThreadLocalMode(Record[7]);
2931 bool UnnamedAddr = false;
2932 if (Record.size() > 8)
2933 UnnamedAddr = Record[8];
2935 bool ExternallyInitialized = false;
2936 if (Record.size() > 9)
2937 ExternallyInitialized = Record[9];
2939 GlobalVariable *NewGV =
2940 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2941 TLM, AddressSpace, ExternallyInitialized);
2942 NewGV->setAlignment(Alignment);
2943 if (!Section.empty())
2944 NewGV->setSection(Section);
2945 NewGV->setVisibility(Visibility);
2946 NewGV->setUnnamedAddr(UnnamedAddr);
2948 if (Record.size() > 10)
2949 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2951 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2953 ValueList.push_back(NewGV);
2955 // Remember which value to use for the global initializer.
2956 if (unsigned InitID = Record[2])
2957 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2959 if (Record.size() > 11) {
2960 if (unsigned ComdatID = Record[11]) {
2961 if (ComdatID > ComdatList.size())
2962 return error("Invalid global variable comdat ID");
2963 NewGV->setComdat(ComdatList[ComdatID - 1]);
2965 } else if (hasImplicitComdat(RawLinkage)) {
2966 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2970 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2971 // alignment, section, visibility, gc, unnamed_addr,
2972 // prologuedata, dllstorageclass, comdat, prefixdata]
2973 case bitc::MODULE_CODE_FUNCTION: {
2974 if (Record.size() < 8)
2975 return error("Invalid record");
2976 Type *Ty = getTypeByID(Record[0]);
2978 return error("Invalid record");
2979 if (auto *PTy = dyn_cast<PointerType>(Ty))
2980 Ty = PTy->getElementType();
2981 auto *FTy = dyn_cast<FunctionType>(Ty);
2983 return error("Invalid type for value");
2985 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2988 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2989 bool isProto = Record[2];
2990 uint64_t RawLinkage = Record[3];
2991 Func->setLinkage(getDecodedLinkage(RawLinkage));
2992 Func->setAttributes(getAttributes(Record[4]));
2995 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2997 Func->setAlignment(Alignment);
2999 if (Record[6]-1 >= SectionTable.size())
3000 return error("Invalid ID");
3001 Func->setSection(SectionTable[Record[6]-1]);
3003 // Local linkage must have default visibility.
3004 if (!Func->hasLocalLinkage())
3005 // FIXME: Change to an error if non-default in 4.0.
3006 Func->setVisibility(getDecodedVisibility(Record[7]));
3007 if (Record.size() > 8 && Record[8]) {
3008 if (Record[8]-1 >= GCTable.size())
3009 return error("Invalid ID");
3010 Func->setGC(GCTable[Record[8]-1].c_str());
3012 bool UnnamedAddr = false;
3013 if (Record.size() > 9)
3014 UnnamedAddr = Record[9];
3015 Func->setUnnamedAddr(UnnamedAddr);
3016 if (Record.size() > 10 && Record[10] != 0)
3017 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3019 if (Record.size() > 11)
3020 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3022 upgradeDLLImportExportLinkage(Func, RawLinkage);
3024 if (Record.size() > 12) {
3025 if (unsigned ComdatID = Record[12]) {
3026 if (ComdatID > ComdatList.size())
3027 return error("Invalid function comdat ID");
3028 Func->setComdat(ComdatList[ComdatID - 1]);
3030 } else if (hasImplicitComdat(RawLinkage)) {
3031 Func->setComdat(reinterpret_cast<Comdat *>(1));
3034 if (Record.size() > 13 && Record[13] != 0)
3035 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3037 if (Record.size() > 14 && Record[14] != 0)
3038 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3040 ValueList.push_back(Func);
3042 // If this is a function with a body, remember the prototype we are
3043 // creating now, so that we can match up the body with them later.
3045 Func->setIsMaterializable(true);
3046 FunctionsWithBodies.push_back(Func);
3047 DeferredFunctionInfo[Func] = 0;
3051 // ALIAS: [alias type, aliasee val#, linkage]
3052 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3053 case bitc::MODULE_CODE_ALIAS: {
3054 if (Record.size() < 3)
3055 return error("Invalid record");
3056 Type *Ty = getTypeByID(Record[0]);
3058 return error("Invalid record");
3059 auto *PTy = dyn_cast<PointerType>(Ty);
3061 return error("Invalid type for value");
3064 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3065 // Old bitcode files didn't have visibility field.
3066 // Local linkage must have default visibility.
3067 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3068 // FIXME: Change to an error if non-default in 4.0.
3069 NewGA->setVisibility(getDecodedVisibility(Record[3]));
3070 if (Record.size() > 4)
3071 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
3073 upgradeDLLImportExportLinkage(NewGA, Record[2]);
3074 if (Record.size() > 5)
3075 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
3076 if (Record.size() > 6)
3077 NewGA->setUnnamedAddr(Record[6]);
3078 ValueList.push_back(NewGA);
3079 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3082 /// MODULE_CODE_PURGEVALS: [numvals]
3083 case bitc::MODULE_CODE_PURGEVALS:
3084 // Trim down the value list to the specified size.
3085 if (Record.size() < 1 || Record[0] > ValueList.size())
3086 return error("Invalid record");
3087 ValueList.shrinkTo(Record[0]);
3095 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3096 Module *M, bool ShouldLazyLoadMetadata) {
3099 if (std::error_code EC = initStream(std::move(Streamer)))
3102 // Sniff for the signature.
3103 if (Stream.Read(8) != 'B' ||
3104 Stream.Read(8) != 'C' ||
3105 Stream.Read(4) != 0x0 ||
3106 Stream.Read(4) != 0xC ||
3107 Stream.Read(4) != 0xE ||
3108 Stream.Read(4) != 0xD)
3109 return error("Invalid bitcode signature");
3111 // We expect a number of well-defined blocks, though we don't necessarily
3112 // need to understand them all.
3114 if (Stream.AtEndOfStream()) {
3115 // We didn't really read a proper Module.
3116 return error("Malformed IR file");
3119 BitstreamEntry Entry =
3120 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3122 if (Entry.Kind != BitstreamEntry::SubBlock)
3123 return error("Malformed block");
3125 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3126 return parseModule(false, ShouldLazyLoadMetadata);
3128 if (Stream.SkipBlock())
3129 return error("Invalid record");
3133 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3134 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3135 return error("Invalid record");
3137 SmallVector<uint64_t, 64> Record;
3140 // Read all the records for this module.
3142 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3144 switch (Entry.Kind) {
3145 case BitstreamEntry::SubBlock: // Handled for us already.
3146 case BitstreamEntry::Error:
3147 return error("Malformed block");
3148 case BitstreamEntry::EndBlock:
3150 case BitstreamEntry::Record:
3151 // The interesting case.
3156 switch (Stream.readRecord(Entry.ID, Record)) {
3157 default: break; // Default behavior, ignore unknown content.
3158 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3160 if (convertToString(Record, 0, S))
3161 return error("Invalid record");
3168 llvm_unreachable("Exit infinite loop");
3171 ErrorOr<std::string> BitcodeReader::parseTriple() {
3172 if (std::error_code EC = initStream(nullptr))
3175 // Sniff for the signature.
3176 if (Stream.Read(8) != 'B' ||
3177 Stream.Read(8) != 'C' ||
3178 Stream.Read(4) != 0x0 ||
3179 Stream.Read(4) != 0xC ||
3180 Stream.Read(4) != 0xE ||
3181 Stream.Read(4) != 0xD)
3182 return error("Invalid bitcode signature");
3184 // We expect a number of well-defined blocks, though we don't necessarily
3185 // need to understand them all.
3187 BitstreamEntry Entry = Stream.advance();
3189 switch (Entry.Kind) {
3190 case BitstreamEntry::Error:
3191 return error("Malformed block");
3192 case BitstreamEntry::EndBlock:
3193 return std::error_code();
3195 case BitstreamEntry::SubBlock:
3196 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3197 return parseModuleTriple();
3199 // Ignore other sub-blocks.
3200 if (Stream.SkipBlock())
3201 return error("Malformed block");
3204 case BitstreamEntry::Record:
3205 Stream.skipRecord(Entry.ID);
3211 /// Parse metadata attachments.
3212 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3213 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3214 return error("Invalid record");
3216 SmallVector<uint64_t, 64> Record;
3218 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3220 switch (Entry.Kind) {
3221 case BitstreamEntry::SubBlock: // Handled for us already.
3222 case BitstreamEntry::Error:
3223 return error("Malformed block");
3224 case BitstreamEntry::EndBlock:
3225 return std::error_code();
3226 case BitstreamEntry::Record:
3227 // The interesting case.
3231 // Read a metadata attachment record.
3233 switch (Stream.readRecord(Entry.ID, Record)) {
3234 default: // Default behavior: ignore.
3236 case bitc::METADATA_ATTACHMENT: {
3237 unsigned RecordLength = Record.size();
3239 return error("Invalid record");
3240 if (RecordLength % 2 == 0) {
3241 // A function attachment.
3242 for (unsigned I = 0; I != RecordLength; I += 2) {
3243 auto K = MDKindMap.find(Record[I]);
3244 if (K == MDKindMap.end())
3245 return error("Invalid ID");
3246 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3247 F.setMetadata(K->second, cast<MDNode>(MD));
3252 // An instruction attachment.
3253 Instruction *Inst = InstructionList[Record[0]];
3254 for (unsigned i = 1; i != RecordLength; i = i+2) {
3255 unsigned Kind = Record[i];
3256 DenseMap<unsigned, unsigned>::iterator I =
3257 MDKindMap.find(Kind);
3258 if (I == MDKindMap.end())
3259 return error("Invalid ID");
3260 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3261 if (isa<LocalAsMetadata>(Node))
3262 // Drop the attachment. This used to be legal, but there's no
3265 Inst->setMetadata(I->second, cast<MDNode>(Node));
3266 if (I->second == LLVMContext::MD_tbaa)
3267 InstsWithTBAATag.push_back(Inst);
3275 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3276 Type *ValType, Type *PtrType) {
3277 if (!isa<PointerType>(PtrType))
3278 return error(DH, "Load/Store operand is not a pointer type");
3279 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3281 if (ValType && ValType != ElemType)
3282 return error(DH, "Explicit load/store type does not match pointee type of "
3284 if (!PointerType::isLoadableOrStorableType(ElemType))
3285 return error(DH, "Cannot load/store from pointer");
3286 return std::error_code();
3289 /// Lazily parse the specified function body block.
3290 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3291 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3292 return error("Invalid record");
3294 InstructionList.clear();
3295 unsigned ModuleValueListSize = ValueList.size();
3296 unsigned ModuleMDValueListSize = MDValueList.size();
3298 // Add all the function arguments to the value table.
3299 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3300 ValueList.push_back(I);
3302 unsigned NextValueNo = ValueList.size();
3303 BasicBlock *CurBB = nullptr;
3304 unsigned CurBBNo = 0;
3307 auto getLastInstruction = [&]() -> Instruction * {
3308 if (CurBB && !CurBB->empty())
3309 return &CurBB->back();
3310 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3311 !FunctionBBs[CurBBNo - 1]->empty())
3312 return &FunctionBBs[CurBBNo - 1]->back();
3316 // Read all the records.
3317 SmallVector<uint64_t, 64> Record;
3319 BitstreamEntry Entry = Stream.advance();
3321 switch (Entry.Kind) {
3322 case BitstreamEntry::Error:
3323 return error("Malformed block");
3324 case BitstreamEntry::EndBlock:
3325 goto OutOfRecordLoop;
3327 case BitstreamEntry::SubBlock:
3329 default: // Skip unknown content.
3330 if (Stream.SkipBlock())
3331 return error("Invalid record");
3333 case bitc::CONSTANTS_BLOCK_ID:
3334 if (std::error_code EC = parseConstants())
3336 NextValueNo = ValueList.size();
3338 case bitc::VALUE_SYMTAB_BLOCK_ID:
3339 if (std::error_code EC = parseValueSymbolTable())
3342 case bitc::METADATA_ATTACHMENT_ID:
3343 if (std::error_code EC = parseMetadataAttachment(*F))
3346 case bitc::METADATA_BLOCK_ID:
3347 if (std::error_code EC = parseMetadata())
3350 case bitc::USELIST_BLOCK_ID:
3351 if (std::error_code EC = parseUseLists())
3357 case BitstreamEntry::Record:
3358 // The interesting case.
3364 Instruction *I = nullptr;
3365 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3367 default: // Default behavior: reject
3368 return error("Invalid value");
3369 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3370 if (Record.size() < 1 || Record[0] == 0)
3371 return error("Invalid record");
3372 // Create all the basic blocks for the function.
3373 FunctionBBs.resize(Record[0]);
3375 // See if anything took the address of blocks in this function.
3376 auto BBFRI = BasicBlockFwdRefs.find(F);
3377 if (BBFRI == BasicBlockFwdRefs.end()) {
3378 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3379 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3381 auto &BBRefs = BBFRI->second;
3382 // Check for invalid basic block references.
3383 if (BBRefs.size() > FunctionBBs.size())
3384 return error("Invalid ID");
3385 assert(!BBRefs.empty() && "Unexpected empty array");
3386 assert(!BBRefs.front() && "Invalid reference to entry block");
3387 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3389 if (I < RE && BBRefs[I]) {
3390 BBRefs[I]->insertInto(F);
3391 FunctionBBs[I] = BBRefs[I];
3393 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3396 // Erase from the table.
3397 BasicBlockFwdRefs.erase(BBFRI);
3400 CurBB = FunctionBBs[0];
3404 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3405 // This record indicates that the last instruction is at the same
3406 // location as the previous instruction with a location.
3407 I = getLastInstruction();
3410 return error("Invalid record");
3411 I->setDebugLoc(LastLoc);
3415 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3416 I = getLastInstruction();
3417 if (!I || Record.size() < 4)
3418 return error("Invalid record");
3420 unsigned Line = Record[0], Col = Record[1];
3421 unsigned ScopeID = Record[2], IAID = Record[3];
3423 MDNode *Scope = nullptr, *IA = nullptr;
3424 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3425 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3426 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3427 I->setDebugLoc(LastLoc);
3432 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3435 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3436 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3437 OpNum+1 > Record.size())
3438 return error("Invalid record");
3440 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3442 return error("Invalid record");
3443 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3444 InstructionList.push_back(I);
3445 if (OpNum < Record.size()) {
3446 if (Opc == Instruction::Add ||
3447 Opc == Instruction::Sub ||
3448 Opc == Instruction::Mul ||
3449 Opc == Instruction::Shl) {
3450 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3451 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3452 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3453 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3454 } else if (Opc == Instruction::SDiv ||
3455 Opc == Instruction::UDiv ||
3456 Opc == Instruction::LShr ||
3457 Opc == Instruction::AShr) {
3458 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3459 cast<BinaryOperator>(I)->setIsExact(true);
3460 } else if (isa<FPMathOperator>(I)) {
3462 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3463 FMF.setUnsafeAlgebra();
3464 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3466 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3468 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3469 FMF.setNoSignedZeros();
3470 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3471 FMF.setAllowReciprocal();
3473 I->setFastMathFlags(FMF);
3479 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3482 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3483 OpNum+2 != Record.size())
3484 return error("Invalid record");
3486 Type *ResTy = getTypeByID(Record[OpNum]);
3487 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3488 if (Opc == -1 || !ResTy)
3489 return error("Invalid record");
3490 Instruction *Temp = nullptr;
3491 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3493 InstructionList.push_back(Temp);
3494 CurBB->getInstList().push_back(Temp);
3497 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3499 InstructionList.push_back(I);
3502 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3503 case bitc::FUNC_CODE_INST_GEP_OLD:
3504 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3510 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3511 InBounds = Record[OpNum++];
3512 Ty = getTypeByID(Record[OpNum++]);
3514 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3519 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3520 return error("Invalid record");
3523 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3526 cast<SequentialType>(BasePtr->getType()->getScalarType())
3529 "Explicit gep type does not match pointee type of pointer operand");
3531 SmallVector<Value*, 16> GEPIdx;
3532 while (OpNum != Record.size()) {
3534 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3535 return error("Invalid record");
3536 GEPIdx.push_back(Op);
3539 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3541 InstructionList.push_back(I);
3543 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3547 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3548 // EXTRACTVAL: [opty, opval, n x indices]
3551 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3552 return error("Invalid record");
3554 unsigned RecSize = Record.size();
3555 if (OpNum == RecSize)
3556 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3558 SmallVector<unsigned, 4> EXTRACTVALIdx;
3559 Type *CurTy = Agg->getType();
3560 for (; OpNum != RecSize; ++OpNum) {
3561 bool IsArray = CurTy->isArrayTy();
3562 bool IsStruct = CurTy->isStructTy();
3563 uint64_t Index = Record[OpNum];
3565 if (!IsStruct && !IsArray)
3566 return error("EXTRACTVAL: Invalid type");
3567 if ((unsigned)Index != Index)
3568 return error("Invalid value");
3569 if (IsStruct && Index >= CurTy->subtypes().size())
3570 return error("EXTRACTVAL: Invalid struct index");
3571 if (IsArray && Index >= CurTy->getArrayNumElements())
3572 return error("EXTRACTVAL: Invalid array index");
3573 EXTRACTVALIdx.push_back((unsigned)Index);
3576 CurTy = CurTy->subtypes()[Index];
3578 CurTy = CurTy->subtypes()[0];
3581 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3582 InstructionList.push_back(I);
3586 case bitc::FUNC_CODE_INST_INSERTVAL: {
3587 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3590 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3591 return error("Invalid record");
3593 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3594 return error("Invalid record");
3596 unsigned RecSize = Record.size();
3597 if (OpNum == RecSize)
3598 return error("INSERTVAL: Invalid instruction with 0 indices");
3600 SmallVector<unsigned, 4> INSERTVALIdx;
3601 Type *CurTy = Agg->getType();
3602 for (; OpNum != RecSize; ++OpNum) {
3603 bool IsArray = CurTy->isArrayTy();
3604 bool IsStruct = CurTy->isStructTy();
3605 uint64_t Index = Record[OpNum];
3607 if (!IsStruct && !IsArray)
3608 return error("INSERTVAL: Invalid type");
3609 if ((unsigned)Index != Index)
3610 return error("Invalid value");
3611 if (IsStruct && Index >= CurTy->subtypes().size())
3612 return error("INSERTVAL: Invalid struct index");
3613 if (IsArray && Index >= CurTy->getArrayNumElements())
3614 return error("INSERTVAL: Invalid array index");
3616 INSERTVALIdx.push_back((unsigned)Index);
3618 CurTy = CurTy->subtypes()[Index];
3620 CurTy = CurTy->subtypes()[0];
3623 if (CurTy != Val->getType())
3624 return error("Inserted value type doesn't match aggregate type");
3626 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3627 InstructionList.push_back(I);
3631 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3632 // obsolete form of select
3633 // handles select i1 ... in old bitcode
3635 Value *TrueVal, *FalseVal, *Cond;
3636 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3637 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3638 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3639 return error("Invalid record");
3641 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3642 InstructionList.push_back(I);
3646 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3647 // new form of select
3648 // handles select i1 or select [N x i1]
3650 Value *TrueVal, *FalseVal, *Cond;
3651 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3652 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3653 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3654 return error("Invalid record");
3656 // select condition can be either i1 or [N x i1]
3657 if (VectorType* vector_type =
3658 dyn_cast<VectorType>(Cond->getType())) {
3660 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3661 return error("Invalid type for value");
3664 if (Cond->getType() != Type::getInt1Ty(Context))
3665 return error("Invalid type for value");
3668 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3669 InstructionList.push_back(I);
3673 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3676 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3677 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3678 return error("Invalid record");
3679 if (!Vec->getType()->isVectorTy())
3680 return error("Invalid type for value");
3681 I = ExtractElementInst::Create(Vec, Idx);
3682 InstructionList.push_back(I);
3686 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3688 Value *Vec, *Elt, *Idx;
3689 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3690 return error("Invalid record");
3691 if (!Vec->getType()->isVectorTy())
3692 return error("Invalid type for value");
3693 if (popValue(Record, OpNum, NextValueNo,
3694 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3695 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3696 return error("Invalid record");
3697 I = InsertElementInst::Create(Vec, Elt, Idx);
3698 InstructionList.push_back(I);
3702 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3704 Value *Vec1, *Vec2, *Mask;
3705 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3706 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3707 return error("Invalid record");
3709 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3710 return error("Invalid record");
3711 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3712 return error("Invalid type for value");
3713 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3714 InstructionList.push_back(I);
3718 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3719 // Old form of ICmp/FCmp returning bool
3720 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3721 // both legal on vectors but had different behaviour.
3722 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3723 // FCmp/ICmp returning bool or vector of bool
3727 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3728 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3729 OpNum+1 != Record.size())
3730 return error("Invalid record");
3732 if (LHS->getType()->isFPOrFPVectorTy())
3733 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3735 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3736 InstructionList.push_back(I);
3740 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3742 unsigned Size = Record.size();
3744 I = ReturnInst::Create(Context);
3745 InstructionList.push_back(I);
3750 Value *Op = nullptr;
3751 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3752 return error("Invalid record");
3753 if (OpNum != Record.size())
3754 return error("Invalid record");
3756 I = ReturnInst::Create(Context, Op);
3757 InstructionList.push_back(I);
3760 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3761 if (Record.size() != 1 && Record.size() != 3)
3762 return error("Invalid record");
3763 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3765 return error("Invalid record");
3767 if (Record.size() == 1) {
3768 I = BranchInst::Create(TrueDest);
3769 InstructionList.push_back(I);
3772 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3773 Value *Cond = getValue(Record, 2, NextValueNo,
3774 Type::getInt1Ty(Context));
3775 if (!FalseDest || !Cond)
3776 return error("Invalid record");
3777 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3778 InstructionList.push_back(I);
3782 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3784 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3785 // "New" SwitchInst format with case ranges. The changes to write this
3786 // format were reverted but we still recognize bitcode that uses it.
3787 // Hopefully someday we will have support for case ranges and can use
3788 // this format again.
3790 Type *OpTy = getTypeByID(Record[1]);
3791 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3793 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3794 BasicBlock *Default = getBasicBlock(Record[3]);
3795 if (!OpTy || !Cond || !Default)
3796 return error("Invalid record");
3798 unsigned NumCases = Record[4];
3800 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3801 InstructionList.push_back(SI);
3803 unsigned CurIdx = 5;
3804 for (unsigned i = 0; i != NumCases; ++i) {
3805 SmallVector<ConstantInt*, 1> CaseVals;
3806 unsigned NumItems = Record[CurIdx++];
3807 for (unsigned ci = 0; ci != NumItems; ++ci) {
3808 bool isSingleNumber = Record[CurIdx++];
3811 unsigned ActiveWords = 1;
3812 if (ValueBitWidth > 64)
3813 ActiveWords = Record[CurIdx++];
3814 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3816 CurIdx += ActiveWords;
3818 if (!isSingleNumber) {
3820 if (ValueBitWidth > 64)
3821 ActiveWords = Record[CurIdx++];
3822 APInt High = readWideAPInt(
3823 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3824 CurIdx += ActiveWords;
3826 // FIXME: It is not clear whether values in the range should be
3827 // compared as signed or unsigned values. The partially
3828 // implemented changes that used this format in the past used
3829 // unsigned comparisons.
3830 for ( ; Low.ule(High); ++Low)
3831 CaseVals.push_back(ConstantInt::get(Context, Low));
3833 CaseVals.push_back(ConstantInt::get(Context, Low));
3835 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3836 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3837 cve = CaseVals.end(); cvi != cve; ++cvi)
3838 SI->addCase(*cvi, DestBB);
3844 // Old SwitchInst format without case ranges.
3846 if (Record.size() < 3 || (Record.size() & 1) == 0)
3847 return error("Invalid record");
3848 Type *OpTy = getTypeByID(Record[0]);
3849 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3850 BasicBlock *Default = getBasicBlock(Record[2]);
3851 if (!OpTy || !Cond || !Default)
3852 return error("Invalid record");
3853 unsigned NumCases = (Record.size()-3)/2;
3854 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3855 InstructionList.push_back(SI);
3856 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3857 ConstantInt *CaseVal =
3858 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3859 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3860 if (!CaseVal || !DestBB) {
3862 return error("Invalid record");
3864 SI->addCase(CaseVal, DestBB);
3869 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3870 if (Record.size() < 2)
3871 return error("Invalid record");
3872 Type *OpTy = getTypeByID(Record[0]);
3873 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3874 if (!OpTy || !Address)
3875 return error("Invalid record");
3876 unsigned NumDests = Record.size()-2;
3877 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3878 InstructionList.push_back(IBI);
3879 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3880 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3881 IBI->addDestination(DestBB);
3884 return error("Invalid record");
3891 case bitc::FUNC_CODE_INST_INVOKE: {
3892 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3893 if (Record.size() < 4)
3894 return error("Invalid record");
3896 AttributeSet PAL = getAttributes(Record[OpNum++]);
3897 unsigned CCInfo = Record[OpNum++];
3898 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3899 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3901 FunctionType *FTy = nullptr;
3902 if (CCInfo >> 13 & 1 &&
3903 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3904 return error("Explicit invoke type is not a function type");
3907 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3908 return error("Invalid record");
3910 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3912 return error("Callee is not a pointer");
3914 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3916 return error("Callee is not of pointer to function type");
3917 } else if (CalleeTy->getElementType() != FTy)
3918 return error("Explicit invoke type does not match pointee type of "
3920 if (Record.size() < FTy->getNumParams() + OpNum)
3921 return error("Insufficient operands to call");
3923 SmallVector<Value*, 16> Ops;
3924 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3925 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3926 FTy->getParamType(i)));
3928 return error("Invalid record");
3931 if (!FTy->isVarArg()) {
3932 if (Record.size() != OpNum)
3933 return error("Invalid record");
3935 // Read type/value pairs for varargs params.
3936 while (OpNum != Record.size()) {
3938 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3939 return error("Invalid record");
3944 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3945 InstructionList.push_back(I);
3947 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
3948 cast<InvokeInst>(I)->setAttributes(PAL);
3951 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3953 Value *Val = nullptr;
3954 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3955 return error("Invalid record");
3956 I = ResumeInst::Create(Val);
3957 InstructionList.push_back(I);
3960 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3961 I = new UnreachableInst(Context);
3962 InstructionList.push_back(I);
3964 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3965 if (Record.size() < 1 || ((Record.size()-1)&1))
3966 return error("Invalid record");
3967 Type *Ty = getTypeByID(Record[0]);
3969 return error("Invalid record");
3971 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3972 InstructionList.push_back(PN);
3974 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3976 // With the new function encoding, it is possible that operands have
3977 // negative IDs (for forward references). Use a signed VBR
3978 // representation to keep the encoding small.
3980 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3982 V = getValue(Record, 1+i, NextValueNo, Ty);
3983 BasicBlock *BB = getBasicBlock(Record[2+i]);
3985 return error("Invalid record");
3986 PN->addIncoming(V, BB);
3992 case bitc::FUNC_CODE_INST_LANDINGPAD:
3993 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
3994 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3996 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
3997 if (Record.size() < 3)
3998 return error("Invalid record");
4000 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4001 if (Record.size() < 4)
4002 return error("Invalid record");
4004 Type *Ty = getTypeByID(Record[Idx++]);
4006 return error("Invalid record");
4007 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4008 Value *PersFn = nullptr;
4009 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4010 return error("Invalid record");
4012 if (!F->hasPersonalityFn())
4013 F->setPersonalityFn(cast<Constant>(PersFn));
4014 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4015 return error("Personality function mismatch");
4018 bool IsCleanup = !!Record[Idx++];
4019 unsigned NumClauses = Record[Idx++];
4020 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4021 LP->setCleanup(IsCleanup);
4022 for (unsigned J = 0; J != NumClauses; ++J) {
4023 LandingPadInst::ClauseType CT =
4024 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4027 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4029 return error("Invalid record");
4032 assert((CT != LandingPadInst::Catch ||
4033 !isa<ArrayType>(Val->getType())) &&
4034 "Catch clause has a invalid type!");
4035 assert((CT != LandingPadInst::Filter ||
4036 isa<ArrayType>(Val->getType())) &&
4037 "Filter clause has invalid type!");
4038 LP->addClause(cast<Constant>(Val));
4042 InstructionList.push_back(I);
4046 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4047 if (Record.size() != 4)
4048 return error("Invalid record");
4049 uint64_t AlignRecord = Record[3];
4050 const uint64_t InAllocaMask = uint64_t(1) << 5;
4051 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4052 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4053 bool InAlloca = AlignRecord & InAllocaMask;
4054 Type *Ty = getTypeByID(Record[0]);
4055 if ((AlignRecord & ExplicitTypeMask) == 0) {
4056 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4058 return error("Old-style alloca with a non-pointer type");
4059 Ty = PTy->getElementType();
4061 Type *OpTy = getTypeByID(Record[1]);
4062 Value *Size = getFnValueByID(Record[2], OpTy);
4064 if (std::error_code EC =
4065 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4069 return error("Invalid record");
4070 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4071 AI->setUsedWithInAlloca(InAlloca);
4073 InstructionList.push_back(I);
4076 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4079 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4080 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4081 return error("Invalid record");
4084 if (OpNum + 3 == Record.size())
4085 Ty = getTypeByID(Record[OpNum++]);
4086 if (std::error_code EC =
4087 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4090 Ty = cast<PointerType>(Op->getType())->getElementType();
4093 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4095 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4097 InstructionList.push_back(I);
4100 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4101 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4104 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4105 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4106 return error("Invalid record");
4109 if (OpNum + 5 == Record.size())
4110 Ty = getTypeByID(Record[OpNum++]);
4111 if (std::error_code EC =
4112 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4115 Ty = cast<PointerType>(Op->getType())->getElementType();
4117 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4118 if (Ordering == NotAtomic || Ordering == Release ||
4119 Ordering == AcquireRelease)
4120 return error("Invalid record");
4121 if (Ordering != NotAtomic && Record[OpNum] == 0)
4122 return error("Invalid record");
4123 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4126 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4128 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4130 InstructionList.push_back(I);
4133 case bitc::FUNC_CODE_INST_STORE:
4134 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4137 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4138 (BitCode == bitc::FUNC_CODE_INST_STORE
4139 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4140 : popValue(Record, OpNum, NextValueNo,
4141 cast<PointerType>(Ptr->getType())->getElementType(),
4143 OpNum + 2 != Record.size())
4144 return error("Invalid record");
4146 if (std::error_code EC = typeCheckLoadStoreInst(
4147 DiagnosticHandler, Val->getType(), Ptr->getType()))
4150 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4152 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4153 InstructionList.push_back(I);
4156 case bitc::FUNC_CODE_INST_STOREATOMIC:
4157 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4158 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4161 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4162 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4163 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4164 : popValue(Record, OpNum, NextValueNo,
4165 cast<PointerType>(Ptr->getType())->getElementType(),
4167 OpNum + 4 != Record.size())
4168 return error("Invalid record");
4170 if (std::error_code EC = typeCheckLoadStoreInst(
4171 DiagnosticHandler, Val->getType(), Ptr->getType()))
4173 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4174 if (Ordering == NotAtomic || Ordering == Acquire ||
4175 Ordering == AcquireRelease)
4176 return error("Invalid record");
4177 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4178 if (Ordering != NotAtomic && Record[OpNum] == 0)
4179 return error("Invalid record");
4182 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4184 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4185 InstructionList.push_back(I);
4188 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4189 case bitc::FUNC_CODE_INST_CMPXCHG: {
4190 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4191 // failureordering?, isweak?]
4193 Value *Ptr, *Cmp, *New;
4194 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4195 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4196 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4197 : popValue(Record, OpNum, NextValueNo,
4198 cast<PointerType>(Ptr->getType())->getElementType(),
4200 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4201 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4202 return error("Invalid record");
4203 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4204 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4205 return error("Invalid record");
4206 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4208 if (std::error_code EC = typeCheckLoadStoreInst(
4209 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4211 AtomicOrdering FailureOrdering;
4212 if (Record.size() < 7)
4214 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4216 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4218 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4220 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4222 if (Record.size() < 8) {
4223 // Before weak cmpxchgs existed, the instruction simply returned the
4224 // value loaded from memory, so bitcode files from that era will be
4225 // expecting the first component of a modern cmpxchg.
4226 CurBB->getInstList().push_back(I);
4227 I = ExtractValueInst::Create(I, 0);
4229 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4232 InstructionList.push_back(I);
4235 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4236 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4239 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4240 popValue(Record, OpNum, NextValueNo,
4241 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4242 OpNum+4 != Record.size())
4243 return error("Invalid record");
4244 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4245 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4246 Operation > AtomicRMWInst::LAST_BINOP)
4247 return error("Invalid record");
4248 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4249 if (Ordering == NotAtomic || Ordering == Unordered)
4250 return error("Invalid record");
4251 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4252 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4253 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4254 InstructionList.push_back(I);
4257 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4258 if (2 != Record.size())
4259 return error("Invalid record");
4260 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4261 if (Ordering == NotAtomic || Ordering == Unordered ||
4262 Ordering == Monotonic)
4263 return error("Invalid record");
4264 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4265 I = new FenceInst(Context, Ordering, SynchScope);
4266 InstructionList.push_back(I);
4269 case bitc::FUNC_CODE_INST_CALL: {
4270 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4271 if (Record.size() < 3)
4272 return error("Invalid record");
4275 AttributeSet PAL = getAttributes(Record[OpNum++]);
4276 unsigned CCInfo = Record[OpNum++];
4278 FunctionType *FTy = nullptr;
4279 if (CCInfo >> 15 & 1 &&
4280 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4281 return error("Explicit call type is not a function type");
4284 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4285 return error("Invalid record");
4287 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4289 return error("Callee is not a pointer type");
4291 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4293 return error("Callee is not of pointer to function type");
4294 } else if (OpTy->getElementType() != FTy)
4295 return error("Explicit call type does not match pointee type of "
4297 if (Record.size() < FTy->getNumParams() + OpNum)
4298 return error("Insufficient operands to call");
4300 SmallVector<Value*, 16> Args;
4301 // Read the fixed params.
4302 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4303 if (FTy->getParamType(i)->isLabelTy())
4304 Args.push_back(getBasicBlock(Record[OpNum]));
4306 Args.push_back(getValue(Record, OpNum, NextValueNo,
4307 FTy->getParamType(i)));
4309 return error("Invalid record");
4312 // Read type/value pairs for varargs params.
4313 if (!FTy->isVarArg()) {
4314 if (OpNum != Record.size())
4315 return error("Invalid record");
4317 while (OpNum != Record.size()) {
4319 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4320 return error("Invalid record");
4325 I = CallInst::Create(FTy, Callee, Args);
4326 InstructionList.push_back(I);
4327 cast<CallInst>(I)->setCallingConv(
4328 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4329 CallInst::TailCallKind TCK = CallInst::TCK_None;
4331 TCK = CallInst::TCK_Tail;
4332 if (CCInfo & (1 << 14))
4333 TCK = CallInst::TCK_MustTail;
4334 cast<CallInst>(I)->setTailCallKind(TCK);
4335 cast<CallInst>(I)->setAttributes(PAL);
4338 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4339 if (Record.size() < 3)
4340 return error("Invalid record");
4341 Type *OpTy = getTypeByID(Record[0]);
4342 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4343 Type *ResTy = getTypeByID(Record[2]);
4344 if (!OpTy || !Op || !ResTy)
4345 return error("Invalid record");
4346 I = new VAArgInst(Op, ResTy);
4347 InstructionList.push_back(I);
4352 // Add instruction to end of current BB. If there is no current BB, reject
4356 return error("Invalid instruction with no BB");
4358 CurBB->getInstList().push_back(I);
4360 // If this was a terminator instruction, move to the next block.
4361 if (isa<TerminatorInst>(I)) {
4363 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4366 // Non-void values get registered in the value table for future use.
4367 if (I && !I->getType()->isVoidTy())
4368 ValueList.assignValue(I, NextValueNo++);
4373 // Check the function list for unresolved values.
4374 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4375 if (!A->getParent()) {
4376 // We found at least one unresolved value. Nuke them all to avoid leaks.
4377 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4378 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4379 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4383 return error("Never resolved value found in function");
4387 // FIXME: Check for unresolved forward-declared metadata references
4388 // and clean up leaks.
4390 // Trim the value list down to the size it was before we parsed this function.
4391 ValueList.shrinkTo(ModuleValueListSize);
4392 MDValueList.shrinkTo(ModuleMDValueListSize);
4393 std::vector<BasicBlock*>().swap(FunctionBBs);
4394 return std::error_code();
4397 /// Find the function body in the bitcode stream
4398 std::error_code BitcodeReader::findFunctionInStream(
4400 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4401 while (DeferredFunctionInfoIterator->second == 0) {
4402 if (Stream.AtEndOfStream())
4403 return error("Could not find function in stream");
4404 // ParseModule will parse the next body in the stream and set its
4405 // position in the DeferredFunctionInfo map.
4406 if (std::error_code EC = parseModule(true))
4409 return std::error_code();
4412 //===----------------------------------------------------------------------===//
4413 // GVMaterializer implementation
4414 //===----------------------------------------------------------------------===//
4416 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4418 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4419 if (std::error_code EC = materializeMetadata())
4422 Function *F = dyn_cast<Function>(GV);
4423 // If it's not a function or is already material, ignore the request.
4424 if (!F || !F->isMaterializable())
4425 return std::error_code();
4427 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4428 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4429 // If its position is recorded as 0, its body is somewhere in the stream
4430 // but we haven't seen it yet.
4431 if (DFII->second == 0)
4432 if (std::error_code EC = findFunctionInStream(F, DFII))
4435 // Move the bit stream to the saved position of the deferred function body.
4436 Stream.JumpToBit(DFII->second);
4438 if (std::error_code EC = parseFunctionBody(F))
4440 F->setIsMaterializable(false);
4445 // Upgrade any old intrinsic calls in the function.
4446 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4447 E = UpgradedIntrinsics.end(); I != E; ++I) {
4448 if (I->first != I->second) {
4449 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4451 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4452 UpgradeIntrinsicCall(CI, I->second);
4457 // Bring in any functions that this function forward-referenced via
4459 return materializeForwardReferencedFunctions();
4462 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4463 const Function *F = dyn_cast<Function>(GV);
4464 if (!F || F->isDeclaration())
4467 // Dematerializing F would leave dangling references that wouldn't be
4468 // reconnected on re-materialization.
4469 if (BlockAddressesTaken.count(F))
4472 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4475 void BitcodeReader::dematerialize(GlobalValue *GV) {
4476 Function *F = dyn_cast<Function>(GV);
4477 // If this function isn't dematerializable, this is a noop.
4478 if (!F || !isDematerializable(F))
4481 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4483 // Just forget the function body, we can remat it later.
4484 F->dropAllReferences();
4485 F->setIsMaterializable(true);
4488 std::error_code BitcodeReader::materializeModule(Module *M) {
4489 assert(M == TheModule &&
4490 "Can only Materialize the Module this BitcodeReader is attached to.");
4492 if (std::error_code EC = materializeMetadata())
4495 // Promise to materialize all forward references.
4496 WillMaterializeAllForwardRefs = true;
4498 // Iterate over the module, deserializing any functions that are still on
4500 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4502 if (std::error_code EC = materialize(F))
4505 // At this point, if there are any function bodies, the current bit is
4506 // pointing to the END_BLOCK record after them. Now make sure the rest
4507 // of the bits in the module have been read.
4511 // Check that all block address forward references got resolved (as we
4513 if (!BasicBlockFwdRefs.empty())
4514 return error("Never resolved function from blockaddress");
4516 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4517 // delete the old functions to clean up. We can't do this unless the entire
4518 // module is materialized because there could always be another function body
4519 // with calls to the old function.
4520 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4521 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4522 if (I->first != I->second) {
4523 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4525 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4526 UpgradeIntrinsicCall(CI, I->second);
4528 if (!I->first->use_empty())
4529 I->first->replaceAllUsesWith(I->second);
4530 I->first->eraseFromParent();
4533 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4535 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4536 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4538 UpgradeDebugInfo(*M);
4539 return std::error_code();
4542 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4543 return IdentifiedStructTypes;
4547 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
4549 return initLazyStream(std::move(Streamer));
4550 return initStreamFromBuffer();
4553 std::error_code BitcodeReader::initStreamFromBuffer() {
4554 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4555 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4557 if (Buffer->getBufferSize() & 3)
4558 return error("Invalid bitcode signature");
4560 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4561 // The magic number is 0x0B17C0DE stored in little endian.
4562 if (isBitcodeWrapper(BufPtr, BufEnd))
4563 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4564 return error("Invalid bitcode wrapper header");
4566 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4567 Stream.init(&*StreamFile);
4569 return std::error_code();
4573 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
4574 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4577 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
4578 StreamingMemoryObject &Bytes = *OwnedBytes;
4579 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4580 Stream.init(&*StreamFile);
4582 unsigned char buf[16];
4583 if (Bytes.readBytes(buf, 16, 0) != 16)
4584 return error("Invalid bitcode signature");
4586 if (!isBitcode(buf, buf + 16))
4587 return error("Invalid bitcode signature");
4589 if (isBitcodeWrapper(buf, buf + 4)) {
4590 const unsigned char *bitcodeStart = buf;
4591 const unsigned char *bitcodeEnd = buf + 16;
4592 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4593 Bytes.dropLeadingBytes(bitcodeStart - buf);
4594 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4596 return std::error_code();
4600 class BitcodeErrorCategoryType : public std::error_category {
4601 const char *name() const LLVM_NOEXCEPT override {
4602 return "llvm.bitcode";
4604 std::string message(int IE) const override {
4605 BitcodeError E = static_cast<BitcodeError>(IE);
4607 case BitcodeError::InvalidBitcodeSignature:
4608 return "Invalid bitcode signature";
4609 case BitcodeError::CorruptedBitcode:
4610 return "Corrupted bitcode";
4612 llvm_unreachable("Unknown error type!");
4617 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4619 const std::error_category &llvm::BitcodeErrorCategory() {
4620 return *ErrorCategory;
4623 //===----------------------------------------------------------------------===//
4624 // External interface
4625 //===----------------------------------------------------------------------===//
4627 static ErrorOr<std::unique_ptr<Module>>
4628 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
4629 BitcodeReader *R, LLVMContext &Context,
4630 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
4631 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4632 M->setMaterializer(R);
4634 auto cleanupOnError = [&](std::error_code EC) {
4635 R->releaseBuffer(); // Never take ownership on error.
4639 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4640 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
4641 ShouldLazyLoadMetadata))
4642 return cleanupOnError(EC);
4644 if (MaterializeAll) {
4645 // Read in the entire module, and destroy the BitcodeReader.
4646 if (std::error_code EC = M->materializeAllPermanently())
4647 return cleanupOnError(EC);
4649 // Resolve forward references from blockaddresses.
4650 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4651 return cleanupOnError(EC);
4653 return std::move(M);
4656 /// \brief Get a lazy one-at-time loading module from bitcode.
4658 /// This isn't always used in a lazy context. In particular, it's also used by
4659 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4660 /// in forward-referenced functions from block address references.
4662 /// \param[in] MaterializeAll Set to \c true if we should materialize
4664 static ErrorOr<std::unique_ptr<Module>>
4665 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4666 LLVMContext &Context, bool MaterializeAll,
4667 DiagnosticHandlerFunction DiagnosticHandler,
4668 bool ShouldLazyLoadMetadata = false) {
4670 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4672 ErrorOr<std::unique_ptr<Module>> Ret =
4673 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
4674 MaterializeAll, ShouldLazyLoadMetadata);
4678 Buffer.release(); // The BitcodeReader owns it now.
4682 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
4683 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
4684 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
4685 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4686 DiagnosticHandler, ShouldLazyLoadMetadata);
4689 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
4690 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
4691 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
4692 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4693 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
4695 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
4699 ErrorOr<std::unique_ptr<Module>>
4700 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4701 DiagnosticHandlerFunction DiagnosticHandler) {
4702 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4703 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
4705 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4706 // written. We must defer until the Module has been fully materialized.
4710 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4711 DiagnosticHandlerFunction DiagnosticHandler) {
4712 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4713 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4715 ErrorOr<std::string> Triple = R->parseTriple();
4716 if (Triple.getError())
4718 return Triple.get();