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 /// ResolveConstants - As we resolve forward-referenced constants, we add
48 /// information about them to this vector. This allows us to resolve them in
49 /// bulk instead of 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) {
67 ValuePtrs.push_back(V);
71 assert(ResolveConstants.empty() && "Constants not resolved?");
75 Value *operator[](unsigned i) const {
76 assert(i < ValuePtrs.size());
80 Value *back() const { return ValuePtrs.back(); }
81 void pop_back() { ValuePtrs.pop_back(); }
82 bool empty() const { return ValuePtrs.empty(); }
83 void shrinkTo(unsigned N) {
84 assert(N <= size() && "Invalid shrinkTo request!");
88 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
89 Value *getValueFwdRef(unsigned Idx, Type *Ty);
91 void AssignValue(Value *V, unsigned Idx);
93 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
94 /// resolves any forward references.
95 void ResolveConstantForwardRefs();
98 class BitcodeReaderMDValueList {
103 std::vector<TrackingMDRef> MDValuePtrs;
105 LLVMContext &Context;
107 BitcodeReaderMDValueList(LLVMContext &C)
108 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
110 // vector compatibility methods
111 unsigned size() const { return MDValuePtrs.size(); }
112 void resize(unsigned N) { MDValuePtrs.resize(N); }
113 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
114 void clear() { MDValuePtrs.clear(); }
115 Metadata *back() const { return MDValuePtrs.back(); }
116 void pop_back() { MDValuePtrs.pop_back(); }
117 bool empty() const { return MDValuePtrs.empty(); }
119 Metadata *operator[](unsigned i) const {
120 assert(i < MDValuePtrs.size());
121 return MDValuePtrs[i];
124 void shrinkTo(unsigned N) {
125 assert(N <= size() && "Invalid shrinkTo request!");
126 MDValuePtrs.resize(N);
129 Metadata *getValueFwdRef(unsigned Idx);
130 void AssignValue(Metadata *MD, unsigned Idx);
131 void tryToResolveCycles();
134 class BitcodeReader : public GVMaterializer {
135 LLVMContext &Context;
136 DiagnosticHandlerFunction DiagnosticHandler;
138 std::unique_ptr<MemoryBuffer> Buffer;
139 std::unique_ptr<BitstreamReader> StreamFile;
140 BitstreamCursor Stream;
141 DataStreamer *LazyStreamer;
142 uint64_t NextUnreadBit;
143 bool SeenValueSymbolTable;
145 std::vector<Type*> TypeList;
146 BitcodeReaderValueList ValueList;
147 BitcodeReaderMDValueList MDValueList;
148 std::vector<Comdat *> ComdatList;
149 SmallVector<Instruction *, 64> InstructionList;
151 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
152 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
153 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
154 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
156 SmallVector<Instruction*, 64> InstsWithTBAATag;
158 /// MAttributes - The set of attributes by index. Index zero in the
159 /// file is for null, and is thus not represented here. As such all indices
161 std::vector<AttributeSet> MAttributes;
163 /// \brief The set of attribute groups.
164 std::map<unsigned, AttributeSet> MAttributeGroups;
166 /// FunctionBBs - While parsing a function body, this is a list of the basic
167 /// blocks for the function.
168 std::vector<BasicBlock*> FunctionBBs;
170 // When reading the module header, this list is populated with functions that
171 // have bodies later in the file.
172 std::vector<Function*> FunctionsWithBodies;
174 // When intrinsic functions are encountered which require upgrading they are
175 // stored here with their replacement function.
176 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
177 UpgradedIntrinsicMap UpgradedIntrinsics;
179 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
180 DenseMap<unsigned, unsigned> MDKindMap;
182 // Several operations happen after the module header has been read, but
183 // before function bodies are processed. This keeps track of whether
184 // we've done this yet.
185 bool SeenFirstFunctionBody;
187 /// DeferredFunctionInfo - When function bodies are initially scanned, this
188 /// map contains info about where to find deferred function body in the
190 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
192 /// When Metadata block is initially scanned when parsing the module, we may
193 /// choose to defer parsing of the metadata. This vector contains info about
194 /// which Metadata blocks are deferred.
195 std::vector<uint64_t> DeferredMetadataInfo;
197 /// These are basic blocks forward-referenced by block addresses. They are
198 /// inserted lazily into functions when they're loaded. The basic block ID is
199 /// its index into the vector.
200 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
201 std::deque<Function *> BasicBlockFwdRefQueue;
203 /// UseRelativeIDs - Indicates that we are using a new encoding for
204 /// instruction operands where most operands in the current
205 /// FUNCTION_BLOCK are encoded relative to the instruction number,
206 /// for a more compact encoding. Some instruction operands are not
207 /// relative to the instruction ID: basic block numbers, and types.
208 /// Once the old style function blocks have been phased out, we would
209 /// not need this flag.
212 /// True if all functions will be materialized, negating the need to process
213 /// (e.g.) blockaddress forward references.
214 bool WillMaterializeAllForwardRefs;
216 /// Functions that have block addresses taken. This is usually empty.
217 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
219 /// True if any Metadata block has been materialized.
220 bool IsMetadataMaterialized;
222 bool StripDebugInfo = false;
225 std::error_code Error(BitcodeError E, const Twine &Message);
226 std::error_code Error(BitcodeError E);
227 std::error_code Error(const Twine &Message);
229 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
230 DiagnosticHandlerFunction DiagnosticHandler);
231 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
232 DiagnosticHandlerFunction DiagnosticHandler);
233 ~BitcodeReader() override { FreeState(); }
235 std::error_code materializeForwardReferencedFunctions();
239 void releaseBuffer();
241 bool isDematerializable(const GlobalValue *GV) const override;
242 std::error_code materialize(GlobalValue *GV) override;
243 std::error_code MaterializeModule(Module *M) override;
244 std::vector<StructType *> getIdentifiedStructTypes() const override;
245 void Dematerialize(GlobalValue *GV) override;
247 /// @brief Main interface to parsing a bitcode buffer.
248 /// @returns true if an error occurred.
249 std::error_code ParseBitcodeInto(Module *M,
250 bool ShouldLazyLoadMetadata = false);
252 /// @brief Cheap mechanism to just extract module triple
253 /// @returns true if an error occurred.
254 ErrorOr<std::string> parseTriple();
256 static uint64_t decodeSignRotatedValue(uint64_t V);
258 /// Materialize any deferred Metadata block.
259 std::error_code materializeMetadata() override;
261 void setStripDebugInfo() override;
264 std::vector<StructType *> IdentifiedStructTypes;
265 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
266 StructType *createIdentifiedStructType(LLVMContext &Context);
268 Type *getTypeByID(unsigned ID);
269 Value *getFnValueByID(unsigned ID, Type *Ty) {
270 if (Ty && Ty->isMetadataTy())
271 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
272 return ValueList.getValueFwdRef(ID, Ty);
274 Metadata *getFnMetadataByID(unsigned ID) {
275 return MDValueList.getValueFwdRef(ID);
277 BasicBlock *getBasicBlock(unsigned ID) const {
278 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
279 return FunctionBBs[ID];
281 AttributeSet getAttributes(unsigned i) const {
282 if (i-1 < MAttributes.size())
283 return MAttributes[i-1];
284 return AttributeSet();
287 /// getValueTypePair - Read a value/type pair out of the specified record from
288 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
289 /// Return true on failure.
290 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
291 unsigned InstNum, Value *&ResVal) {
292 if (Slot == Record.size()) return true;
293 unsigned ValNo = (unsigned)Record[Slot++];
294 // Adjust the ValNo, if it was encoded relative to the InstNum.
296 ValNo = InstNum - ValNo;
297 if (ValNo < InstNum) {
298 // If this is not a forward reference, just return the value we already
300 ResVal = getFnValueByID(ValNo, nullptr);
301 return ResVal == nullptr;
303 if (Slot == Record.size())
306 unsigned TypeNo = (unsigned)Record[Slot++];
307 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
308 return ResVal == nullptr;
311 /// popValue - Read a value out of the specified record from slot 'Slot'.
312 /// Increment Slot past the number of slots used by the value in the record.
313 /// Return true if there is an error.
314 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
315 unsigned InstNum, Type *Ty, Value *&ResVal) {
316 if (getValue(Record, Slot, InstNum, Ty, ResVal))
318 // All values currently take a single record slot.
323 /// getValue -- Like popValue, but does not increment the Slot number.
324 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
325 unsigned InstNum, Type *Ty, Value *&ResVal) {
326 ResVal = getValue(Record, Slot, InstNum, Ty);
327 return ResVal == nullptr;
330 /// getValue -- Version of getValue that returns ResVal directly,
331 /// or 0 if there is an error.
332 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
333 unsigned InstNum, Type *Ty) {
334 if (Slot == Record.size()) return nullptr;
335 unsigned ValNo = (unsigned)Record[Slot];
336 // Adjust the ValNo, if it was encoded relative to the InstNum.
338 ValNo = InstNum - ValNo;
339 return getFnValueByID(ValNo, Ty);
342 /// getValueSigned -- Like getValue, but decodes signed VBRs.
343 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
344 unsigned InstNum, Type *Ty) {
345 if (Slot == Record.size()) return nullptr;
346 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
347 // Adjust the ValNo, if it was encoded relative to the InstNum.
349 ValNo = InstNum - ValNo;
350 return getFnValueByID(ValNo, Ty);
353 /// Converts alignment exponent (i.e. power of two (or zero)) to the
354 /// corresponding alignment to use. If alignment is too large, returns
355 /// a corresponding error code.
356 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
357 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
358 std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
359 std::error_code ParseAttributeBlock();
360 std::error_code ParseAttributeGroupBlock();
361 std::error_code ParseTypeTable();
362 std::error_code ParseTypeTableBody();
364 std::error_code ParseValueSymbolTable();
365 std::error_code ParseConstants();
366 std::error_code RememberAndSkipFunctionBody();
367 /// Save the positions of the Metadata blocks and skip parsing the blocks.
368 std::error_code rememberAndSkipMetadata();
369 std::error_code ParseFunctionBody(Function *F);
370 std::error_code GlobalCleanup();
371 std::error_code ResolveGlobalAndAliasInits();
372 std::error_code ParseMetadata();
373 std::error_code ParseMetadataAttachment(Function &F);
374 ErrorOr<std::string> parseModuleTriple();
375 std::error_code ParseUseLists();
376 std::error_code InitStream();
377 std::error_code InitStreamFromBuffer();
378 std::error_code InitLazyStream();
379 std::error_code FindFunctionInStream(
381 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
385 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
386 DiagnosticSeverity Severity,
388 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
390 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
392 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
393 std::error_code EC, const Twine &Message) {
394 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
395 DiagnosticHandler(DI);
399 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
400 std::error_code EC) {
401 return Error(DiagnosticHandler, EC, EC.message());
404 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
405 return ::Error(DiagnosticHandler, make_error_code(E), Message);
408 std::error_code BitcodeReader::Error(const Twine &Message) {
409 return ::Error(DiagnosticHandler,
410 make_error_code(BitcodeError::CorruptedBitcode), Message);
413 std::error_code BitcodeReader::Error(BitcodeError E) {
414 return ::Error(DiagnosticHandler, make_error_code(E));
417 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
421 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
424 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
425 DiagnosticHandlerFunction DiagnosticHandler)
426 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
427 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
428 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
429 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
430 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
432 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
433 DiagnosticHandlerFunction DiagnosticHandler)
434 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
435 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
436 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
437 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
438 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
440 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
441 if (WillMaterializeAllForwardRefs)
442 return std::error_code();
444 // Prevent recursion.
445 WillMaterializeAllForwardRefs = true;
447 while (!BasicBlockFwdRefQueue.empty()) {
448 Function *F = BasicBlockFwdRefQueue.front();
449 BasicBlockFwdRefQueue.pop_front();
450 assert(F && "Expected valid function");
451 if (!BasicBlockFwdRefs.count(F))
452 // Already materialized.
455 // Check for a function that isn't materializable to prevent an infinite
456 // loop. When parsing a blockaddress stored in a global variable, there
457 // isn't a trivial way to check if a function will have a body without a
458 // linear search through FunctionsWithBodies, so just check it here.
459 if (!F->isMaterializable())
460 return Error("Never resolved function from blockaddress");
462 // Try to materialize F.
463 if (std::error_code EC = materialize(F))
466 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
469 WillMaterializeAllForwardRefs = false;
470 return std::error_code();
473 void BitcodeReader::FreeState() {
475 std::vector<Type*>().swap(TypeList);
478 std::vector<Comdat *>().swap(ComdatList);
480 std::vector<AttributeSet>().swap(MAttributes);
481 std::vector<BasicBlock*>().swap(FunctionBBs);
482 std::vector<Function*>().swap(FunctionsWithBodies);
483 DeferredFunctionInfo.clear();
484 DeferredMetadataInfo.clear();
487 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
488 BasicBlockFwdRefQueue.clear();
491 //===----------------------------------------------------------------------===//
492 // Helper functions to implement forward reference resolution, etc.
493 //===----------------------------------------------------------------------===//
495 /// ConvertToString - Convert a string from a record into an std::string, return
497 template<typename StrTy>
498 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
500 if (Idx > Record.size())
503 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
504 Result += (char)Record[i];
508 static bool hasImplicitComdat(size_t Val) {
512 case 1: // Old WeakAnyLinkage
513 case 4: // Old LinkOnceAnyLinkage
514 case 10: // Old WeakODRLinkage
515 case 11: // Old LinkOnceODRLinkage
520 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
522 default: // Map unknown/new linkages to external
524 return GlobalValue::ExternalLinkage;
526 return GlobalValue::AppendingLinkage;
528 return GlobalValue::InternalLinkage;
530 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
532 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
534 return GlobalValue::ExternalWeakLinkage;
536 return GlobalValue::CommonLinkage;
538 return GlobalValue::PrivateLinkage;
540 return GlobalValue::AvailableExternallyLinkage;
542 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
544 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
546 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
547 case 1: // Old value with implicit comdat.
549 return GlobalValue::WeakAnyLinkage;
550 case 10: // Old value with implicit comdat.
552 return GlobalValue::WeakODRLinkage;
553 case 4: // Old value with implicit comdat.
555 return GlobalValue::LinkOnceAnyLinkage;
556 case 11: // Old value with implicit comdat.
558 return GlobalValue::LinkOnceODRLinkage;
562 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
564 default: // Map unknown visibilities to default.
565 case 0: return GlobalValue::DefaultVisibility;
566 case 1: return GlobalValue::HiddenVisibility;
567 case 2: return GlobalValue::ProtectedVisibility;
571 static GlobalValue::DLLStorageClassTypes
572 GetDecodedDLLStorageClass(unsigned Val) {
574 default: // Map unknown values to default.
575 case 0: return GlobalValue::DefaultStorageClass;
576 case 1: return GlobalValue::DLLImportStorageClass;
577 case 2: return GlobalValue::DLLExportStorageClass;
581 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
583 case 0: return GlobalVariable::NotThreadLocal;
584 default: // Map unknown non-zero value to general dynamic.
585 case 1: return GlobalVariable::GeneralDynamicTLSModel;
586 case 2: return GlobalVariable::LocalDynamicTLSModel;
587 case 3: return GlobalVariable::InitialExecTLSModel;
588 case 4: return GlobalVariable::LocalExecTLSModel;
592 static int GetDecodedCastOpcode(unsigned Val) {
595 case bitc::CAST_TRUNC : return Instruction::Trunc;
596 case bitc::CAST_ZEXT : return Instruction::ZExt;
597 case bitc::CAST_SEXT : return Instruction::SExt;
598 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
599 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
600 case bitc::CAST_UITOFP : return Instruction::UIToFP;
601 case bitc::CAST_SITOFP : return Instruction::SIToFP;
602 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
603 case bitc::CAST_FPEXT : return Instruction::FPExt;
604 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
605 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
606 case bitc::CAST_BITCAST : return Instruction::BitCast;
607 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
611 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
612 bool IsFP = Ty->isFPOrFPVectorTy();
613 // BinOps are only valid for int/fp or vector of int/fp types
614 if (!IsFP && !Ty->isIntOrIntVectorTy())
620 case bitc::BINOP_ADD:
621 return IsFP ? Instruction::FAdd : Instruction::Add;
622 case bitc::BINOP_SUB:
623 return IsFP ? Instruction::FSub : Instruction::Sub;
624 case bitc::BINOP_MUL:
625 return IsFP ? Instruction::FMul : Instruction::Mul;
626 case bitc::BINOP_UDIV:
627 return IsFP ? -1 : Instruction::UDiv;
628 case bitc::BINOP_SDIV:
629 return IsFP ? Instruction::FDiv : Instruction::SDiv;
630 case bitc::BINOP_UREM:
631 return IsFP ? -1 : Instruction::URem;
632 case bitc::BINOP_SREM:
633 return IsFP ? Instruction::FRem : Instruction::SRem;
634 case bitc::BINOP_SHL:
635 return IsFP ? -1 : Instruction::Shl;
636 case bitc::BINOP_LSHR:
637 return IsFP ? -1 : Instruction::LShr;
638 case bitc::BINOP_ASHR:
639 return IsFP ? -1 : Instruction::AShr;
640 case bitc::BINOP_AND:
641 return IsFP ? -1 : Instruction::And;
643 return IsFP ? -1 : Instruction::Or;
644 case bitc::BINOP_XOR:
645 return IsFP ? -1 : Instruction::Xor;
649 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
651 default: return AtomicRMWInst::BAD_BINOP;
652 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
653 case bitc::RMW_ADD: return AtomicRMWInst::Add;
654 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
655 case bitc::RMW_AND: return AtomicRMWInst::And;
656 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
657 case bitc::RMW_OR: return AtomicRMWInst::Or;
658 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
659 case bitc::RMW_MAX: return AtomicRMWInst::Max;
660 case bitc::RMW_MIN: return AtomicRMWInst::Min;
661 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
662 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
666 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
668 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
669 case bitc::ORDERING_UNORDERED: return Unordered;
670 case bitc::ORDERING_MONOTONIC: return Monotonic;
671 case bitc::ORDERING_ACQUIRE: return Acquire;
672 case bitc::ORDERING_RELEASE: return Release;
673 case bitc::ORDERING_ACQREL: return AcquireRelease;
674 default: // Map unknown orderings to sequentially-consistent.
675 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
679 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
681 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
682 default: // Map unknown scopes to cross-thread.
683 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
687 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
689 default: // Map unknown selection kinds to any.
690 case bitc::COMDAT_SELECTION_KIND_ANY:
692 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
693 return Comdat::ExactMatch;
694 case bitc::COMDAT_SELECTION_KIND_LARGEST:
695 return Comdat::Largest;
696 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
697 return Comdat::NoDuplicates;
698 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
699 return Comdat::SameSize;
703 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
705 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
706 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
712 /// @brief A class for maintaining the slot number definition
713 /// as a placeholder for the actual definition for forward constants defs.
714 class ConstantPlaceHolder : public ConstantExpr {
715 void operator=(const ConstantPlaceHolder &) = delete;
717 // allocate space for exactly one operand
718 void *operator new(size_t s) {
719 return User::operator new(s, 1);
721 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
722 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
723 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
726 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
727 static bool classof(const Value *V) {
728 return isa<ConstantExpr>(V) &&
729 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
733 /// Provide fast operand accessors
734 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
738 // FIXME: can we inherit this from ConstantExpr?
740 struct OperandTraits<ConstantPlaceHolder> :
741 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
743 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
747 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
756 WeakVH &OldV = ValuePtrs[Idx];
762 // Handle constants and non-constants (e.g. instrs) differently for
764 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
765 ResolveConstants.push_back(std::make_pair(PHC, Idx));
768 // If there was a forward reference to this value, replace it.
769 Value *PrevVal = OldV;
770 OldV->replaceAllUsesWith(V);
776 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
781 if (Value *V = ValuePtrs[Idx]) {
782 assert(Ty == V->getType() && "Type mismatch in constant table!");
783 return cast<Constant>(V);
786 // Create and return a placeholder, which will later be RAUW'd.
787 Constant *C = new ConstantPlaceHolder(Ty, Context);
792 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
796 if (Value *V = ValuePtrs[Idx]) {
797 // If the types don't match, it's invalid.
798 if (Ty && Ty != V->getType())
803 // No type specified, must be invalid reference.
804 if (!Ty) return nullptr;
806 // Create and return a placeholder, which will later be RAUW'd.
807 Value *V = new Argument(Ty);
812 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
813 /// resolves any forward references. The idea behind this is that we sometimes
814 /// get constants (such as large arrays) which reference *many* forward ref
815 /// constants. Replacing each of these causes a lot of thrashing when
816 /// building/reuniquing the constant. Instead of doing this, we look at all the
817 /// uses and rewrite all the place holders at once for any constant that uses
819 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
820 // Sort the values by-pointer so that they are efficient to look up with a
822 std::sort(ResolveConstants.begin(), ResolveConstants.end());
824 SmallVector<Constant*, 64> NewOps;
826 while (!ResolveConstants.empty()) {
827 Value *RealVal = operator[](ResolveConstants.back().second);
828 Constant *Placeholder = ResolveConstants.back().first;
829 ResolveConstants.pop_back();
831 // Loop over all users of the placeholder, updating them to reference the
832 // new value. If they reference more than one placeholder, update them all
834 while (!Placeholder->use_empty()) {
835 auto UI = Placeholder->user_begin();
838 // If the using object isn't uniqued, just update the operands. This
839 // handles instructions and initializers for global variables.
840 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
841 UI.getUse().set(RealVal);
845 // Otherwise, we have a constant that uses the placeholder. Replace that
846 // constant with a new constant that has *all* placeholder uses updated.
847 Constant *UserC = cast<Constant>(U);
848 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
851 if (!isa<ConstantPlaceHolder>(*I)) {
852 // Not a placeholder reference.
854 } else if (*I == Placeholder) {
855 // Common case is that it just references this one placeholder.
858 // Otherwise, look up the placeholder in ResolveConstants.
859 ResolveConstantsTy::iterator It =
860 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
861 std::pair<Constant*, unsigned>(cast<Constant>(*I),
863 assert(It != ResolveConstants.end() && It->first == *I);
864 NewOp = operator[](It->second);
867 NewOps.push_back(cast<Constant>(NewOp));
870 // Make the new constant.
872 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
873 NewC = ConstantArray::get(UserCA->getType(), NewOps);
874 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
875 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
876 } else if (isa<ConstantVector>(UserC)) {
877 NewC = ConstantVector::get(NewOps);
879 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
880 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
883 UserC->replaceAllUsesWith(NewC);
884 UserC->destroyConstant();
888 // Update all ValueHandles, they should be the only users at this point.
889 Placeholder->replaceAllUsesWith(RealVal);
894 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
903 TrackingMDRef &OldMD = MDValuePtrs[Idx];
909 // If there was a forward reference to this value, replace it.
910 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
911 PrevMD->replaceAllUsesWith(MD);
915 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
919 if (Metadata *MD = MDValuePtrs[Idx])
922 // Track forward refs to be resolved later.
924 MinFwdRef = std::min(MinFwdRef, Idx);
925 MaxFwdRef = std::max(MaxFwdRef, Idx);
928 MinFwdRef = MaxFwdRef = Idx;
932 // Create and return a placeholder, which will later be RAUW'd.
933 Metadata *MD = MDNode::getTemporary(Context, None).release();
934 MDValuePtrs[Idx].reset(MD);
938 void BitcodeReaderMDValueList::tryToResolveCycles() {
944 // Still forward references... can't resolve cycles.
947 // Resolve any cycles.
948 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
949 auto &MD = MDValuePtrs[I];
950 auto *N = dyn_cast_or_null<MDNode>(MD);
954 assert(!N->isTemporary() && "Unexpected forward reference");
958 // Make sure we return early again until there's another forward ref.
962 Type *BitcodeReader::getTypeByID(unsigned ID) {
963 // The type table size is always specified correctly.
964 if (ID >= TypeList.size())
967 if (Type *Ty = TypeList[ID])
970 // If we have a forward reference, the only possible case is when it is to a
971 // named struct. Just create a placeholder for now.
972 return TypeList[ID] = createIdentifiedStructType(Context);
975 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
977 auto *Ret = StructType::create(Context, Name);
978 IdentifiedStructTypes.push_back(Ret);
982 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
983 auto *Ret = StructType::create(Context);
984 IdentifiedStructTypes.push_back(Ret);
989 //===----------------------------------------------------------------------===//
990 // Functions for parsing blocks from the bitcode file
991 //===----------------------------------------------------------------------===//
994 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
995 /// been decoded from the given integer. This function must stay in sync with
996 /// 'encodeLLVMAttributesForBitcode'.
997 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
998 uint64_t EncodedAttrs) {
999 // FIXME: Remove in 4.0.
1001 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1002 // the bits above 31 down by 11 bits.
1003 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1004 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1005 "Alignment must be a power of two.");
1008 B.addAlignmentAttr(Alignment);
1009 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1010 (EncodedAttrs & 0xffff));
1013 std::error_code BitcodeReader::ParseAttributeBlock() {
1014 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1015 return Error("Invalid record");
1017 if (!MAttributes.empty())
1018 return Error("Invalid multiple blocks");
1020 SmallVector<uint64_t, 64> Record;
1022 SmallVector<AttributeSet, 8> Attrs;
1024 // Read all the records.
1026 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1028 switch (Entry.Kind) {
1029 case BitstreamEntry::SubBlock: // Handled for us already.
1030 case BitstreamEntry::Error:
1031 return Error("Malformed block");
1032 case BitstreamEntry::EndBlock:
1033 return std::error_code();
1034 case BitstreamEntry::Record:
1035 // The interesting case.
1041 switch (Stream.readRecord(Entry.ID, Record)) {
1042 default: // Default behavior: ignore.
1044 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1045 // FIXME: Remove in 4.0.
1046 if (Record.size() & 1)
1047 return Error("Invalid record");
1049 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1051 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1052 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1055 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1059 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1060 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1061 Attrs.push_back(MAttributeGroups[Record[i]]);
1063 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1071 // Returns Attribute::None on unrecognized codes.
1072 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1075 return Attribute::None;
1076 case bitc::ATTR_KIND_ALIGNMENT:
1077 return Attribute::Alignment;
1078 case bitc::ATTR_KIND_ALWAYS_INLINE:
1079 return Attribute::AlwaysInline;
1080 case bitc::ATTR_KIND_BUILTIN:
1081 return Attribute::Builtin;
1082 case bitc::ATTR_KIND_BY_VAL:
1083 return Attribute::ByVal;
1084 case bitc::ATTR_KIND_IN_ALLOCA:
1085 return Attribute::InAlloca;
1086 case bitc::ATTR_KIND_COLD:
1087 return Attribute::Cold;
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_STRUCT_RET:
1149 return Attribute::StructRet;
1150 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1151 return Attribute::SanitizeAddress;
1152 case bitc::ATTR_KIND_SANITIZE_THREAD:
1153 return Attribute::SanitizeThread;
1154 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1155 return Attribute::SanitizeMemory;
1156 case bitc::ATTR_KIND_UW_TABLE:
1157 return Attribute::UWTable;
1158 case bitc::ATTR_KIND_Z_EXT:
1159 return Attribute::ZExt;
1163 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1164 unsigned &Alignment) {
1165 // Note: Alignment in bitcode files is incremented by 1, so that zero
1166 // can be used for default alignment.
1167 if (Exponent > Value::MaxAlignmentExponent + 1)
1168 return Error("Invalid alignment value");
1169 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1170 return std::error_code();
1173 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1174 Attribute::AttrKind *Kind) {
1175 *Kind = GetAttrFromCode(Code);
1176 if (*Kind == Attribute::None)
1177 return Error(BitcodeError::CorruptedBitcode,
1178 "Unknown attribute kind (" + Twine(Code) + ")");
1179 return std::error_code();
1182 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
1183 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1184 return Error("Invalid record");
1186 if (!MAttributeGroups.empty())
1187 return Error("Invalid multiple blocks");
1189 SmallVector<uint64_t, 64> Record;
1191 // Read all the records.
1193 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1195 switch (Entry.Kind) {
1196 case BitstreamEntry::SubBlock: // Handled for us already.
1197 case BitstreamEntry::Error:
1198 return Error("Malformed block");
1199 case BitstreamEntry::EndBlock:
1200 return std::error_code();
1201 case BitstreamEntry::Record:
1202 // The interesting case.
1208 switch (Stream.readRecord(Entry.ID, Record)) {
1209 default: // Default behavior: ignore.
1211 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1212 if (Record.size() < 3)
1213 return Error("Invalid record");
1215 uint64_t GrpID = Record[0];
1216 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1219 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1220 if (Record[i] == 0) { // Enum attribute
1221 Attribute::AttrKind Kind;
1222 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1225 B.addAttribute(Kind);
1226 } else if (Record[i] == 1) { // Integer attribute
1227 Attribute::AttrKind Kind;
1228 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1230 if (Kind == Attribute::Alignment)
1231 B.addAlignmentAttr(Record[++i]);
1232 else if (Kind == Attribute::StackAlignment)
1233 B.addStackAlignmentAttr(Record[++i]);
1234 else if (Kind == Attribute::Dereferenceable)
1235 B.addDereferenceableAttr(Record[++i]);
1236 else if (Kind == Attribute::DereferenceableOrNull)
1237 B.addDereferenceableOrNullAttr(Record[++i]);
1238 } else { // String attribute
1239 assert((Record[i] == 3 || Record[i] == 4) &&
1240 "Invalid attribute group entry");
1241 bool HasValue = (Record[i++] == 4);
1242 SmallString<64> KindStr;
1243 SmallString<64> ValStr;
1245 while (Record[i] != 0 && i != e)
1246 KindStr += Record[i++];
1247 assert(Record[i] == 0 && "Kind string not null terminated");
1250 // Has a value associated with it.
1251 ++i; // Skip the '0' that terminates the "kind" string.
1252 while (Record[i] != 0 && i != e)
1253 ValStr += Record[i++];
1254 assert(Record[i] == 0 && "Value string not null terminated");
1257 B.addAttribute(KindStr.str(), ValStr.str());
1261 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1268 std::error_code BitcodeReader::ParseTypeTable() {
1269 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1270 return Error("Invalid record");
1272 return ParseTypeTableBody();
1275 std::error_code BitcodeReader::ParseTypeTableBody() {
1276 if (!TypeList.empty())
1277 return Error("Invalid multiple blocks");
1279 SmallVector<uint64_t, 64> Record;
1280 unsigned NumRecords = 0;
1282 SmallString<64> TypeName;
1284 // Read all the records for this type table.
1286 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1288 switch (Entry.Kind) {
1289 case BitstreamEntry::SubBlock: // Handled for us already.
1290 case BitstreamEntry::Error:
1291 return Error("Malformed block");
1292 case BitstreamEntry::EndBlock:
1293 if (NumRecords != TypeList.size())
1294 return Error("Malformed block");
1295 return std::error_code();
1296 case BitstreamEntry::Record:
1297 // The interesting case.
1303 Type *ResultTy = nullptr;
1304 switch (Stream.readRecord(Entry.ID, Record)) {
1306 return Error("Invalid value");
1307 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1308 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1309 // type list. This allows us to reserve space.
1310 if (Record.size() < 1)
1311 return Error("Invalid record");
1312 TypeList.resize(Record[0]);
1314 case bitc::TYPE_CODE_VOID: // VOID
1315 ResultTy = Type::getVoidTy(Context);
1317 case bitc::TYPE_CODE_HALF: // HALF
1318 ResultTy = Type::getHalfTy(Context);
1320 case bitc::TYPE_CODE_FLOAT: // FLOAT
1321 ResultTy = Type::getFloatTy(Context);
1323 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1324 ResultTy = Type::getDoubleTy(Context);
1326 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1327 ResultTy = Type::getX86_FP80Ty(Context);
1329 case bitc::TYPE_CODE_FP128: // FP128
1330 ResultTy = Type::getFP128Ty(Context);
1332 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1333 ResultTy = Type::getPPC_FP128Ty(Context);
1335 case bitc::TYPE_CODE_LABEL: // LABEL
1336 ResultTy = Type::getLabelTy(Context);
1338 case bitc::TYPE_CODE_METADATA: // METADATA
1339 ResultTy = Type::getMetadataTy(Context);
1341 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1342 ResultTy = Type::getX86_MMXTy(Context);
1344 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1345 if (Record.size() < 1)
1346 return Error("Invalid record");
1348 uint64_t NumBits = Record[0];
1349 if (NumBits < IntegerType::MIN_INT_BITS ||
1350 NumBits > IntegerType::MAX_INT_BITS)
1351 return Error("Bitwidth for integer type out of range");
1352 ResultTy = IntegerType::get(Context, NumBits);
1355 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1356 // [pointee type, address space]
1357 if (Record.size() < 1)
1358 return Error("Invalid record");
1359 unsigned AddressSpace = 0;
1360 if (Record.size() == 2)
1361 AddressSpace = Record[1];
1362 ResultTy = getTypeByID(Record[0]);
1364 return Error("Invalid type");
1365 ResultTy = PointerType::get(ResultTy, AddressSpace);
1368 case bitc::TYPE_CODE_FUNCTION_OLD: {
1369 // FIXME: attrid is dead, remove it in LLVM 4.0
1370 // FUNCTION: [vararg, attrid, retty, paramty x N]
1371 if (Record.size() < 3)
1372 return Error("Invalid record");
1373 SmallVector<Type*, 8> ArgTys;
1374 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1375 if (Type *T = getTypeByID(Record[i]))
1376 ArgTys.push_back(T);
1381 ResultTy = getTypeByID(Record[2]);
1382 if (!ResultTy || ArgTys.size() < Record.size()-3)
1383 return Error("Invalid type");
1385 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1388 case bitc::TYPE_CODE_FUNCTION: {
1389 // FUNCTION: [vararg, retty, paramty x N]
1390 if (Record.size() < 2)
1391 return Error("Invalid record");
1392 SmallVector<Type*, 8> ArgTys;
1393 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1394 if (Type *T = getTypeByID(Record[i]))
1395 ArgTys.push_back(T);
1400 ResultTy = getTypeByID(Record[1]);
1401 if (!ResultTy || ArgTys.size() < Record.size()-2)
1402 return Error("Invalid type");
1404 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1407 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1408 if (Record.size() < 1)
1409 return Error("Invalid record");
1410 SmallVector<Type*, 8> EltTys;
1411 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1412 if (Type *T = getTypeByID(Record[i]))
1413 EltTys.push_back(T);
1417 if (EltTys.size() != Record.size()-1)
1418 return Error("Invalid type");
1419 ResultTy = StructType::get(Context, EltTys, Record[0]);
1422 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1423 if (ConvertToString(Record, 0, TypeName))
1424 return Error("Invalid record");
1427 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1428 if (Record.size() < 1)
1429 return Error("Invalid record");
1431 if (NumRecords >= TypeList.size())
1432 return Error("Invalid TYPE table");
1434 // Check to see if this was forward referenced, if so fill in the temp.
1435 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1437 Res->setName(TypeName);
1438 TypeList[NumRecords] = nullptr;
1439 } else // Otherwise, create a new struct.
1440 Res = createIdentifiedStructType(Context, TypeName);
1443 SmallVector<Type*, 8> EltTys;
1444 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1445 if (Type *T = getTypeByID(Record[i]))
1446 EltTys.push_back(T);
1450 if (EltTys.size() != Record.size()-1)
1451 return Error("Invalid record");
1452 Res->setBody(EltTys, Record[0]);
1456 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1457 if (Record.size() != 1)
1458 return Error("Invalid record");
1460 if (NumRecords >= TypeList.size())
1461 return Error("Invalid TYPE table");
1463 // Check to see if this was forward referenced, if so fill in the temp.
1464 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1466 Res->setName(TypeName);
1467 TypeList[NumRecords] = nullptr;
1468 } else // Otherwise, create a new struct with no body.
1469 Res = createIdentifiedStructType(Context, TypeName);
1474 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1475 if (Record.size() < 2)
1476 return Error("Invalid record");
1477 if ((ResultTy = getTypeByID(Record[1])) &&
1478 StructType::isValidElementType(ResultTy))
1479 ResultTy = ArrayType::get(ResultTy, Record[0]);
1481 return Error("Invalid type");
1483 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1484 if (Record.size() < 2)
1485 return Error("Invalid record");
1486 if ((ResultTy = getTypeByID(Record[1])) &&
1487 StructType::isValidElementType(ResultTy))
1488 ResultTy = VectorType::get(ResultTy, Record[0]);
1490 return Error("Invalid type");
1494 if (NumRecords >= TypeList.size())
1495 return Error("Invalid TYPE table");
1496 if (TypeList[NumRecords])
1498 "Invalid TYPE table: Only named structs can be forward referenced");
1499 assert(ResultTy && "Didn't read a type?");
1500 TypeList[NumRecords++] = ResultTy;
1504 std::error_code BitcodeReader::ParseValueSymbolTable() {
1505 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1506 return Error("Invalid record");
1508 SmallVector<uint64_t, 64> Record;
1510 Triple TT(TheModule->getTargetTriple());
1512 // Read all the records for this value table.
1513 SmallString<128> ValueName;
1515 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1517 switch (Entry.Kind) {
1518 case BitstreamEntry::SubBlock: // Handled for us already.
1519 case BitstreamEntry::Error:
1520 return Error("Malformed block");
1521 case BitstreamEntry::EndBlock:
1522 return std::error_code();
1523 case BitstreamEntry::Record:
1524 // The interesting case.
1530 switch (Stream.readRecord(Entry.ID, Record)) {
1531 default: // Default behavior: unknown type.
1533 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1534 if (ConvertToString(Record, 1, ValueName))
1535 return Error("Invalid record");
1536 unsigned ValueID = Record[0];
1537 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1538 return Error("Invalid record");
1539 Value *V = ValueList[ValueID];
1541 V->setName(StringRef(ValueName.data(), ValueName.size()));
1542 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1543 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1544 if (TT.isOSBinFormatMachO())
1545 GO->setComdat(nullptr);
1547 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1553 case bitc::VST_CODE_BBENTRY: {
1554 if (ConvertToString(Record, 1, ValueName))
1555 return Error("Invalid record");
1556 BasicBlock *BB = getBasicBlock(Record[0]);
1558 return Error("Invalid record");
1560 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1568 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1570 std::error_code BitcodeReader::ParseMetadata() {
1571 IsMetadataMaterialized = true;
1572 unsigned NextMDValueNo = MDValueList.size();
1574 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1575 return Error("Invalid record");
1577 SmallVector<uint64_t, 64> Record;
1580 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1581 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1583 return getMD(ID - 1);
1586 auto getMDString = [&](unsigned ID) -> MDString *{
1587 // This requires that the ID is not really a forward reference. In
1588 // particular, the MDString must already have been resolved.
1589 return cast_or_null<MDString>(getMDOrNull(ID));
1592 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1593 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1595 // Read all the records.
1597 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1599 switch (Entry.Kind) {
1600 case BitstreamEntry::SubBlock: // Handled for us already.
1601 case BitstreamEntry::Error:
1602 return Error("Malformed block");
1603 case BitstreamEntry::EndBlock:
1604 MDValueList.tryToResolveCycles();
1605 return std::error_code();
1606 case BitstreamEntry::Record:
1607 // The interesting case.
1613 unsigned Code = Stream.readRecord(Entry.ID, Record);
1614 bool IsDistinct = false;
1616 default: // Default behavior: ignore.
1618 case bitc::METADATA_NAME: {
1619 // Read name of the named metadata.
1620 SmallString<8> Name(Record.begin(), Record.end());
1622 Code = Stream.ReadCode();
1624 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1625 unsigned NextBitCode = Stream.readRecord(Code, Record);
1626 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1628 // Read named metadata elements.
1629 unsigned Size = Record.size();
1630 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1631 for (unsigned i = 0; i != Size; ++i) {
1632 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1634 return Error("Invalid record");
1635 NMD->addOperand(MD);
1639 case bitc::METADATA_OLD_FN_NODE: {
1640 // FIXME: Remove in 4.0.
1641 // This is a LocalAsMetadata record, the only type of function-local
1643 if (Record.size() % 2 == 1)
1644 return Error("Invalid record");
1646 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1647 // to be legal, but there's no upgrade path.
1648 auto dropRecord = [&] {
1649 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1651 if (Record.size() != 2) {
1656 Type *Ty = getTypeByID(Record[0]);
1657 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1662 MDValueList.AssignValue(
1663 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1667 case bitc::METADATA_OLD_NODE: {
1668 // FIXME: Remove in 4.0.
1669 if (Record.size() % 2 == 1)
1670 return Error("Invalid record");
1672 unsigned Size = Record.size();
1673 SmallVector<Metadata *, 8> Elts;
1674 for (unsigned i = 0; i != Size; i += 2) {
1675 Type *Ty = getTypeByID(Record[i]);
1677 return Error("Invalid record");
1678 if (Ty->isMetadataTy())
1679 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1680 else if (!Ty->isVoidTy()) {
1682 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1683 assert(isa<ConstantAsMetadata>(MD) &&
1684 "Expected non-function-local metadata");
1687 Elts.push_back(nullptr);
1689 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1692 case bitc::METADATA_VALUE: {
1693 if (Record.size() != 2)
1694 return Error("Invalid record");
1696 Type *Ty = getTypeByID(Record[0]);
1697 if (Ty->isMetadataTy() || Ty->isVoidTy())
1698 return Error("Invalid record");
1700 MDValueList.AssignValue(
1701 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1705 case bitc::METADATA_DISTINCT_NODE:
1708 case bitc::METADATA_NODE: {
1709 SmallVector<Metadata *, 8> Elts;
1710 Elts.reserve(Record.size());
1711 for (unsigned ID : Record)
1712 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1713 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1714 : MDNode::get(Context, Elts),
1718 case bitc::METADATA_LOCATION: {
1719 if (Record.size() != 5)
1720 return Error("Invalid record");
1722 unsigned Line = Record[1];
1723 unsigned Column = Record[2];
1724 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1725 Metadata *InlinedAt =
1726 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1727 MDValueList.AssignValue(
1728 GET_OR_DISTINCT(MDLocation, Record[0],
1729 (Context, Line, Column, Scope, InlinedAt)),
1733 case bitc::METADATA_GENERIC_DEBUG: {
1734 if (Record.size() < 4)
1735 return Error("Invalid record");
1737 unsigned Tag = Record[1];
1738 unsigned Version = Record[2];
1740 if (Tag >= 1u << 16 || Version != 0)
1741 return Error("Invalid record");
1743 auto *Header = getMDString(Record[3]);
1744 SmallVector<Metadata *, 8> DwarfOps;
1745 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1746 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1748 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1749 (Context, Tag, Header, DwarfOps)),
1753 case bitc::METADATA_SUBRANGE: {
1754 if (Record.size() != 3)
1755 return Error("Invalid record");
1757 MDValueList.AssignValue(
1758 GET_OR_DISTINCT(MDSubrange, Record[0],
1759 (Context, Record[1], unrotateSign(Record[2]))),
1763 case bitc::METADATA_ENUMERATOR: {
1764 if (Record.size() != 3)
1765 return Error("Invalid record");
1767 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1768 (Context, unrotateSign(Record[1]),
1769 getMDString(Record[2]))),
1773 case bitc::METADATA_BASIC_TYPE: {
1774 if (Record.size() != 6)
1775 return Error("Invalid record");
1777 MDValueList.AssignValue(
1778 GET_OR_DISTINCT(MDBasicType, Record[0],
1779 (Context, Record[1], getMDString(Record[2]),
1780 Record[3], Record[4], Record[5])),
1784 case bitc::METADATA_DERIVED_TYPE: {
1785 if (Record.size() != 12)
1786 return Error("Invalid record");
1788 MDValueList.AssignValue(
1789 GET_OR_DISTINCT(MDDerivedType, Record[0],
1790 (Context, Record[1], getMDString(Record[2]),
1791 getMDOrNull(Record[3]), Record[4],
1792 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1793 Record[7], Record[8], Record[9], Record[10],
1794 getMDOrNull(Record[11]))),
1798 case bitc::METADATA_COMPOSITE_TYPE: {
1799 if (Record.size() != 16)
1800 return Error("Invalid record");
1802 MDValueList.AssignValue(
1803 GET_OR_DISTINCT(MDCompositeType, Record[0],
1804 (Context, Record[1], getMDString(Record[2]),
1805 getMDOrNull(Record[3]), Record[4],
1806 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1807 Record[7], Record[8], Record[9], Record[10],
1808 getMDOrNull(Record[11]), Record[12],
1809 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1810 getMDString(Record[15]))),
1814 case bitc::METADATA_SUBROUTINE_TYPE: {
1815 if (Record.size() != 3)
1816 return Error("Invalid record");
1818 MDValueList.AssignValue(
1819 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1820 (Context, Record[1], getMDOrNull(Record[2]))),
1824 case bitc::METADATA_FILE: {
1825 if (Record.size() != 3)
1826 return Error("Invalid record");
1828 MDValueList.AssignValue(
1829 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1830 getMDString(Record[2]))),
1834 case bitc::METADATA_COMPILE_UNIT: {
1835 if (Record.size() != 14)
1836 return Error("Invalid record");
1838 MDValueList.AssignValue(
1839 GET_OR_DISTINCT(MDCompileUnit, Record[0],
1840 (Context, Record[1], getMDOrNull(Record[2]),
1841 getMDString(Record[3]), Record[4],
1842 getMDString(Record[5]), Record[6],
1843 getMDString(Record[7]), Record[8],
1844 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1845 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1846 getMDOrNull(Record[13]))),
1850 case bitc::METADATA_SUBPROGRAM: {
1851 if (Record.size() != 19)
1852 return Error("Invalid record");
1854 MDValueList.AssignValue(
1856 MDSubprogram, Record[0],
1857 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1858 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1859 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1860 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1861 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1862 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1866 case bitc::METADATA_LEXICAL_BLOCK: {
1867 if (Record.size() != 5)
1868 return Error("Invalid record");
1870 MDValueList.AssignValue(
1871 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1872 (Context, getMDOrNull(Record[1]),
1873 getMDOrNull(Record[2]), Record[3], Record[4])),
1877 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1878 if (Record.size() != 4)
1879 return Error("Invalid record");
1881 MDValueList.AssignValue(
1882 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1883 (Context, getMDOrNull(Record[1]),
1884 getMDOrNull(Record[2]), Record[3])),
1888 case bitc::METADATA_NAMESPACE: {
1889 if (Record.size() != 5)
1890 return Error("Invalid record");
1892 MDValueList.AssignValue(
1893 GET_OR_DISTINCT(MDNamespace, Record[0],
1894 (Context, getMDOrNull(Record[1]),
1895 getMDOrNull(Record[2]), getMDString(Record[3]),
1900 case bitc::METADATA_TEMPLATE_TYPE: {
1901 if (Record.size() != 3)
1902 return Error("Invalid record");
1904 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1906 (Context, getMDString(Record[1]),
1907 getMDOrNull(Record[2]))),
1911 case bitc::METADATA_TEMPLATE_VALUE: {
1912 if (Record.size() != 5)
1913 return Error("Invalid record");
1915 MDValueList.AssignValue(
1916 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1917 (Context, Record[1], getMDString(Record[2]),
1918 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1922 case bitc::METADATA_GLOBAL_VAR: {
1923 if (Record.size() != 11)
1924 return Error("Invalid record");
1926 MDValueList.AssignValue(
1927 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1928 (Context, getMDOrNull(Record[1]),
1929 getMDString(Record[2]), getMDString(Record[3]),
1930 getMDOrNull(Record[4]), Record[5],
1931 getMDOrNull(Record[6]), Record[7], Record[8],
1932 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1936 case bitc::METADATA_LOCAL_VAR: {
1937 // 10th field is for the obseleted 'inlinedAt:' field.
1938 if (Record.size() != 9 && Record.size() != 10)
1939 return Error("Invalid record");
1941 MDValueList.AssignValue(
1942 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1943 (Context, Record[1], getMDOrNull(Record[2]),
1944 getMDString(Record[3]), getMDOrNull(Record[4]),
1945 Record[5], getMDOrNull(Record[6]), Record[7],
1950 case bitc::METADATA_EXPRESSION: {
1951 if (Record.size() < 1)
1952 return Error("Invalid record");
1954 MDValueList.AssignValue(
1955 GET_OR_DISTINCT(MDExpression, Record[0],
1956 (Context, makeArrayRef(Record).slice(1))),
1960 case bitc::METADATA_OBJC_PROPERTY: {
1961 if (Record.size() != 8)
1962 return Error("Invalid record");
1964 MDValueList.AssignValue(
1965 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1966 (Context, getMDString(Record[1]),
1967 getMDOrNull(Record[2]), Record[3],
1968 getMDString(Record[4]), getMDString(Record[5]),
1969 Record[6], getMDOrNull(Record[7]))),
1973 case bitc::METADATA_IMPORTED_ENTITY: {
1974 if (Record.size() != 6)
1975 return Error("Invalid record");
1977 MDValueList.AssignValue(
1978 GET_OR_DISTINCT(MDImportedEntity, Record[0],
1979 (Context, Record[1], getMDOrNull(Record[2]),
1980 getMDOrNull(Record[3]), Record[4],
1981 getMDString(Record[5]))),
1985 case bitc::METADATA_STRING: {
1986 std::string String(Record.begin(), Record.end());
1987 llvm::UpgradeMDStringConstant(String);
1988 Metadata *MD = MDString::get(Context, String);
1989 MDValueList.AssignValue(MD, NextMDValueNo++);
1992 case bitc::METADATA_KIND: {
1993 if (Record.size() < 2)
1994 return Error("Invalid record");
1996 unsigned Kind = Record[0];
1997 SmallString<8> Name(Record.begin()+1, Record.end());
1999 unsigned NewKind = TheModule->getMDKindID(Name.str());
2000 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2001 return Error("Conflicting METADATA_KIND records");
2006 #undef GET_OR_DISTINCT
2009 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
2010 /// the LSB for dense VBR encoding.
2011 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2016 // There is no such thing as -0 with integers. "-0" really means MININT.
2020 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
2021 /// values and aliases that we can.
2022 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
2023 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2024 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2025 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2026 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2028 GlobalInitWorklist.swap(GlobalInits);
2029 AliasInitWorklist.swap(AliasInits);
2030 FunctionPrefixWorklist.swap(FunctionPrefixes);
2031 FunctionPrologueWorklist.swap(FunctionPrologues);
2033 while (!GlobalInitWorklist.empty()) {
2034 unsigned ValID = GlobalInitWorklist.back().second;
2035 if (ValID >= ValueList.size()) {
2036 // Not ready to resolve this yet, it requires something later in the file.
2037 GlobalInits.push_back(GlobalInitWorklist.back());
2039 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2040 GlobalInitWorklist.back().first->setInitializer(C);
2042 return Error("Expected a constant");
2044 GlobalInitWorklist.pop_back();
2047 while (!AliasInitWorklist.empty()) {
2048 unsigned ValID = AliasInitWorklist.back().second;
2049 if (ValID >= ValueList.size()) {
2050 AliasInits.push_back(AliasInitWorklist.back());
2052 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2053 AliasInitWorklist.back().first->setAliasee(C);
2055 return Error("Expected a constant");
2057 AliasInitWorklist.pop_back();
2060 while (!FunctionPrefixWorklist.empty()) {
2061 unsigned ValID = FunctionPrefixWorklist.back().second;
2062 if (ValID >= ValueList.size()) {
2063 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2065 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2066 FunctionPrefixWorklist.back().first->setPrefixData(C);
2068 return Error("Expected a constant");
2070 FunctionPrefixWorklist.pop_back();
2073 while (!FunctionPrologueWorklist.empty()) {
2074 unsigned ValID = FunctionPrologueWorklist.back().second;
2075 if (ValID >= ValueList.size()) {
2076 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2078 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2079 FunctionPrologueWorklist.back().first->setPrologueData(C);
2081 return Error("Expected a constant");
2083 FunctionPrologueWorklist.pop_back();
2086 return std::error_code();
2089 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2090 SmallVector<uint64_t, 8> Words(Vals.size());
2091 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2092 BitcodeReader::decodeSignRotatedValue);
2094 return APInt(TypeBits, Words);
2097 std::error_code BitcodeReader::ParseConstants() {
2098 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2099 return Error("Invalid record");
2101 SmallVector<uint64_t, 64> Record;
2103 // Read all the records for this value table.
2104 Type *CurTy = Type::getInt32Ty(Context);
2105 unsigned NextCstNo = ValueList.size();
2107 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2109 switch (Entry.Kind) {
2110 case BitstreamEntry::SubBlock: // Handled for us already.
2111 case BitstreamEntry::Error:
2112 return Error("Malformed block");
2113 case BitstreamEntry::EndBlock:
2114 if (NextCstNo != ValueList.size())
2115 return Error("Invalid ronstant reference");
2117 // Once all the constants have been read, go through and resolve forward
2119 ValueList.ResolveConstantForwardRefs();
2120 return std::error_code();
2121 case BitstreamEntry::Record:
2122 // The interesting case.
2129 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2131 default: // Default behavior: unknown constant
2132 case bitc::CST_CODE_UNDEF: // UNDEF
2133 V = UndefValue::get(CurTy);
2135 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2137 return Error("Invalid record");
2138 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2139 return Error("Invalid record");
2140 CurTy = TypeList[Record[0]];
2141 continue; // Skip the ValueList manipulation.
2142 case bitc::CST_CODE_NULL: // NULL
2143 V = Constant::getNullValue(CurTy);
2145 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2146 if (!CurTy->isIntegerTy() || Record.empty())
2147 return Error("Invalid record");
2148 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2150 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2151 if (!CurTy->isIntegerTy() || Record.empty())
2152 return Error("Invalid record");
2154 APInt VInt = ReadWideAPInt(Record,
2155 cast<IntegerType>(CurTy)->getBitWidth());
2156 V = ConstantInt::get(Context, VInt);
2160 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2162 return Error("Invalid record");
2163 if (CurTy->isHalfTy())
2164 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2165 APInt(16, (uint16_t)Record[0])));
2166 else if (CurTy->isFloatTy())
2167 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2168 APInt(32, (uint32_t)Record[0])));
2169 else if (CurTy->isDoubleTy())
2170 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2171 APInt(64, Record[0])));
2172 else if (CurTy->isX86_FP80Ty()) {
2173 // Bits are not stored the same way as a normal i80 APInt, compensate.
2174 uint64_t Rearrange[2];
2175 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2176 Rearrange[1] = Record[0] >> 48;
2177 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2178 APInt(80, Rearrange)));
2179 } else if (CurTy->isFP128Ty())
2180 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2181 APInt(128, Record)));
2182 else if (CurTy->isPPC_FP128Ty())
2183 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2184 APInt(128, Record)));
2186 V = UndefValue::get(CurTy);
2190 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2192 return Error("Invalid record");
2194 unsigned Size = Record.size();
2195 SmallVector<Constant*, 16> Elts;
2197 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2198 for (unsigned i = 0; i != Size; ++i)
2199 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2200 STy->getElementType(i)));
2201 V = ConstantStruct::get(STy, Elts);
2202 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2203 Type *EltTy = ATy->getElementType();
2204 for (unsigned i = 0; i != Size; ++i)
2205 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2206 V = ConstantArray::get(ATy, Elts);
2207 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2208 Type *EltTy = VTy->getElementType();
2209 for (unsigned i = 0; i != Size; ++i)
2210 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2211 V = ConstantVector::get(Elts);
2213 V = UndefValue::get(CurTy);
2217 case bitc::CST_CODE_STRING: // STRING: [values]
2218 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2220 return Error("Invalid record");
2222 SmallString<16> Elts(Record.begin(), Record.end());
2223 V = ConstantDataArray::getString(Context, Elts,
2224 BitCode == bitc::CST_CODE_CSTRING);
2227 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2229 return Error("Invalid record");
2231 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2232 unsigned Size = Record.size();
2234 if (EltTy->isIntegerTy(8)) {
2235 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2236 if (isa<VectorType>(CurTy))
2237 V = ConstantDataVector::get(Context, Elts);
2239 V = ConstantDataArray::get(Context, Elts);
2240 } else if (EltTy->isIntegerTy(16)) {
2241 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2242 if (isa<VectorType>(CurTy))
2243 V = ConstantDataVector::get(Context, Elts);
2245 V = ConstantDataArray::get(Context, Elts);
2246 } else if (EltTy->isIntegerTy(32)) {
2247 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2248 if (isa<VectorType>(CurTy))
2249 V = ConstantDataVector::get(Context, Elts);
2251 V = ConstantDataArray::get(Context, Elts);
2252 } else if (EltTy->isIntegerTy(64)) {
2253 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2254 if (isa<VectorType>(CurTy))
2255 V = ConstantDataVector::get(Context, Elts);
2257 V = ConstantDataArray::get(Context, Elts);
2258 } else if (EltTy->isFloatTy()) {
2259 SmallVector<float, 16> Elts(Size);
2260 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2261 if (isa<VectorType>(CurTy))
2262 V = ConstantDataVector::get(Context, Elts);
2264 V = ConstantDataArray::get(Context, Elts);
2265 } else if (EltTy->isDoubleTy()) {
2266 SmallVector<double, 16> Elts(Size);
2267 std::transform(Record.begin(), Record.end(), Elts.begin(),
2269 if (isa<VectorType>(CurTy))
2270 V = ConstantDataVector::get(Context, Elts);
2272 V = ConstantDataArray::get(Context, Elts);
2274 return Error("Invalid type for value");
2279 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2280 if (Record.size() < 3)
2281 return Error("Invalid record");
2282 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2284 V = UndefValue::get(CurTy); // Unknown binop.
2286 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2287 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2289 if (Record.size() >= 4) {
2290 if (Opc == Instruction::Add ||
2291 Opc == Instruction::Sub ||
2292 Opc == Instruction::Mul ||
2293 Opc == Instruction::Shl) {
2294 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2295 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2296 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2297 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2298 } else if (Opc == Instruction::SDiv ||
2299 Opc == Instruction::UDiv ||
2300 Opc == Instruction::LShr ||
2301 Opc == Instruction::AShr) {
2302 if (Record[3] & (1 << bitc::PEO_EXACT))
2303 Flags |= SDivOperator::IsExact;
2306 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2310 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2311 if (Record.size() < 3)
2312 return Error("Invalid record");
2313 int Opc = GetDecodedCastOpcode(Record[0]);
2315 V = UndefValue::get(CurTy); // Unknown cast.
2317 Type *OpTy = getTypeByID(Record[1]);
2319 return Error("Invalid record");
2320 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2321 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2322 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2326 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2327 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2329 Type *PointeeType = nullptr;
2330 if (Record.size() % 2)
2331 PointeeType = getTypeByID(Record[OpNum++]);
2332 SmallVector<Constant*, 16> Elts;
2333 while (OpNum != Record.size()) {
2334 Type *ElTy = getTypeByID(Record[OpNum++]);
2336 return Error("Invalid record");
2337 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2342 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2344 return Error("Explicit gep operator type does not match pointee type "
2345 "of pointer operand");
2347 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2348 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2350 bitc::CST_CODE_CE_INBOUNDS_GEP);
2353 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2354 if (Record.size() < 3)
2355 return Error("Invalid record");
2357 Type *SelectorTy = Type::getInt1Ty(Context);
2359 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2360 // vector. Otherwise, it must be a single bit.
2361 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2362 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2363 VTy->getNumElements());
2365 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2367 ValueList.getConstantFwdRef(Record[1],CurTy),
2368 ValueList.getConstantFwdRef(Record[2],CurTy));
2371 case bitc::CST_CODE_CE_EXTRACTELT
2372 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2373 if (Record.size() < 3)
2374 return Error("Invalid record");
2376 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2378 return Error("Invalid record");
2379 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2380 Constant *Op1 = nullptr;
2381 if (Record.size() == 4) {
2382 Type *IdxTy = getTypeByID(Record[2]);
2384 return Error("Invalid record");
2385 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2386 } else // TODO: Remove with llvm 4.0
2387 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2389 return Error("Invalid record");
2390 V = ConstantExpr::getExtractElement(Op0, Op1);
2393 case bitc::CST_CODE_CE_INSERTELT
2394 : { // CE_INSERTELT: [opval, opval, opty, opval]
2395 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2396 if (Record.size() < 3 || !OpTy)
2397 return Error("Invalid record");
2398 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2399 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2400 OpTy->getElementType());
2401 Constant *Op2 = nullptr;
2402 if (Record.size() == 4) {
2403 Type *IdxTy = getTypeByID(Record[2]);
2405 return Error("Invalid record");
2406 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2407 } else // TODO: Remove with llvm 4.0
2408 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2410 return Error("Invalid record");
2411 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2414 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2415 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2416 if (Record.size() < 3 || !OpTy)
2417 return Error("Invalid record");
2418 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2419 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2420 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2421 OpTy->getNumElements());
2422 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2423 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2426 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2427 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2429 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2430 if (Record.size() < 4 || !RTy || !OpTy)
2431 return Error("Invalid record");
2432 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2433 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2434 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2435 RTy->getNumElements());
2436 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2437 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2440 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2441 if (Record.size() < 4)
2442 return Error("Invalid record");
2443 Type *OpTy = getTypeByID(Record[0]);
2445 return Error("Invalid record");
2446 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2447 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2449 if (OpTy->isFPOrFPVectorTy())
2450 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2452 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2455 // This maintains backward compatibility, pre-asm dialect keywords.
2456 // FIXME: Remove with the 4.0 release.
2457 case bitc::CST_CODE_INLINEASM_OLD: {
2458 if (Record.size() < 2)
2459 return Error("Invalid record");
2460 std::string AsmStr, ConstrStr;
2461 bool HasSideEffects = Record[0] & 1;
2462 bool IsAlignStack = Record[0] >> 1;
2463 unsigned AsmStrSize = Record[1];
2464 if (2+AsmStrSize >= Record.size())
2465 return Error("Invalid record");
2466 unsigned ConstStrSize = Record[2+AsmStrSize];
2467 if (3+AsmStrSize+ConstStrSize > Record.size())
2468 return Error("Invalid record");
2470 for (unsigned i = 0; i != AsmStrSize; ++i)
2471 AsmStr += (char)Record[2+i];
2472 for (unsigned i = 0; i != ConstStrSize; ++i)
2473 ConstrStr += (char)Record[3+AsmStrSize+i];
2474 PointerType *PTy = cast<PointerType>(CurTy);
2475 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2476 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2479 // This version adds support for the asm dialect keywords (e.g.,
2481 case bitc::CST_CODE_INLINEASM: {
2482 if (Record.size() < 2)
2483 return Error("Invalid record");
2484 std::string AsmStr, ConstrStr;
2485 bool HasSideEffects = Record[0] & 1;
2486 bool IsAlignStack = (Record[0] >> 1) & 1;
2487 unsigned AsmDialect = Record[0] >> 2;
2488 unsigned AsmStrSize = Record[1];
2489 if (2+AsmStrSize >= Record.size())
2490 return Error("Invalid record");
2491 unsigned ConstStrSize = Record[2+AsmStrSize];
2492 if (3+AsmStrSize+ConstStrSize > Record.size())
2493 return Error("Invalid record");
2495 for (unsigned i = 0; i != AsmStrSize; ++i)
2496 AsmStr += (char)Record[2+i];
2497 for (unsigned i = 0; i != ConstStrSize; ++i)
2498 ConstrStr += (char)Record[3+AsmStrSize+i];
2499 PointerType *PTy = cast<PointerType>(CurTy);
2500 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2501 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2502 InlineAsm::AsmDialect(AsmDialect));
2505 case bitc::CST_CODE_BLOCKADDRESS:{
2506 if (Record.size() < 3)
2507 return Error("Invalid record");
2508 Type *FnTy = getTypeByID(Record[0]);
2510 return Error("Invalid record");
2512 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2514 return Error("Invalid record");
2516 // Don't let Fn get dematerialized.
2517 BlockAddressesTaken.insert(Fn);
2519 // If the function is already parsed we can insert the block address right
2522 unsigned BBID = Record[2];
2524 // Invalid reference to entry block.
2525 return Error("Invalid ID");
2527 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2528 for (size_t I = 0, E = BBID; I != E; ++I) {
2530 return Error("Invalid ID");
2535 // Otherwise insert a placeholder and remember it so it can be inserted
2536 // when the function is parsed.
2537 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2539 BasicBlockFwdRefQueue.push_back(Fn);
2540 if (FwdBBs.size() < BBID + 1)
2541 FwdBBs.resize(BBID + 1);
2543 FwdBBs[BBID] = BasicBlock::Create(Context);
2546 V = BlockAddress::get(Fn, BB);
2551 ValueList.AssignValue(V, NextCstNo);
2556 std::error_code BitcodeReader::ParseUseLists() {
2557 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2558 return Error("Invalid record");
2560 // Read all the records.
2561 SmallVector<uint64_t, 64> Record;
2563 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2565 switch (Entry.Kind) {
2566 case BitstreamEntry::SubBlock: // Handled for us already.
2567 case BitstreamEntry::Error:
2568 return Error("Malformed block");
2569 case BitstreamEntry::EndBlock:
2570 return std::error_code();
2571 case BitstreamEntry::Record:
2572 // The interesting case.
2576 // Read a use list record.
2579 switch (Stream.readRecord(Entry.ID, Record)) {
2580 default: // Default behavior: unknown type.
2582 case bitc::USELIST_CODE_BB:
2585 case bitc::USELIST_CODE_DEFAULT: {
2586 unsigned RecordLength = Record.size();
2587 if (RecordLength < 3)
2588 // Records should have at least an ID and two indexes.
2589 return Error("Invalid record");
2590 unsigned ID = Record.back();
2595 assert(ID < FunctionBBs.size() && "Basic block not found");
2596 V = FunctionBBs[ID];
2599 unsigned NumUses = 0;
2600 SmallDenseMap<const Use *, unsigned, 16> Order;
2601 for (const Use &U : V->uses()) {
2602 if (++NumUses > Record.size())
2604 Order[&U] = Record[NumUses - 1];
2606 if (Order.size() != Record.size() || NumUses > Record.size())
2607 // Mismatches can happen if the functions are being materialized lazily
2608 // (out-of-order), or a value has been upgraded.
2611 V->sortUseList([&](const Use &L, const Use &R) {
2612 return Order.lookup(&L) < Order.lookup(&R);
2620 /// When we see the block for metadata, remember where it is and then skip it.
2621 /// This lets us lazily deserialize the metadata.
2622 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2623 // Save the current stream state.
2624 uint64_t CurBit = Stream.GetCurrentBitNo();
2625 DeferredMetadataInfo.push_back(CurBit);
2627 // Skip over the block for now.
2628 if (Stream.SkipBlock())
2629 return Error("Invalid record");
2630 return std::error_code();
2633 std::error_code BitcodeReader::materializeMetadata() {
2634 for (uint64_t BitPos : DeferredMetadataInfo) {
2635 // Move the bit stream to the saved position.
2636 Stream.JumpToBit(BitPos);
2637 if (std::error_code EC = ParseMetadata())
2640 DeferredMetadataInfo.clear();
2641 return std::error_code();
2644 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2646 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2647 /// remember where it is and then skip it. This lets us lazily deserialize the
2649 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2650 // Get the function we are talking about.
2651 if (FunctionsWithBodies.empty())
2652 return Error("Insufficient function protos");
2654 Function *Fn = FunctionsWithBodies.back();
2655 FunctionsWithBodies.pop_back();
2657 // Save the current stream state.
2658 uint64_t CurBit = Stream.GetCurrentBitNo();
2659 DeferredFunctionInfo[Fn] = CurBit;
2661 // Skip over the function block for now.
2662 if (Stream.SkipBlock())
2663 return Error("Invalid record");
2664 return std::error_code();
2667 std::error_code BitcodeReader::GlobalCleanup() {
2668 // Patch the initializers for globals and aliases up.
2669 ResolveGlobalAndAliasInits();
2670 if (!GlobalInits.empty() || !AliasInits.empty())
2671 return Error("Malformed global initializer set");
2673 // Look for intrinsic functions which need to be upgraded at some point
2674 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2677 if (UpgradeIntrinsicFunction(FI, NewFn))
2678 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2681 // Look for global variables which need to be renamed.
2682 for (Module::global_iterator
2683 GI = TheModule->global_begin(), GE = TheModule->global_end();
2685 GlobalVariable *GV = GI++;
2686 UpgradeGlobalVariable(GV);
2689 // Force deallocation of memory for these vectors to favor the client that
2690 // want lazy deserialization.
2691 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2692 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2693 return std::error_code();
2696 std::error_code BitcodeReader::ParseModule(bool Resume,
2697 bool ShouldLazyLoadMetadata) {
2699 Stream.JumpToBit(NextUnreadBit);
2700 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2701 return Error("Invalid record");
2703 SmallVector<uint64_t, 64> Record;
2704 std::vector<std::string> SectionTable;
2705 std::vector<std::string> GCTable;
2707 // Read all the records for this module.
2709 BitstreamEntry Entry = Stream.advance();
2711 switch (Entry.Kind) {
2712 case BitstreamEntry::Error:
2713 return Error("Malformed block");
2714 case BitstreamEntry::EndBlock:
2715 return GlobalCleanup();
2717 case BitstreamEntry::SubBlock:
2719 default: // Skip unknown content.
2720 if (Stream.SkipBlock())
2721 return Error("Invalid record");
2723 case bitc::BLOCKINFO_BLOCK_ID:
2724 if (Stream.ReadBlockInfoBlock())
2725 return Error("Malformed block");
2727 case bitc::PARAMATTR_BLOCK_ID:
2728 if (std::error_code EC = ParseAttributeBlock())
2731 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2732 if (std::error_code EC = ParseAttributeGroupBlock())
2735 case bitc::TYPE_BLOCK_ID_NEW:
2736 if (std::error_code EC = ParseTypeTable())
2739 case bitc::VALUE_SYMTAB_BLOCK_ID:
2740 if (std::error_code EC = ParseValueSymbolTable())
2742 SeenValueSymbolTable = true;
2744 case bitc::CONSTANTS_BLOCK_ID:
2745 if (std::error_code EC = ParseConstants())
2747 if (std::error_code EC = ResolveGlobalAndAliasInits())
2750 case bitc::METADATA_BLOCK_ID:
2751 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2752 if (std::error_code EC = rememberAndSkipMetadata())
2756 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2757 if (std::error_code EC = ParseMetadata())
2760 case bitc::FUNCTION_BLOCK_ID:
2761 // If this is the first function body we've seen, reverse the
2762 // FunctionsWithBodies list.
2763 if (!SeenFirstFunctionBody) {
2764 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2765 if (std::error_code EC = GlobalCleanup())
2767 SeenFirstFunctionBody = true;
2770 if (std::error_code EC = RememberAndSkipFunctionBody())
2772 // For streaming bitcode, suspend parsing when we reach the function
2773 // bodies. Subsequent materialization calls will resume it when
2774 // necessary. For streaming, the function bodies must be at the end of
2775 // the bitcode. If the bitcode file is old, the symbol table will be
2776 // at the end instead and will not have been seen yet. In this case,
2777 // just finish the parse now.
2778 if (LazyStreamer && SeenValueSymbolTable) {
2779 NextUnreadBit = Stream.GetCurrentBitNo();
2780 return std::error_code();
2783 case bitc::USELIST_BLOCK_ID:
2784 if (std::error_code EC = ParseUseLists())
2790 case BitstreamEntry::Record:
2791 // The interesting case.
2797 switch (Stream.readRecord(Entry.ID, Record)) {
2798 default: break; // Default behavior, ignore unknown content.
2799 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2800 if (Record.size() < 1)
2801 return Error("Invalid record");
2802 // Only version #0 and #1 are supported so far.
2803 unsigned module_version = Record[0];
2804 switch (module_version) {
2806 return Error("Invalid value");
2808 UseRelativeIDs = false;
2811 UseRelativeIDs = true;
2816 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2818 if (ConvertToString(Record, 0, S))
2819 return Error("Invalid record");
2820 TheModule->setTargetTriple(S);
2823 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2825 if (ConvertToString(Record, 0, S))
2826 return Error("Invalid record");
2827 TheModule->setDataLayout(S);
2830 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2832 if (ConvertToString(Record, 0, S))
2833 return Error("Invalid record");
2834 TheModule->setModuleInlineAsm(S);
2837 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2838 // FIXME: Remove in 4.0.
2840 if (ConvertToString(Record, 0, S))
2841 return Error("Invalid record");
2845 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2847 if (ConvertToString(Record, 0, S))
2848 return Error("Invalid record");
2849 SectionTable.push_back(S);
2852 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2854 if (ConvertToString(Record, 0, S))
2855 return Error("Invalid record");
2856 GCTable.push_back(S);
2859 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2860 if (Record.size() < 2)
2861 return Error("Invalid record");
2862 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2863 unsigned ComdatNameSize = Record[1];
2864 std::string ComdatName;
2865 ComdatName.reserve(ComdatNameSize);
2866 for (unsigned i = 0; i != ComdatNameSize; ++i)
2867 ComdatName += (char)Record[2 + i];
2868 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2869 C->setSelectionKind(SK);
2870 ComdatList.push_back(C);
2873 // GLOBALVAR: [pointer type, isconst, initid,
2874 // linkage, alignment, section, visibility, threadlocal,
2875 // unnamed_addr, externally_initialized, dllstorageclass,
2877 case bitc::MODULE_CODE_GLOBALVAR: {
2878 if (Record.size() < 6)
2879 return Error("Invalid record");
2880 Type *Ty = getTypeByID(Record[0]);
2882 return Error("Invalid record");
2883 bool isConstant = Record[1] & 1;
2884 bool explicitType = Record[1] & 2;
2885 unsigned AddressSpace;
2887 AddressSpace = Record[1] >> 2;
2889 if (!Ty->isPointerTy())
2890 return Error("Invalid type for value");
2891 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2892 Ty = cast<PointerType>(Ty)->getElementType();
2895 uint64_t RawLinkage = Record[3];
2896 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2898 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2900 std::string Section;
2902 if (Record[5]-1 >= SectionTable.size())
2903 return Error("Invalid ID");
2904 Section = SectionTable[Record[5]-1];
2906 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2907 // Local linkage must have default visibility.
2908 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2909 // FIXME: Change to an error if non-default in 4.0.
2910 Visibility = GetDecodedVisibility(Record[6]);
2912 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2913 if (Record.size() > 7)
2914 TLM = GetDecodedThreadLocalMode(Record[7]);
2916 bool UnnamedAddr = false;
2917 if (Record.size() > 8)
2918 UnnamedAddr = Record[8];
2920 bool ExternallyInitialized = false;
2921 if (Record.size() > 9)
2922 ExternallyInitialized = Record[9];
2924 GlobalVariable *NewGV =
2925 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2926 TLM, AddressSpace, ExternallyInitialized);
2927 NewGV->setAlignment(Alignment);
2928 if (!Section.empty())
2929 NewGV->setSection(Section);
2930 NewGV->setVisibility(Visibility);
2931 NewGV->setUnnamedAddr(UnnamedAddr);
2933 if (Record.size() > 10)
2934 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2936 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2938 ValueList.push_back(NewGV);
2940 // Remember which value to use for the global initializer.
2941 if (unsigned InitID = Record[2])
2942 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2944 if (Record.size() > 11) {
2945 if (unsigned ComdatID = Record[11]) {
2946 assert(ComdatID <= ComdatList.size());
2947 NewGV->setComdat(ComdatList[ComdatID - 1]);
2949 } else if (hasImplicitComdat(RawLinkage)) {
2950 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2954 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2955 // alignment, section, visibility, gc, unnamed_addr,
2956 // prologuedata, dllstorageclass, comdat, prefixdata]
2957 case bitc::MODULE_CODE_FUNCTION: {
2958 if (Record.size() < 8)
2959 return Error("Invalid record");
2960 Type *Ty = getTypeByID(Record[0]);
2962 return Error("Invalid record");
2963 if (auto *PTy = dyn_cast<PointerType>(Ty))
2964 Ty = PTy->getElementType();
2965 auto *FTy = dyn_cast<FunctionType>(Ty);
2967 return Error("Invalid type for value");
2969 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2972 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2973 bool isProto = Record[2];
2974 uint64_t RawLinkage = Record[3];
2975 Func->setLinkage(getDecodedLinkage(RawLinkage));
2976 Func->setAttributes(getAttributes(Record[4]));
2979 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2981 Func->setAlignment(Alignment);
2983 if (Record[6]-1 >= SectionTable.size())
2984 return Error("Invalid ID");
2985 Func->setSection(SectionTable[Record[6]-1]);
2987 // Local linkage must have default visibility.
2988 if (!Func->hasLocalLinkage())
2989 // FIXME: Change to an error if non-default in 4.0.
2990 Func->setVisibility(GetDecodedVisibility(Record[7]));
2991 if (Record.size() > 8 && Record[8]) {
2992 if (Record[8]-1 > GCTable.size())
2993 return Error("Invalid ID");
2994 Func->setGC(GCTable[Record[8]-1].c_str());
2996 bool UnnamedAddr = false;
2997 if (Record.size() > 9)
2998 UnnamedAddr = Record[9];
2999 Func->setUnnamedAddr(UnnamedAddr);
3000 if (Record.size() > 10 && Record[10] != 0)
3001 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3003 if (Record.size() > 11)
3004 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
3006 UpgradeDLLImportExportLinkage(Func, RawLinkage);
3008 if (Record.size() > 12) {
3009 if (unsigned ComdatID = Record[12]) {
3010 assert(ComdatID <= ComdatList.size());
3011 Func->setComdat(ComdatList[ComdatID - 1]);
3013 } else if (hasImplicitComdat(RawLinkage)) {
3014 Func->setComdat(reinterpret_cast<Comdat *>(1));
3017 if (Record.size() > 13 && Record[13] != 0)
3018 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3020 ValueList.push_back(Func);
3022 // If this is a function with a body, remember the prototype we are
3023 // creating now, so that we can match up the body with them later.
3025 Func->setIsMaterializable(true);
3026 FunctionsWithBodies.push_back(Func);
3028 DeferredFunctionInfo[Func] = 0;
3032 // ALIAS: [alias type, aliasee val#, linkage]
3033 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3034 case bitc::MODULE_CODE_ALIAS: {
3035 if (Record.size() < 3)
3036 return Error("Invalid record");
3037 Type *Ty = getTypeByID(Record[0]);
3039 return Error("Invalid record");
3040 auto *PTy = dyn_cast<PointerType>(Ty);
3042 return Error("Invalid type for value");
3045 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
3046 getDecodedLinkage(Record[2]), "", TheModule);
3047 // Old bitcode files didn't have visibility field.
3048 // Local linkage must have default visibility.
3049 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3050 // FIXME: Change to an error if non-default in 4.0.
3051 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3052 if (Record.size() > 4)
3053 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3055 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3056 if (Record.size() > 5)
3057 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3058 if (Record.size() > 6)
3059 NewGA->setUnnamedAddr(Record[6]);
3060 ValueList.push_back(NewGA);
3061 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3064 /// MODULE_CODE_PURGEVALS: [numvals]
3065 case bitc::MODULE_CODE_PURGEVALS:
3066 // Trim down the value list to the specified size.
3067 if (Record.size() < 1 || Record[0] > ValueList.size())
3068 return Error("Invalid record");
3069 ValueList.shrinkTo(Record[0]);
3076 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3077 bool ShouldLazyLoadMetadata) {
3078 TheModule = nullptr;
3080 if (std::error_code EC = InitStream())
3083 // Sniff for the signature.
3084 if (Stream.Read(8) != 'B' ||
3085 Stream.Read(8) != 'C' ||
3086 Stream.Read(4) != 0x0 ||
3087 Stream.Read(4) != 0xC ||
3088 Stream.Read(4) != 0xE ||
3089 Stream.Read(4) != 0xD)
3090 return Error("Invalid bitcode signature");
3092 // We expect a number of well-defined blocks, though we don't necessarily
3093 // need to understand them all.
3095 if (Stream.AtEndOfStream()) {
3097 return std::error_code();
3098 // We didn't really read a proper Module.
3099 return Error("Malformed IR file");
3102 BitstreamEntry Entry =
3103 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3105 switch (Entry.Kind) {
3106 case BitstreamEntry::Error:
3107 return Error("Malformed block");
3108 case BitstreamEntry::EndBlock:
3109 return std::error_code();
3111 case BitstreamEntry::SubBlock:
3113 case bitc::BLOCKINFO_BLOCK_ID:
3114 if (Stream.ReadBlockInfoBlock())
3115 return Error("Malformed block");
3117 case bitc::MODULE_BLOCK_ID:
3118 // Reject multiple MODULE_BLOCK's in a single bitstream.
3120 return Error("Invalid multiple blocks");
3122 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3125 return std::error_code();
3128 if (Stream.SkipBlock())
3129 return Error("Invalid record");
3133 case BitstreamEntry::Record:
3134 // There should be no records in the top-level of blocks.
3136 // The ranlib in Xcode 4 will align archive members by appending newlines
3137 // to the end of them. If this file size is a multiple of 4 but not 8, we
3138 // have to read and ignore these final 4 bytes :-(
3139 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3140 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3141 Stream.AtEndOfStream())
3142 return std::error_code();
3144 return Error("Invalid record");
3149 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3150 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3151 return Error("Invalid record");
3153 SmallVector<uint64_t, 64> Record;
3156 // Read all the records for this module.
3158 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3160 switch (Entry.Kind) {
3161 case BitstreamEntry::SubBlock: // Handled for us already.
3162 case BitstreamEntry::Error:
3163 return Error("Malformed block");
3164 case BitstreamEntry::EndBlock:
3166 case BitstreamEntry::Record:
3167 // The interesting case.
3172 switch (Stream.readRecord(Entry.ID, Record)) {
3173 default: break; // Default behavior, ignore unknown content.
3174 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3176 if (ConvertToString(Record, 0, S))
3177 return Error("Invalid record");
3184 llvm_unreachable("Exit infinite loop");
3187 ErrorOr<std::string> BitcodeReader::parseTriple() {
3188 if (std::error_code EC = InitStream())
3191 // Sniff for the signature.
3192 if (Stream.Read(8) != 'B' ||
3193 Stream.Read(8) != 'C' ||
3194 Stream.Read(4) != 0x0 ||
3195 Stream.Read(4) != 0xC ||
3196 Stream.Read(4) != 0xE ||
3197 Stream.Read(4) != 0xD)
3198 return Error("Invalid bitcode signature");
3200 // We expect a number of well-defined blocks, though we don't necessarily
3201 // need to understand them all.
3203 BitstreamEntry Entry = Stream.advance();
3205 switch (Entry.Kind) {
3206 case BitstreamEntry::Error:
3207 return Error("Malformed block");
3208 case BitstreamEntry::EndBlock:
3209 return std::error_code();
3211 case BitstreamEntry::SubBlock:
3212 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3213 return parseModuleTriple();
3215 // Ignore other sub-blocks.
3216 if (Stream.SkipBlock())
3217 return Error("Malformed block");
3220 case BitstreamEntry::Record:
3221 Stream.skipRecord(Entry.ID);
3227 /// ParseMetadataAttachment - Parse metadata attachments.
3228 std::error_code BitcodeReader::ParseMetadataAttachment(Function &F) {
3229 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3230 return Error("Invalid record");
3232 SmallVector<uint64_t, 64> Record;
3234 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3236 switch (Entry.Kind) {
3237 case BitstreamEntry::SubBlock: // Handled for us already.
3238 case BitstreamEntry::Error:
3239 return Error("Malformed block");
3240 case BitstreamEntry::EndBlock:
3241 return std::error_code();
3242 case BitstreamEntry::Record:
3243 // The interesting case.
3247 // Read a metadata attachment record.
3249 switch (Stream.readRecord(Entry.ID, Record)) {
3250 default: // Default behavior: ignore.
3252 case bitc::METADATA_ATTACHMENT: {
3253 unsigned RecordLength = Record.size();
3255 return Error("Invalid record");
3256 if (RecordLength % 2 == 0) {
3257 // A function attachment.
3258 for (unsigned I = 0; I != RecordLength; I += 2) {
3259 auto K = MDKindMap.find(Record[I]);
3260 if (K == MDKindMap.end())
3261 return Error("Invalid ID");
3262 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3263 F.setMetadata(K->second, cast<MDNode>(MD));
3268 // An instruction attachment.
3269 Instruction *Inst = InstructionList[Record[0]];
3270 for (unsigned i = 1; i != RecordLength; i = i+2) {
3271 unsigned Kind = Record[i];
3272 DenseMap<unsigned, unsigned>::iterator I =
3273 MDKindMap.find(Kind);
3274 if (I == MDKindMap.end())
3275 return Error("Invalid ID");
3276 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3277 if (isa<LocalAsMetadata>(Node))
3278 // Drop the attachment. This used to be legal, but there's no
3281 Inst->setMetadata(I->second, cast<MDNode>(Node));
3282 if (I->second == LLVMContext::MD_tbaa)
3283 InstsWithTBAATag.push_back(Inst);
3291 /// ParseFunctionBody - Lazily parse the specified function body block.
3292 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3293 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3294 return Error("Invalid record");
3296 InstructionList.clear();
3297 unsigned ModuleValueListSize = ValueList.size();
3298 unsigned ModuleMDValueListSize = MDValueList.size();
3300 // Add all the function arguments to the value table.
3301 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3302 ValueList.push_back(I);
3304 unsigned NextValueNo = ValueList.size();
3305 BasicBlock *CurBB = nullptr;
3306 unsigned CurBBNo = 0;
3309 auto getLastInstruction = [&]() -> Instruction * {
3310 if (CurBB && !CurBB->empty())
3311 return &CurBB->back();
3312 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3313 !FunctionBBs[CurBBNo - 1]->empty())
3314 return &FunctionBBs[CurBBNo - 1]->back();
3318 // Read all the records.
3319 SmallVector<uint64_t, 64> Record;
3321 BitstreamEntry Entry = Stream.advance();
3323 switch (Entry.Kind) {
3324 case BitstreamEntry::Error:
3325 return Error("Malformed block");
3326 case BitstreamEntry::EndBlock:
3327 goto OutOfRecordLoop;
3329 case BitstreamEntry::SubBlock:
3331 default: // Skip unknown content.
3332 if (Stream.SkipBlock())
3333 return Error("Invalid record");
3335 case bitc::CONSTANTS_BLOCK_ID:
3336 if (std::error_code EC = ParseConstants())
3338 NextValueNo = ValueList.size();
3340 case bitc::VALUE_SYMTAB_BLOCK_ID:
3341 if (std::error_code EC = ParseValueSymbolTable())
3344 case bitc::METADATA_ATTACHMENT_ID:
3345 if (std::error_code EC = ParseMetadataAttachment(*F))
3348 case bitc::METADATA_BLOCK_ID:
3349 if (std::error_code EC = ParseMetadata())
3352 case bitc::USELIST_BLOCK_ID:
3353 if (std::error_code EC = ParseUseLists())
3359 case BitstreamEntry::Record:
3360 // The interesting case.
3366 Instruction *I = nullptr;
3367 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3369 default: // Default behavior: reject
3370 return Error("Invalid value");
3371 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3372 if (Record.size() < 1 || Record[0] == 0)
3373 return Error("Invalid record");
3374 // Create all the basic blocks for the function.
3375 FunctionBBs.resize(Record[0]);
3377 // See if anything took the address of blocks in this function.
3378 auto BBFRI = BasicBlockFwdRefs.find(F);
3379 if (BBFRI == BasicBlockFwdRefs.end()) {
3380 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3381 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3383 auto &BBRefs = BBFRI->second;
3384 // Check for invalid basic block references.
3385 if (BBRefs.size() > FunctionBBs.size())
3386 return Error("Invalid ID");
3387 assert(!BBRefs.empty() && "Unexpected empty array");
3388 assert(!BBRefs.front() && "Invalid reference to entry block");
3389 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3391 if (I < RE && BBRefs[I]) {
3392 BBRefs[I]->insertInto(F);
3393 FunctionBBs[I] = BBRefs[I];
3395 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3398 // Erase from the table.
3399 BasicBlockFwdRefs.erase(BBFRI);
3402 CurBB = FunctionBBs[0];
3406 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3407 // This record indicates that the last instruction is at the same
3408 // location as the previous instruction with a location.
3409 I = getLastInstruction();
3412 return Error("Invalid record");
3413 I->setDebugLoc(LastLoc);
3417 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3418 I = getLastInstruction();
3419 if (!I || Record.size() < 4)
3420 return Error("Invalid record");
3422 unsigned Line = Record[0], Col = Record[1];
3423 unsigned ScopeID = Record[2], IAID = Record[3];
3425 MDNode *Scope = nullptr, *IA = nullptr;
3426 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3427 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3428 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3429 I->setDebugLoc(LastLoc);
3434 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3437 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3438 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3439 OpNum+1 > Record.size())
3440 return Error("Invalid record");
3442 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3444 return Error("Invalid record");
3445 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3446 InstructionList.push_back(I);
3447 if (OpNum < Record.size()) {
3448 if (Opc == Instruction::Add ||
3449 Opc == Instruction::Sub ||
3450 Opc == Instruction::Mul ||
3451 Opc == Instruction::Shl) {
3452 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3453 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3454 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3455 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3456 } else if (Opc == Instruction::SDiv ||
3457 Opc == Instruction::UDiv ||
3458 Opc == Instruction::LShr ||
3459 Opc == Instruction::AShr) {
3460 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3461 cast<BinaryOperator>(I)->setIsExact(true);
3462 } else if (isa<FPMathOperator>(I)) {
3464 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3465 FMF.setUnsafeAlgebra();
3466 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3468 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3470 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3471 FMF.setNoSignedZeros();
3472 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3473 FMF.setAllowReciprocal();
3475 I->setFastMathFlags(FMF);
3481 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3484 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3485 OpNum+2 != Record.size())
3486 return Error("Invalid record");
3488 Type *ResTy = getTypeByID(Record[OpNum]);
3489 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3490 if (Opc == -1 || !ResTy)
3491 return Error("Invalid record");
3492 Instruction *Temp = nullptr;
3493 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3495 InstructionList.push_back(Temp);
3496 CurBB->getInstList().push_back(Temp);
3499 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3501 InstructionList.push_back(I);
3504 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3505 case bitc::FUNC_CODE_INST_GEP_OLD:
3506 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3512 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3513 InBounds = Record[OpNum++];
3514 Ty = getTypeByID(Record[OpNum++]);
3516 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3521 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3522 return Error("Invalid record");
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 SmallVector<unsigned, 4> EXTRACTVALIdx;
3555 Type *CurTy = Agg->getType();
3556 for (unsigned RecSize = Record.size();
3557 OpNum != RecSize; ++OpNum) {
3558 bool IsArray = CurTy->isArrayTy();
3559 bool IsStruct = CurTy->isStructTy();
3560 uint64_t Index = Record[OpNum];
3562 if (!IsStruct && !IsArray)
3563 return Error("EXTRACTVAL: Invalid type");
3564 if ((unsigned)Index != Index)
3565 return Error("Invalid value");
3566 if (IsStruct && Index >= CurTy->subtypes().size())
3567 return Error("EXTRACTVAL: Invalid struct index");
3568 if (IsArray && Index >= CurTy->getArrayNumElements())
3569 return Error("EXTRACTVAL: Invalid array index");
3570 EXTRACTVALIdx.push_back((unsigned)Index);
3573 CurTy = CurTy->subtypes()[Index];
3575 CurTy = CurTy->subtypes()[0];
3578 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3579 InstructionList.push_back(I);
3583 case bitc::FUNC_CODE_INST_INSERTVAL: {
3584 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3587 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3588 return Error("Invalid record");
3590 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3591 return Error("Invalid record");
3593 SmallVector<unsigned, 4> INSERTVALIdx;
3594 Type *CurTy = Agg->getType();
3595 for (unsigned RecSize = Record.size();
3596 OpNum != RecSize; ++OpNum) {
3597 bool IsArray = CurTy->isArrayTy();
3598 bool IsStruct = CurTy->isStructTy();
3599 uint64_t Index = Record[OpNum];
3601 if (!IsStruct && !IsArray)
3602 return Error("INSERTVAL: Invalid type");
3603 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3604 return Error("Invalid type");
3605 if ((unsigned)Index != Index)
3606 return Error("Invalid value");
3607 if (IsStruct && Index >= CurTy->subtypes().size())
3608 return Error("INSERTVAL: Invalid struct index");
3609 if (IsArray && Index >= CurTy->getArrayNumElements())
3610 return Error("INSERTVAL: Invalid array index");
3612 INSERTVALIdx.push_back((unsigned)Index);
3614 CurTy = CurTy->subtypes()[Index];
3616 CurTy = CurTy->subtypes()[0];
3619 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3620 InstructionList.push_back(I);
3624 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3625 // obsolete form of select
3626 // handles select i1 ... in old bitcode
3628 Value *TrueVal, *FalseVal, *Cond;
3629 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3630 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3631 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3632 return Error("Invalid record");
3634 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3635 InstructionList.push_back(I);
3639 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3640 // new form of select
3641 // handles select i1 or select [N x i1]
3643 Value *TrueVal, *FalseVal, *Cond;
3644 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3645 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3646 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3647 return Error("Invalid record");
3649 // select condition can be either i1 or [N x i1]
3650 if (VectorType* vector_type =
3651 dyn_cast<VectorType>(Cond->getType())) {
3653 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3654 return Error("Invalid type for value");
3657 if (Cond->getType() != Type::getInt1Ty(Context))
3658 return Error("Invalid type for value");
3661 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3662 InstructionList.push_back(I);
3666 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3669 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3670 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3671 return Error("Invalid record");
3672 if (!Vec->getType()->isVectorTy())
3673 return Error("Invalid type for value");
3674 I = ExtractElementInst::Create(Vec, Idx);
3675 InstructionList.push_back(I);
3679 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3681 Value *Vec, *Elt, *Idx;
3682 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3683 return Error("Invalid record");
3684 if (!Vec->getType()->isVectorTy())
3685 return Error("Invalid type for value");
3686 if (popValue(Record, OpNum, NextValueNo,
3687 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3688 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3689 return Error("Invalid record");
3690 I = InsertElementInst::Create(Vec, Elt, Idx);
3691 InstructionList.push_back(I);
3695 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3697 Value *Vec1, *Vec2, *Mask;
3698 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3699 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3700 return Error("Invalid record");
3702 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3703 return Error("Invalid record");
3704 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3705 return Error("Invalid type for value");
3706 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3707 InstructionList.push_back(I);
3711 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3712 // Old form of ICmp/FCmp returning bool
3713 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3714 // both legal on vectors but had different behaviour.
3715 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3716 // FCmp/ICmp returning bool or vector of bool
3720 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3721 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3722 OpNum+1 != Record.size())
3723 return Error("Invalid record");
3725 if (LHS->getType()->isFPOrFPVectorTy())
3726 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3728 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3729 InstructionList.push_back(I);
3733 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3735 unsigned Size = Record.size();
3737 I = ReturnInst::Create(Context);
3738 InstructionList.push_back(I);
3743 Value *Op = nullptr;
3744 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3745 return Error("Invalid record");
3746 if (OpNum != Record.size())
3747 return Error("Invalid record");
3749 I = ReturnInst::Create(Context, Op);
3750 InstructionList.push_back(I);
3753 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3754 if (Record.size() != 1 && Record.size() != 3)
3755 return Error("Invalid record");
3756 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3758 return Error("Invalid record");
3760 if (Record.size() == 1) {
3761 I = BranchInst::Create(TrueDest);
3762 InstructionList.push_back(I);
3765 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3766 Value *Cond = getValue(Record, 2, NextValueNo,
3767 Type::getInt1Ty(Context));
3768 if (!FalseDest || !Cond)
3769 return Error("Invalid record");
3770 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3771 InstructionList.push_back(I);
3775 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3777 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3778 // "New" SwitchInst format with case ranges. The changes to write this
3779 // format were reverted but we still recognize bitcode that uses it.
3780 // Hopefully someday we will have support for case ranges and can use
3781 // this format again.
3783 Type *OpTy = getTypeByID(Record[1]);
3784 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3786 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3787 BasicBlock *Default = getBasicBlock(Record[3]);
3788 if (!OpTy || !Cond || !Default)
3789 return Error("Invalid record");
3791 unsigned NumCases = Record[4];
3793 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3794 InstructionList.push_back(SI);
3796 unsigned CurIdx = 5;
3797 for (unsigned i = 0; i != NumCases; ++i) {
3798 SmallVector<ConstantInt*, 1> CaseVals;
3799 unsigned NumItems = Record[CurIdx++];
3800 for (unsigned ci = 0; ci != NumItems; ++ci) {
3801 bool isSingleNumber = Record[CurIdx++];
3804 unsigned ActiveWords = 1;
3805 if (ValueBitWidth > 64)
3806 ActiveWords = Record[CurIdx++];
3807 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3809 CurIdx += ActiveWords;
3811 if (!isSingleNumber) {
3813 if (ValueBitWidth > 64)
3814 ActiveWords = Record[CurIdx++];
3816 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3818 CurIdx += ActiveWords;
3820 // FIXME: It is not clear whether values in the range should be
3821 // compared as signed or unsigned values. The partially
3822 // implemented changes that used this format in the past used
3823 // unsigned comparisons.
3824 for ( ; Low.ule(High); ++Low)
3825 CaseVals.push_back(ConstantInt::get(Context, Low));
3827 CaseVals.push_back(ConstantInt::get(Context, Low));
3829 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3830 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3831 cve = CaseVals.end(); cvi != cve; ++cvi)
3832 SI->addCase(*cvi, DestBB);
3838 // Old SwitchInst format without case ranges.
3840 if (Record.size() < 3 || (Record.size() & 1) == 0)
3841 return Error("Invalid record");
3842 Type *OpTy = getTypeByID(Record[0]);
3843 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3844 BasicBlock *Default = getBasicBlock(Record[2]);
3845 if (!OpTy || !Cond || !Default)
3846 return Error("Invalid record");
3847 unsigned NumCases = (Record.size()-3)/2;
3848 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3849 InstructionList.push_back(SI);
3850 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3851 ConstantInt *CaseVal =
3852 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3853 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3854 if (!CaseVal || !DestBB) {
3856 return Error("Invalid record");
3858 SI->addCase(CaseVal, DestBB);
3863 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3864 if (Record.size() < 2)
3865 return Error("Invalid record");
3866 Type *OpTy = getTypeByID(Record[0]);
3867 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3868 if (!OpTy || !Address)
3869 return Error("Invalid record");
3870 unsigned NumDests = Record.size()-2;
3871 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3872 InstructionList.push_back(IBI);
3873 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3874 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3875 IBI->addDestination(DestBB);
3878 return Error("Invalid record");
3885 case bitc::FUNC_CODE_INST_INVOKE: {
3886 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3887 if (Record.size() < 4)
3888 return Error("Invalid record");
3890 AttributeSet PAL = getAttributes(Record[OpNum++]);
3891 unsigned CCInfo = Record[OpNum++];
3892 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3893 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3895 FunctionType *FTy = nullptr;
3896 if (CCInfo >> 13 & 1 &&
3897 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3898 return Error("Explicit invoke type is not a function type");
3901 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3902 return Error("Invalid record");
3904 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3906 return Error("Callee is not a pointer");
3908 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3910 return Error("Callee is not of pointer to function type");
3911 } else if (CalleeTy->getElementType() != FTy)
3912 return Error("Explicit invoke type does not match pointee type of "
3914 if (Record.size() < FTy->getNumParams() + OpNum)
3915 return Error("Insufficient operands to call");
3917 SmallVector<Value*, 16> Ops;
3918 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3919 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3920 FTy->getParamType(i)));
3922 return Error("Invalid record");
3925 if (!FTy->isVarArg()) {
3926 if (Record.size() != OpNum)
3927 return Error("Invalid record");
3929 // Read type/value pairs for varargs params.
3930 while (OpNum != Record.size()) {
3932 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3933 return Error("Invalid record");
3938 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3939 InstructionList.push_back(I);
3941 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
3942 cast<InvokeInst>(I)->setAttributes(PAL);
3945 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3947 Value *Val = nullptr;
3948 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3949 return Error("Invalid record");
3950 I = ResumeInst::Create(Val);
3951 InstructionList.push_back(I);
3954 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3955 I = new UnreachableInst(Context);
3956 InstructionList.push_back(I);
3958 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3959 if (Record.size() < 1 || ((Record.size()-1)&1))
3960 return Error("Invalid record");
3961 Type *Ty = getTypeByID(Record[0]);
3963 return Error("Invalid record");
3965 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3966 InstructionList.push_back(PN);
3968 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3970 // With the new function encoding, it is possible that operands have
3971 // negative IDs (for forward references). Use a signed VBR
3972 // representation to keep the encoding small.
3974 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3976 V = getValue(Record, 1+i, NextValueNo, Ty);
3977 BasicBlock *BB = getBasicBlock(Record[2+i]);
3979 return Error("Invalid record");
3980 PN->addIncoming(V, BB);
3986 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3987 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3989 if (Record.size() < 4)
3990 return Error("Invalid record");
3991 Type *Ty = getTypeByID(Record[Idx++]);
3993 return Error("Invalid record");
3994 Value *PersFn = nullptr;
3995 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3996 return Error("Invalid record");
3998 bool IsCleanup = !!Record[Idx++];
3999 unsigned NumClauses = Record[Idx++];
4000 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
4001 LP->setCleanup(IsCleanup);
4002 for (unsigned J = 0; J != NumClauses; ++J) {
4003 LandingPadInst::ClauseType CT =
4004 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4007 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4009 return Error("Invalid record");
4012 assert((CT != LandingPadInst::Catch ||
4013 !isa<ArrayType>(Val->getType())) &&
4014 "Catch clause has a invalid type!");
4015 assert((CT != LandingPadInst::Filter ||
4016 isa<ArrayType>(Val->getType())) &&
4017 "Filter clause has invalid type!");
4018 LP->addClause(cast<Constant>(Val));
4022 InstructionList.push_back(I);
4026 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4027 if (Record.size() != 4)
4028 return Error("Invalid record");
4029 uint64_t AlignRecord = Record[3];
4030 const uint64_t InAllocaMask = uint64_t(1) << 5;
4031 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4032 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4033 bool InAlloca = AlignRecord & InAllocaMask;
4034 Type *Ty = getTypeByID(Record[0]);
4035 if ((AlignRecord & ExplicitTypeMask) == 0) {
4036 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4038 return Error("Old-style alloca with a non-pointer type");
4039 Ty = PTy->getElementType();
4041 Type *OpTy = getTypeByID(Record[1]);
4042 Value *Size = getFnValueByID(Record[2], OpTy);
4044 if (std::error_code EC =
4045 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4049 return Error("Invalid record");
4050 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4051 AI->setUsedWithInAlloca(InAlloca);
4053 InstructionList.push_back(I);
4056 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4059 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4060 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4061 return Error("Invalid record");
4064 if (OpNum + 3 == Record.size())
4065 Ty = getTypeByID(Record[OpNum++]);
4067 Ty = cast<PointerType>(Op->getType())->getElementType();
4068 else if (Ty != cast<PointerType>(Op->getType())->getElementType())
4069 return Error("Explicit load type does not match pointee type of "
4073 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4075 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4077 InstructionList.push_back(I);
4080 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4081 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4084 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4085 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4086 return Error("Invalid record");
4089 if (OpNum + 5 == Record.size())
4090 Ty = getTypeByID(Record[OpNum++]);
4092 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4093 if (Ordering == NotAtomic || Ordering == Release ||
4094 Ordering == AcquireRelease)
4095 return Error("Invalid record");
4096 if (Ordering != NotAtomic && Record[OpNum] == 0)
4097 return Error("Invalid record");
4098 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4101 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4103 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4106 assert((!Ty || Ty == I->getType()) &&
4107 "Explicit type doesn't match pointee type of the first operand");
4109 InstructionList.push_back(I);
4112 case bitc::FUNC_CODE_INST_STORE:
4113 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4116 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4117 (BitCode == bitc::FUNC_CODE_INST_STORE
4118 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4119 : popValue(Record, OpNum, NextValueNo,
4120 cast<PointerType>(Ptr->getType())->getElementType(),
4122 OpNum + 2 != Record.size())
4123 return Error("Invalid record");
4125 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4127 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4128 InstructionList.push_back(I);
4131 case bitc::FUNC_CODE_INST_STOREATOMIC:
4132 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4133 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4136 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4137 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4138 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4139 : popValue(Record, OpNum, NextValueNo,
4140 cast<PointerType>(Ptr->getType())->getElementType(),
4142 OpNum + 4 != Record.size())
4143 return Error("Invalid record");
4145 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4146 if (Ordering == NotAtomic || Ordering == Acquire ||
4147 Ordering == AcquireRelease)
4148 return Error("Invalid record");
4149 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4150 if (Ordering != NotAtomic && Record[OpNum] == 0)
4151 return Error("Invalid record");
4154 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4156 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4157 InstructionList.push_back(I);
4160 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4161 case bitc::FUNC_CODE_INST_CMPXCHG: {
4162 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4163 // failureordering?, isweak?]
4165 Value *Ptr, *Cmp, *New;
4166 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4167 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4168 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4169 : popValue(Record, OpNum, NextValueNo,
4170 cast<PointerType>(Ptr->getType())->getElementType(),
4172 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4173 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4174 return Error("Invalid record");
4175 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4176 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4177 return Error("Invalid record");
4178 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4180 AtomicOrdering FailureOrdering;
4181 if (Record.size() < 7)
4183 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4185 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4187 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4189 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4191 if (Record.size() < 8) {
4192 // Before weak cmpxchgs existed, the instruction simply returned the
4193 // value loaded from memory, so bitcode files from that era will be
4194 // expecting the first component of a modern cmpxchg.
4195 CurBB->getInstList().push_back(I);
4196 I = ExtractValueInst::Create(I, 0);
4198 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4201 InstructionList.push_back(I);
4204 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4205 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4208 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4209 popValue(Record, OpNum, NextValueNo,
4210 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4211 OpNum+4 != Record.size())
4212 return Error("Invalid record");
4213 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4214 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4215 Operation > AtomicRMWInst::LAST_BINOP)
4216 return Error("Invalid record");
4217 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4218 if (Ordering == NotAtomic || Ordering == Unordered)
4219 return Error("Invalid record");
4220 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4221 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4222 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4223 InstructionList.push_back(I);
4226 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4227 if (2 != Record.size())
4228 return Error("Invalid record");
4229 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4230 if (Ordering == NotAtomic || Ordering == Unordered ||
4231 Ordering == Monotonic)
4232 return Error("Invalid record");
4233 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4234 I = new FenceInst(Context, Ordering, SynchScope);
4235 InstructionList.push_back(I);
4238 case bitc::FUNC_CODE_INST_CALL: {
4239 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4240 if (Record.size() < 3)
4241 return Error("Invalid record");
4244 AttributeSet PAL = getAttributes(Record[OpNum++]);
4245 unsigned CCInfo = Record[OpNum++];
4247 FunctionType *FTy = nullptr;
4248 if (CCInfo >> 15 & 1 &&
4249 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4250 return Error("Explicit call type is not a function type");
4253 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4254 return Error("Invalid record");
4256 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4258 return Error("Callee is not a pointer type");
4260 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4262 return Error("Callee is not of pointer to function type");
4263 } else if (OpTy->getElementType() != FTy)
4264 return Error("Explicit call type does not match pointee type of "
4266 if (Record.size() < FTy->getNumParams() + OpNum)
4267 return Error("Insufficient operands to call");
4269 SmallVector<Value*, 16> Args;
4270 // Read the fixed params.
4271 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4272 if (FTy->getParamType(i)->isLabelTy())
4273 Args.push_back(getBasicBlock(Record[OpNum]));
4275 Args.push_back(getValue(Record, OpNum, NextValueNo,
4276 FTy->getParamType(i)));
4278 return Error("Invalid record");
4281 // Read type/value pairs for varargs params.
4282 if (!FTy->isVarArg()) {
4283 if (OpNum != Record.size())
4284 return Error("Invalid record");
4286 while (OpNum != Record.size()) {
4288 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4289 return Error("Invalid record");
4294 I = CallInst::Create(FTy, Callee, Args);
4295 InstructionList.push_back(I);
4296 cast<CallInst>(I)->setCallingConv(
4297 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4298 CallInst::TailCallKind TCK = CallInst::TCK_None;
4300 TCK = CallInst::TCK_Tail;
4301 if (CCInfo & (1 << 14))
4302 TCK = CallInst::TCK_MustTail;
4303 cast<CallInst>(I)->setTailCallKind(TCK);
4304 cast<CallInst>(I)->setAttributes(PAL);
4307 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4308 if (Record.size() < 3)
4309 return Error("Invalid record");
4310 Type *OpTy = getTypeByID(Record[0]);
4311 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4312 Type *ResTy = getTypeByID(Record[2]);
4313 if (!OpTy || !Op || !ResTy)
4314 return Error("Invalid record");
4315 I = new VAArgInst(Op, ResTy);
4316 InstructionList.push_back(I);
4321 // Add instruction to end of current BB. If there is no current BB, reject
4325 return Error("Invalid instruction with no BB");
4327 CurBB->getInstList().push_back(I);
4329 // If this was a terminator instruction, move to the next block.
4330 if (isa<TerminatorInst>(I)) {
4332 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4335 // Non-void values get registered in the value table for future use.
4336 if (I && !I->getType()->isVoidTy())
4337 ValueList.AssignValue(I, NextValueNo++);
4342 // Check the function list for unresolved values.
4343 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4344 if (!A->getParent()) {
4345 // We found at least one unresolved value. Nuke them all to avoid leaks.
4346 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4347 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4348 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4352 return Error("Never resolved value found in function");
4356 // FIXME: Check for unresolved forward-declared metadata references
4357 // and clean up leaks.
4359 // Trim the value list down to the size it was before we parsed this function.
4360 ValueList.shrinkTo(ModuleValueListSize);
4361 MDValueList.shrinkTo(ModuleMDValueListSize);
4362 std::vector<BasicBlock*>().swap(FunctionBBs);
4363 return std::error_code();
4366 /// Find the function body in the bitcode stream
4367 std::error_code BitcodeReader::FindFunctionInStream(
4369 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4370 while (DeferredFunctionInfoIterator->second == 0) {
4371 if (Stream.AtEndOfStream())
4372 return Error("Could not find function in stream");
4373 // ParseModule will parse the next body in the stream and set its
4374 // position in the DeferredFunctionInfo map.
4375 if (std::error_code EC = ParseModule(true))
4378 return std::error_code();
4381 //===----------------------------------------------------------------------===//
4382 // GVMaterializer implementation
4383 //===----------------------------------------------------------------------===//
4385 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4387 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4388 if (std::error_code EC = materializeMetadata())
4391 Function *F = dyn_cast<Function>(GV);
4392 // If it's not a function or is already material, ignore the request.
4393 if (!F || !F->isMaterializable())
4394 return std::error_code();
4396 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4397 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4398 // If its position is recorded as 0, its body is somewhere in the stream
4399 // but we haven't seen it yet.
4400 if (DFII->second == 0 && LazyStreamer)
4401 if (std::error_code EC = FindFunctionInStream(F, DFII))
4404 // Move the bit stream to the saved position of the deferred function body.
4405 Stream.JumpToBit(DFII->second);
4407 if (std::error_code EC = ParseFunctionBody(F))
4409 F->setIsMaterializable(false);
4414 // Upgrade any old intrinsic calls in the function.
4415 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4416 E = UpgradedIntrinsics.end(); I != E; ++I) {
4417 if (I->first != I->second) {
4418 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4420 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4421 UpgradeIntrinsicCall(CI, I->second);
4426 // Bring in any functions that this function forward-referenced via
4428 return materializeForwardReferencedFunctions();
4431 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4432 const Function *F = dyn_cast<Function>(GV);
4433 if (!F || F->isDeclaration())
4436 // Dematerializing F would leave dangling references that wouldn't be
4437 // reconnected on re-materialization.
4438 if (BlockAddressesTaken.count(F))
4441 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4444 void BitcodeReader::Dematerialize(GlobalValue *GV) {
4445 Function *F = dyn_cast<Function>(GV);
4446 // If this function isn't dematerializable, this is a noop.
4447 if (!F || !isDematerializable(F))
4450 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4452 // Just forget the function body, we can remat it later.
4453 F->dropAllReferences();
4454 F->setIsMaterializable(true);
4457 std::error_code BitcodeReader::MaterializeModule(Module *M) {
4458 assert(M == TheModule &&
4459 "Can only Materialize the Module this BitcodeReader is attached to.");
4461 if (std::error_code EC = materializeMetadata())
4464 // Promise to materialize all forward references.
4465 WillMaterializeAllForwardRefs = true;
4467 // Iterate over the module, deserializing any functions that are still on
4469 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4471 if (std::error_code EC = materialize(F))
4474 // At this point, if there are any function bodies, the current bit is
4475 // pointing to the END_BLOCK record after them. Now make sure the rest
4476 // of the bits in the module have been read.
4480 // Check that all block address forward references got resolved (as we
4482 if (!BasicBlockFwdRefs.empty())
4483 return Error("Never resolved function from blockaddress");
4485 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4486 // delete the old functions to clean up. We can't do this unless the entire
4487 // module is materialized because there could always be another function body
4488 // with calls to the old function.
4489 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4490 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4491 if (I->first != I->second) {
4492 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4494 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4495 UpgradeIntrinsicCall(CI, I->second);
4497 if (!I->first->use_empty())
4498 I->first->replaceAllUsesWith(I->second);
4499 I->first->eraseFromParent();
4502 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4504 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4505 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4507 UpgradeDebugInfo(*M);
4508 return std::error_code();
4511 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4512 return IdentifiedStructTypes;
4515 std::error_code BitcodeReader::InitStream() {
4517 return InitLazyStream();
4518 return InitStreamFromBuffer();
4521 std::error_code BitcodeReader::InitStreamFromBuffer() {
4522 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4523 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4525 if (Buffer->getBufferSize() & 3)
4526 return Error("Invalid bitcode signature");
4528 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4529 // The magic number is 0x0B17C0DE stored in little endian.
4530 if (isBitcodeWrapper(BufPtr, BufEnd))
4531 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4532 return Error("Invalid bitcode wrapper header");
4534 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4535 Stream.init(&*StreamFile);
4537 return std::error_code();
4540 std::error_code BitcodeReader::InitLazyStream() {
4541 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4543 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4544 StreamingMemoryObject &Bytes = *OwnedBytes;
4545 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4546 Stream.init(&*StreamFile);
4548 unsigned char buf[16];
4549 if (Bytes.readBytes(buf, 16, 0) != 16)
4550 return Error("Invalid bitcode signature");
4552 if (!isBitcode(buf, buf + 16))
4553 return Error("Invalid bitcode signature");
4555 if (isBitcodeWrapper(buf, buf + 4)) {
4556 const unsigned char *bitcodeStart = buf;
4557 const unsigned char *bitcodeEnd = buf + 16;
4558 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4559 Bytes.dropLeadingBytes(bitcodeStart - buf);
4560 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4562 return std::error_code();
4566 class BitcodeErrorCategoryType : public std::error_category {
4567 const char *name() const LLVM_NOEXCEPT override {
4568 return "llvm.bitcode";
4570 std::string message(int IE) const override {
4571 BitcodeError E = static_cast<BitcodeError>(IE);
4573 case BitcodeError::InvalidBitcodeSignature:
4574 return "Invalid bitcode signature";
4575 case BitcodeError::CorruptedBitcode:
4576 return "Corrupted bitcode";
4578 llvm_unreachable("Unknown error type!");
4583 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4585 const std::error_category &llvm::BitcodeErrorCategory() {
4586 return *ErrorCategory;
4589 //===----------------------------------------------------------------------===//
4590 // External interface
4591 //===----------------------------------------------------------------------===//
4593 /// \brief Get a lazy one-at-time loading module from bitcode.
4595 /// This isn't always used in a lazy context. In particular, it's also used by
4596 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4597 /// in forward-referenced functions from block address references.
4599 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4600 /// materialize everything -- in particular, if this isn't truly lazy.
4601 static ErrorOr<Module *>
4602 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4603 LLVMContext &Context, bool WillMaterializeAll,
4604 DiagnosticHandlerFunction DiagnosticHandler,
4605 bool ShouldLazyLoadMetadata = false) {
4606 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4608 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4609 M->setMaterializer(R);
4611 auto cleanupOnError = [&](std::error_code EC) {
4612 R->releaseBuffer(); // Never take ownership on error.
4613 delete M; // Also deletes R.
4617 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4618 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4619 return cleanupOnError(EC);
4621 if (!WillMaterializeAll)
4622 // Resolve forward references from blockaddresses.
4623 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4624 return cleanupOnError(EC);
4626 Buffer.release(); // The BitcodeReader owns it now.
4631 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4632 LLVMContext &Context,
4633 DiagnosticHandlerFunction DiagnosticHandler,
4634 bool ShouldLazyLoadMetadata) {
4635 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4636 DiagnosticHandler, ShouldLazyLoadMetadata);
4639 ErrorOr<std::unique_ptr<Module>>
4640 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4641 LLVMContext &Context,
4642 DiagnosticHandlerFunction DiagnosticHandler) {
4643 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4644 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4645 M->setMaterializer(R);
4646 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4648 return std::move(M);
4652 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4653 DiagnosticHandlerFunction DiagnosticHandler) {
4654 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4655 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4656 std::move(Buf), Context, true, DiagnosticHandler);
4659 Module *M = ModuleOrErr.get();
4660 // Read in the entire module, and destroy the BitcodeReader.
4661 if (std::error_code EC = M->materializeAllPermanently()) {
4666 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4667 // written. We must defer until the Module has been fully materialized.
4673 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4674 DiagnosticHandlerFunction DiagnosticHandler) {
4675 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4676 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4678 ErrorOr<std::string> Triple = R->parseTriple();
4679 if (Triple.getError())
4681 return Triple.get();