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/FunctionInfo.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/DataStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
42 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
45 class BitcodeReaderValueList {
46 std::vector<WeakVH> ValuePtrs;
48 /// As we resolve forward-referenced constants, we add information about them
49 /// to this vector. This allows us to resolve them in bulk instead of
50 /// resolving each reference at a time. See the code in
51 /// ResolveConstantForwardRefs for more information about this.
53 /// The key of this vector is the placeholder constant, the value is the slot
54 /// number that holds the resolved value.
55 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
56 ResolveConstantsTy ResolveConstants;
59 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
60 ~BitcodeReaderValueList() {
61 assert(ResolveConstants.empty() && "Constants not resolved?");
64 // vector compatibility methods
65 unsigned size() const { return ValuePtrs.size(); }
66 void resize(unsigned N) { ValuePtrs.resize(N); }
67 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
70 assert(ResolveConstants.empty() && "Constants not resolved?");
74 Value *operator[](unsigned i) const {
75 assert(i < ValuePtrs.size());
79 Value *back() const { return ValuePtrs.back(); }
80 void pop_back() { ValuePtrs.pop_back(); }
81 bool empty() const { return ValuePtrs.empty(); }
82 void shrinkTo(unsigned N) {
83 assert(N <= size() && "Invalid shrinkTo request!");
87 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
88 Value *getValueFwdRef(unsigned Idx, Type *Ty);
90 void assignValue(Value *V, unsigned Idx);
92 /// Once all constants are read, this method bulk resolves any forward
94 void resolveConstantForwardRefs();
97 class BitcodeReaderMDValueList {
102 std::vector<TrackingMDRef> MDValuePtrs;
104 LLVMContext &Context;
106 BitcodeReaderMDValueList(LLVMContext &C)
107 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
109 // vector compatibility methods
110 unsigned size() const { return MDValuePtrs.size(); }
111 void resize(unsigned N) { MDValuePtrs.resize(N); }
112 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
113 void clear() { MDValuePtrs.clear(); }
114 Metadata *back() const { return MDValuePtrs.back(); }
115 void pop_back() { MDValuePtrs.pop_back(); }
116 bool empty() const { return MDValuePtrs.empty(); }
118 Metadata *operator[](unsigned i) const {
119 assert(i < MDValuePtrs.size());
120 return MDValuePtrs[i];
123 void shrinkTo(unsigned N) {
124 assert(N <= size() && "Invalid shrinkTo request!");
125 MDValuePtrs.resize(N);
128 Metadata *getValueFwdRef(unsigned Idx);
129 void assignValue(Metadata *MD, unsigned Idx);
130 void tryToResolveCycles();
133 class BitcodeReader : public GVMaterializer {
134 LLVMContext &Context;
135 Module *TheModule = nullptr;
136 std::unique_ptr<MemoryBuffer> Buffer;
137 std::unique_ptr<BitstreamReader> StreamFile;
138 BitstreamCursor Stream;
139 // Next offset to start scanning for lazy parsing of function bodies.
140 uint64_t NextUnreadBit = 0;
141 // Last function offset found in the VST.
142 uint64_t LastFunctionBlockBit = 0;
143 bool SeenValueSymbolTable = false;
144 uint64_t VSTOffset = 0;
145 // Contains an arbitrary and optional string identifying the bitcode producer
146 std::string ProducerIdentification;
147 // Number of module level metadata records specified by the
148 // MODULE_CODE_METADATA_VALUES record.
149 unsigned NumModuleMDs = 0;
150 // Support older bitcode without the MODULE_CODE_METADATA_VALUES record.
151 bool SeenModuleValuesRecord = false;
153 std::vector<Type*> TypeList;
154 BitcodeReaderValueList ValueList;
155 BitcodeReaderMDValueList MDValueList;
156 std::vector<Comdat *> ComdatList;
157 SmallVector<Instruction *, 64> InstructionList;
159 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
160 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
161 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
162 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
163 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
165 SmallVector<Instruction*, 64> InstsWithTBAATag;
167 /// The set of attributes by index. Index zero in the file is for null, and
168 /// is thus not represented here. As such all indices are off by one.
169 std::vector<AttributeSet> MAttributes;
171 /// The set of attribute groups.
172 std::map<unsigned, AttributeSet> MAttributeGroups;
174 /// While parsing a function body, this is a list of the basic blocks for the
176 std::vector<BasicBlock*> FunctionBBs;
178 // When reading the module header, this list is populated with functions that
179 // have bodies later in the file.
180 std::vector<Function*> FunctionsWithBodies;
182 // When intrinsic functions are encountered which require upgrading they are
183 // stored here with their replacement function.
184 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
185 UpgradedIntrinsicMap UpgradedIntrinsics;
187 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
188 DenseMap<unsigned, unsigned> MDKindMap;
190 // Several operations happen after the module header has been read, but
191 // before function bodies are processed. This keeps track of whether
192 // we've done this yet.
193 bool SeenFirstFunctionBody = false;
195 /// When function bodies are initially scanned, this map contains info about
196 /// where to find deferred function body in the stream.
197 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
199 /// When Metadata block is initially scanned when parsing the module, we may
200 /// choose to defer parsing of the metadata. This vector contains info about
201 /// which Metadata blocks are deferred.
202 std::vector<uint64_t> DeferredMetadataInfo;
204 /// These are basic blocks forward-referenced by block addresses. They are
205 /// inserted lazily into functions when they're loaded. The basic block ID is
206 /// its index into the vector.
207 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
208 std::deque<Function *> BasicBlockFwdRefQueue;
210 /// Indicates that we are using a new encoding for instruction operands where
211 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
212 /// instruction number, for a more compact encoding. Some instruction
213 /// operands are not relative to the instruction ID: basic block numbers, and
214 /// types. Once the old style function blocks have been phased out, we would
215 /// not need this flag.
216 bool UseRelativeIDs = false;
218 /// True if all functions will be materialized, negating the need to process
219 /// (e.g.) blockaddress forward references.
220 bool WillMaterializeAllForwardRefs = false;
222 /// Functions that have block addresses taken. This is usually empty.
223 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
225 /// True if any Metadata block has been materialized.
226 bool IsMetadataMaterialized = false;
228 bool StripDebugInfo = false;
230 /// Functions that need to be matched with subprograms when upgrading old
232 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
234 std::vector<std::string> BundleTags;
237 std::error_code error(BitcodeError E, const Twine &Message);
238 std::error_code error(BitcodeError E);
239 std::error_code error(const Twine &Message);
241 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
242 BitcodeReader(LLVMContext &Context);
243 ~BitcodeReader() override { freeState(); }
245 std::error_code materializeForwardReferencedFunctions();
249 void releaseBuffer();
251 bool isDematerializable(const GlobalValue *GV) const override;
252 std::error_code materialize(GlobalValue *GV) override;
253 std::error_code materializeModule(Module *M) override;
254 std::vector<StructType *> getIdentifiedStructTypes() const override;
255 void dematerialize(GlobalValue *GV) override;
257 /// \brief Main interface to parsing a bitcode buffer.
258 /// \returns true if an error occurred.
259 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
261 bool ShouldLazyLoadMetadata = false);
263 /// \brief Cheap mechanism to just extract module triple
264 /// \returns true if an error occurred.
265 ErrorOr<std::string> parseTriple();
267 /// Cheap mechanism to just extract the identification block out of bitcode.
268 ErrorOr<std::string> parseIdentificationBlock();
270 static uint64_t decodeSignRotatedValue(uint64_t V);
272 /// Materialize any deferred Metadata block.
273 std::error_code materializeMetadata() override;
275 void setStripDebugInfo() override;
278 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
279 // ProducerIdentification data member, and do some basic enforcement on the
280 // "epoch" encoded in the bitcode.
281 std::error_code parseBitcodeVersion();
283 std::vector<StructType *> IdentifiedStructTypes;
284 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
285 StructType *createIdentifiedStructType(LLVMContext &Context);
287 Type *getTypeByID(unsigned ID);
288 Value *getFnValueByID(unsigned ID, Type *Ty) {
289 if (Ty && Ty->isMetadataTy())
290 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
291 return ValueList.getValueFwdRef(ID, Ty);
293 Metadata *getFnMetadataByID(unsigned ID) {
294 return MDValueList.getValueFwdRef(ID);
296 BasicBlock *getBasicBlock(unsigned ID) const {
297 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
298 return FunctionBBs[ID];
300 AttributeSet getAttributes(unsigned i) const {
301 if (i-1 < MAttributes.size())
302 return MAttributes[i-1];
303 return AttributeSet();
306 /// Read a value/type pair out of the specified record from slot 'Slot'.
307 /// Increment Slot past the number of slots used in the record. Return true on
309 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
310 unsigned InstNum, Value *&ResVal) {
311 if (Slot == Record.size()) return true;
312 unsigned ValNo = (unsigned)Record[Slot++];
313 // Adjust the ValNo, if it was encoded relative to the InstNum.
315 ValNo = InstNum - ValNo;
316 if (ValNo < InstNum) {
317 // If this is not a forward reference, just return the value we already
319 ResVal = getFnValueByID(ValNo, nullptr);
320 return ResVal == nullptr;
322 if (Slot == Record.size())
325 unsigned TypeNo = (unsigned)Record[Slot++];
326 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
327 return ResVal == nullptr;
330 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
331 /// past the number of slots used by the value in the record. Return true if
332 /// there is an error.
333 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
334 unsigned InstNum, Type *Ty, Value *&ResVal) {
335 if (getValue(Record, Slot, InstNum, Ty, ResVal))
337 // All values currently take a single record slot.
342 /// Like popValue, but does not increment the Slot number.
343 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
344 unsigned InstNum, Type *Ty, Value *&ResVal) {
345 ResVal = getValue(Record, Slot, InstNum, Ty);
346 return ResVal == nullptr;
349 /// Version of getValue that returns ResVal directly, or 0 if there is an
351 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
352 unsigned InstNum, Type *Ty) {
353 if (Slot == Record.size()) return nullptr;
354 unsigned ValNo = (unsigned)Record[Slot];
355 // Adjust the ValNo, if it was encoded relative to the InstNum.
357 ValNo = InstNum - ValNo;
358 return getFnValueByID(ValNo, Ty);
361 /// Like getValue, but decodes signed VBRs.
362 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
363 unsigned InstNum, Type *Ty) {
364 if (Slot == Record.size()) return nullptr;
365 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
366 // Adjust the ValNo, if it was encoded relative to the InstNum.
368 ValNo = InstNum - ValNo;
369 return getFnValueByID(ValNo, Ty);
372 /// Converts alignment exponent (i.e. power of two (or zero)) to the
373 /// corresponding alignment to use. If alignment is too large, returns
374 /// a corresponding error code.
375 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
376 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
377 std::error_code parseModule(uint64_t ResumeBit,
378 bool ShouldLazyLoadMetadata = false);
379 std::error_code parseAttributeBlock();
380 std::error_code parseAttributeGroupBlock();
381 std::error_code parseTypeTable();
382 std::error_code parseTypeTableBody();
383 std::error_code parseOperandBundleTags();
385 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
386 unsigned NameIndex, Triple &TT);
387 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
388 std::error_code parseConstants();
389 std::error_code rememberAndSkipFunctionBodies();
390 std::error_code rememberAndSkipFunctionBody();
391 /// Save the positions of the Metadata blocks and skip parsing the blocks.
392 std::error_code rememberAndSkipMetadata();
393 std::error_code parseFunctionBody(Function *F);
394 std::error_code globalCleanup();
395 std::error_code resolveGlobalAndAliasInits();
396 std::error_code parseMetadata(bool ModuleLevel = false);
397 std::error_code parseMetadataKinds();
398 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
399 std::error_code parseMetadataAttachment(Function &F);
400 ErrorOr<std::string> parseModuleTriple();
401 std::error_code parseUseLists();
402 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
403 std::error_code initStreamFromBuffer();
404 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
405 std::error_code findFunctionInStream(
407 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
410 /// Class to manage reading and parsing function summary index bitcode
412 class FunctionIndexBitcodeReader {
413 DiagnosticHandlerFunction DiagnosticHandler;
415 /// Eventually points to the function index built during parsing.
416 FunctionInfoIndex *TheIndex = nullptr;
418 std::unique_ptr<MemoryBuffer> Buffer;
419 std::unique_ptr<BitstreamReader> StreamFile;
420 BitstreamCursor Stream;
422 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
424 /// If false, the summary section is fully parsed into the index during
425 /// the initial parse. Otherwise, if true, the caller is expected to
426 /// invoke \a readFunctionSummary for each summary needed, and the summary
427 /// section is thus parsed lazily.
430 /// Used to indicate whether caller only wants to check for the presence
431 /// of the function summary bitcode section. All blocks are skipped,
432 /// but the SeenFuncSummary boolean is set.
433 bool CheckFuncSummaryPresenceOnly = false;
435 /// Indicates whether we have encountered a function summary section
436 /// yet during parsing, used when checking if file contains function
438 bool SeenFuncSummary = false;
440 /// \brief Map populated during function summary section parsing, and
441 /// consumed during ValueSymbolTable parsing.
443 /// Used to correlate summary records with VST entries. For the per-module
444 /// index this maps the ValueID to the parsed function summary, and
445 /// for the combined index this maps the summary record's bitcode
446 /// offset to the function summary (since in the combined index the
447 /// VST records do not hold value IDs but rather hold the function
448 /// summary record offset).
449 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
451 /// Map populated during module path string table parsing, from the
452 /// module ID to a string reference owned by the index's module
453 /// path string table, used to correlate with combined index function
455 DenseMap<uint64_t, StringRef> ModuleIdMap;
458 std::error_code error(BitcodeError E, const Twine &Message);
459 std::error_code error(BitcodeError E);
460 std::error_code error(const Twine &Message);
462 FunctionIndexBitcodeReader(MemoryBuffer *Buffer,
463 DiagnosticHandlerFunction DiagnosticHandler,
465 bool CheckFuncSummaryPresenceOnly = false);
466 FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler,
468 bool CheckFuncSummaryPresenceOnly = false);
469 ~FunctionIndexBitcodeReader() { freeState(); }
473 void releaseBuffer();
475 /// Check if the parser has encountered a function summary section.
476 bool foundFuncSummary() { return SeenFuncSummary; }
478 /// \brief Main interface to parsing a bitcode buffer.
479 /// \returns true if an error occurred.
480 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
481 FunctionInfoIndex *I);
483 /// \brief Interface for parsing a function summary lazily.
484 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
485 FunctionInfoIndex *I,
486 size_t FunctionSummaryOffset);
489 std::error_code parseModule();
490 std::error_code parseValueSymbolTable();
491 std::error_code parseEntireSummary();
492 std::error_code parseModuleStringTable();
493 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
494 std::error_code initStreamFromBuffer();
495 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
499 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
500 DiagnosticSeverity Severity,
502 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
504 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
506 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
507 std::error_code EC, const Twine &Message) {
508 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
509 DiagnosticHandler(DI);
513 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
514 std::error_code EC) {
515 return error(DiagnosticHandler, EC, EC.message());
518 static std::error_code error(LLVMContext &Context, std::error_code EC,
519 const Twine &Message) {
520 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
524 static std::error_code error(LLVMContext &Context, std::error_code EC) {
525 return error(Context, EC, EC.message());
528 static std::error_code error(LLVMContext &Context, const Twine &Message) {
529 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
533 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
534 if (!ProducerIdentification.empty()) {
535 return ::error(Context, make_error_code(E),
536 Message + " (Producer: '" + ProducerIdentification +
537 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
539 return ::error(Context, make_error_code(E), Message);
542 std::error_code BitcodeReader::error(const Twine &Message) {
543 if (!ProducerIdentification.empty()) {
544 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
545 Message + " (Producer: '" + ProducerIdentification +
546 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
548 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
552 std::error_code BitcodeReader::error(BitcodeError E) {
553 return ::error(Context, make_error_code(E));
556 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
557 : Context(Context), Buffer(Buffer), ValueList(Context),
558 MDValueList(Context) {}
560 BitcodeReader::BitcodeReader(LLVMContext &Context)
561 : Context(Context), Buffer(nullptr), ValueList(Context),
562 MDValueList(Context) {}
564 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
565 if (WillMaterializeAllForwardRefs)
566 return std::error_code();
568 // Prevent recursion.
569 WillMaterializeAllForwardRefs = true;
571 while (!BasicBlockFwdRefQueue.empty()) {
572 Function *F = BasicBlockFwdRefQueue.front();
573 BasicBlockFwdRefQueue.pop_front();
574 assert(F && "Expected valid function");
575 if (!BasicBlockFwdRefs.count(F))
576 // Already materialized.
579 // Check for a function that isn't materializable to prevent an infinite
580 // loop. When parsing a blockaddress stored in a global variable, there
581 // isn't a trivial way to check if a function will have a body without a
582 // linear search through FunctionsWithBodies, so just check it here.
583 if (!F->isMaterializable())
584 return error("Never resolved function from blockaddress");
586 // Try to materialize F.
587 if (std::error_code EC = materialize(F))
590 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
593 WillMaterializeAllForwardRefs = false;
594 return std::error_code();
597 void BitcodeReader::freeState() {
599 std::vector<Type*>().swap(TypeList);
602 std::vector<Comdat *>().swap(ComdatList);
604 std::vector<AttributeSet>().swap(MAttributes);
605 std::vector<BasicBlock*>().swap(FunctionBBs);
606 std::vector<Function*>().swap(FunctionsWithBodies);
607 DeferredFunctionInfo.clear();
608 DeferredMetadataInfo.clear();
611 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
612 BasicBlockFwdRefQueue.clear();
615 //===----------------------------------------------------------------------===//
616 // Helper functions to implement forward reference resolution, etc.
617 //===----------------------------------------------------------------------===//
619 /// Convert a string from a record into an std::string, return true on failure.
620 template <typename StrTy>
621 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
623 if (Idx > Record.size())
626 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
627 Result += (char)Record[i];
631 static bool hasImplicitComdat(size_t Val) {
635 case 1: // Old WeakAnyLinkage
636 case 4: // Old LinkOnceAnyLinkage
637 case 10: // Old WeakODRLinkage
638 case 11: // Old LinkOnceODRLinkage
643 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
645 default: // Map unknown/new linkages to external
647 return GlobalValue::ExternalLinkage;
649 return GlobalValue::AppendingLinkage;
651 return GlobalValue::InternalLinkage;
653 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
655 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
657 return GlobalValue::ExternalWeakLinkage;
659 return GlobalValue::CommonLinkage;
661 return GlobalValue::PrivateLinkage;
663 return GlobalValue::AvailableExternallyLinkage;
665 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
667 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
669 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
670 case 1: // Old value with implicit comdat.
672 return GlobalValue::WeakAnyLinkage;
673 case 10: // Old value with implicit comdat.
675 return GlobalValue::WeakODRLinkage;
676 case 4: // Old value with implicit comdat.
678 return GlobalValue::LinkOnceAnyLinkage;
679 case 11: // Old value with implicit comdat.
681 return GlobalValue::LinkOnceODRLinkage;
685 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
687 default: // Map unknown visibilities to default.
688 case 0: return GlobalValue::DefaultVisibility;
689 case 1: return GlobalValue::HiddenVisibility;
690 case 2: return GlobalValue::ProtectedVisibility;
694 static GlobalValue::DLLStorageClassTypes
695 getDecodedDLLStorageClass(unsigned Val) {
697 default: // Map unknown values to default.
698 case 0: return GlobalValue::DefaultStorageClass;
699 case 1: return GlobalValue::DLLImportStorageClass;
700 case 2: return GlobalValue::DLLExportStorageClass;
704 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
706 case 0: return GlobalVariable::NotThreadLocal;
707 default: // Map unknown non-zero value to general dynamic.
708 case 1: return GlobalVariable::GeneralDynamicTLSModel;
709 case 2: return GlobalVariable::LocalDynamicTLSModel;
710 case 3: return GlobalVariable::InitialExecTLSModel;
711 case 4: return GlobalVariable::LocalExecTLSModel;
715 static int getDecodedCastOpcode(unsigned Val) {
718 case bitc::CAST_TRUNC : return Instruction::Trunc;
719 case bitc::CAST_ZEXT : return Instruction::ZExt;
720 case bitc::CAST_SEXT : return Instruction::SExt;
721 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
722 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
723 case bitc::CAST_UITOFP : return Instruction::UIToFP;
724 case bitc::CAST_SITOFP : return Instruction::SIToFP;
725 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
726 case bitc::CAST_FPEXT : return Instruction::FPExt;
727 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
728 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
729 case bitc::CAST_BITCAST : return Instruction::BitCast;
730 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
734 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
735 bool IsFP = Ty->isFPOrFPVectorTy();
736 // BinOps are only valid for int/fp or vector of int/fp types
737 if (!IsFP && !Ty->isIntOrIntVectorTy())
743 case bitc::BINOP_ADD:
744 return IsFP ? Instruction::FAdd : Instruction::Add;
745 case bitc::BINOP_SUB:
746 return IsFP ? Instruction::FSub : Instruction::Sub;
747 case bitc::BINOP_MUL:
748 return IsFP ? Instruction::FMul : Instruction::Mul;
749 case bitc::BINOP_UDIV:
750 return IsFP ? -1 : Instruction::UDiv;
751 case bitc::BINOP_SDIV:
752 return IsFP ? Instruction::FDiv : Instruction::SDiv;
753 case bitc::BINOP_UREM:
754 return IsFP ? -1 : Instruction::URem;
755 case bitc::BINOP_SREM:
756 return IsFP ? Instruction::FRem : Instruction::SRem;
757 case bitc::BINOP_SHL:
758 return IsFP ? -1 : Instruction::Shl;
759 case bitc::BINOP_LSHR:
760 return IsFP ? -1 : Instruction::LShr;
761 case bitc::BINOP_ASHR:
762 return IsFP ? -1 : Instruction::AShr;
763 case bitc::BINOP_AND:
764 return IsFP ? -1 : Instruction::And;
766 return IsFP ? -1 : Instruction::Or;
767 case bitc::BINOP_XOR:
768 return IsFP ? -1 : Instruction::Xor;
772 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
774 default: return AtomicRMWInst::BAD_BINOP;
775 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
776 case bitc::RMW_ADD: return AtomicRMWInst::Add;
777 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
778 case bitc::RMW_AND: return AtomicRMWInst::And;
779 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
780 case bitc::RMW_OR: return AtomicRMWInst::Or;
781 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
782 case bitc::RMW_MAX: return AtomicRMWInst::Max;
783 case bitc::RMW_MIN: return AtomicRMWInst::Min;
784 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
785 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
789 static AtomicOrdering getDecodedOrdering(unsigned Val) {
791 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
792 case bitc::ORDERING_UNORDERED: return Unordered;
793 case bitc::ORDERING_MONOTONIC: return Monotonic;
794 case bitc::ORDERING_ACQUIRE: return Acquire;
795 case bitc::ORDERING_RELEASE: return Release;
796 case bitc::ORDERING_ACQREL: return AcquireRelease;
797 default: // Map unknown orderings to sequentially-consistent.
798 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
802 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
804 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
805 default: // Map unknown scopes to cross-thread.
806 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
810 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
812 default: // Map unknown selection kinds to any.
813 case bitc::COMDAT_SELECTION_KIND_ANY:
815 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
816 return Comdat::ExactMatch;
817 case bitc::COMDAT_SELECTION_KIND_LARGEST:
818 return Comdat::Largest;
819 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
820 return Comdat::NoDuplicates;
821 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
822 return Comdat::SameSize;
826 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
828 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
829 FMF.setUnsafeAlgebra();
830 if (0 != (Val & FastMathFlags::NoNaNs))
832 if (0 != (Val & FastMathFlags::NoInfs))
834 if (0 != (Val & FastMathFlags::NoSignedZeros))
835 FMF.setNoSignedZeros();
836 if (0 != (Val & FastMathFlags::AllowReciprocal))
837 FMF.setAllowReciprocal();
841 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
843 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
844 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
850 /// \brief A class for maintaining the slot number definition
851 /// as a placeholder for the actual definition for forward constants defs.
852 class ConstantPlaceHolder : public ConstantExpr {
853 void operator=(const ConstantPlaceHolder &) = delete;
856 // allocate space for exactly one operand
857 void *operator new(size_t s) { return User::operator new(s, 1); }
858 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
859 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
860 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
863 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
864 static bool classof(const Value *V) {
865 return isa<ConstantExpr>(V) &&
866 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
869 /// Provide fast operand accessors
870 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
874 // FIXME: can we inherit this from ConstantExpr?
876 struct OperandTraits<ConstantPlaceHolder> :
877 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
879 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
882 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
891 WeakVH &OldV = ValuePtrs[Idx];
897 // Handle constants and non-constants (e.g. instrs) differently for
899 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
900 ResolveConstants.push_back(std::make_pair(PHC, Idx));
903 // If there was a forward reference to this value, replace it.
904 Value *PrevVal = OldV;
905 OldV->replaceAllUsesWith(V);
913 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
918 if (Value *V = ValuePtrs[Idx]) {
919 if (Ty != V->getType())
920 report_fatal_error("Type mismatch in constant table!");
921 return cast<Constant>(V);
924 // Create and return a placeholder, which will later be RAUW'd.
925 Constant *C = new ConstantPlaceHolder(Ty, Context);
930 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
931 // Bail out for a clearly invalid value. This would make us call resize(0)
938 if (Value *V = ValuePtrs[Idx]) {
939 // If the types don't match, it's invalid.
940 if (Ty && Ty != V->getType())
945 // No type specified, must be invalid reference.
946 if (!Ty) return nullptr;
948 // Create and return a placeholder, which will later be RAUW'd.
949 Value *V = new Argument(Ty);
954 /// Once all constants are read, this method bulk resolves any forward
955 /// references. The idea behind this is that we sometimes get constants (such
956 /// as large arrays) which reference *many* forward ref constants. Replacing
957 /// each of these causes a lot of thrashing when building/reuniquing the
958 /// constant. Instead of doing this, we look at all the uses and rewrite all
959 /// the place holders at once for any constant that uses a placeholder.
960 void BitcodeReaderValueList::resolveConstantForwardRefs() {
961 // Sort the values by-pointer so that they are efficient to look up with a
963 std::sort(ResolveConstants.begin(), ResolveConstants.end());
965 SmallVector<Constant*, 64> NewOps;
967 while (!ResolveConstants.empty()) {
968 Value *RealVal = operator[](ResolveConstants.back().second);
969 Constant *Placeholder = ResolveConstants.back().first;
970 ResolveConstants.pop_back();
972 // Loop over all users of the placeholder, updating them to reference the
973 // new value. If they reference more than one placeholder, update them all
975 while (!Placeholder->use_empty()) {
976 auto UI = Placeholder->user_begin();
979 // If the using object isn't uniqued, just update the operands. This
980 // handles instructions and initializers for global variables.
981 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
982 UI.getUse().set(RealVal);
986 // Otherwise, we have a constant that uses the placeholder. Replace that
987 // constant with a new constant that has *all* placeholder uses updated.
988 Constant *UserC = cast<Constant>(U);
989 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
992 if (!isa<ConstantPlaceHolder>(*I)) {
993 // Not a placeholder reference.
995 } else if (*I == Placeholder) {
996 // Common case is that it just references this one placeholder.
999 // Otherwise, look up the placeholder in ResolveConstants.
1000 ResolveConstantsTy::iterator It =
1001 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1002 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1004 assert(It != ResolveConstants.end() && It->first == *I);
1005 NewOp = operator[](It->second);
1008 NewOps.push_back(cast<Constant>(NewOp));
1011 // Make the new constant.
1013 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1014 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1015 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1016 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1017 } else if (isa<ConstantVector>(UserC)) {
1018 NewC = ConstantVector::get(NewOps);
1020 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1021 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1024 UserC->replaceAllUsesWith(NewC);
1025 UserC->destroyConstant();
1029 // Update all ValueHandles, they should be the only users at this point.
1030 Placeholder->replaceAllUsesWith(RealVal);
1035 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1036 if (Idx == size()) {
1044 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1050 // If there was a forward reference to this value, replace it.
1051 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1052 PrevMD->replaceAllUsesWith(MD);
1056 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1060 if (Metadata *MD = MDValuePtrs[Idx])
1063 // Track forward refs to be resolved later.
1065 MinFwdRef = std::min(MinFwdRef, Idx);
1066 MaxFwdRef = std::max(MaxFwdRef, Idx);
1069 MinFwdRef = MaxFwdRef = Idx;
1073 // Create and return a placeholder, which will later be RAUW'd.
1074 Metadata *MD = MDNode::getTemporary(Context, None).release();
1075 MDValuePtrs[Idx].reset(MD);
1079 void BitcodeReaderMDValueList::tryToResolveCycles() {
1085 // Still forward references... can't resolve cycles.
1088 // Resolve any cycles.
1089 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1090 auto &MD = MDValuePtrs[I];
1091 auto *N = dyn_cast_or_null<MDNode>(MD);
1095 assert(!N->isTemporary() && "Unexpected forward reference");
1099 // Make sure we return early again until there's another forward ref.
1103 Type *BitcodeReader::getTypeByID(unsigned ID) {
1104 // The type table size is always specified correctly.
1105 if (ID >= TypeList.size())
1108 if (Type *Ty = TypeList[ID])
1111 // If we have a forward reference, the only possible case is when it is to a
1112 // named struct. Just create a placeholder for now.
1113 return TypeList[ID] = createIdentifiedStructType(Context);
1116 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1118 auto *Ret = StructType::create(Context, Name);
1119 IdentifiedStructTypes.push_back(Ret);
1123 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1124 auto *Ret = StructType::create(Context);
1125 IdentifiedStructTypes.push_back(Ret);
1130 //===----------------------------------------------------------------------===//
1131 // Functions for parsing blocks from the bitcode file
1132 //===----------------------------------------------------------------------===//
1135 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1136 /// been decoded from the given integer. This function must stay in sync with
1137 /// 'encodeLLVMAttributesForBitcode'.
1138 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1139 uint64_t EncodedAttrs) {
1140 // FIXME: Remove in 4.0.
1142 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1143 // the bits above 31 down by 11 bits.
1144 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1145 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1146 "Alignment must be a power of two.");
1149 B.addAlignmentAttr(Alignment);
1150 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1151 (EncodedAttrs & 0xffff));
1154 std::error_code BitcodeReader::parseAttributeBlock() {
1155 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1156 return error("Invalid record");
1158 if (!MAttributes.empty())
1159 return error("Invalid multiple blocks");
1161 SmallVector<uint64_t, 64> Record;
1163 SmallVector<AttributeSet, 8> Attrs;
1165 // Read all the records.
1167 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1169 switch (Entry.Kind) {
1170 case BitstreamEntry::SubBlock: // Handled for us already.
1171 case BitstreamEntry::Error:
1172 return error("Malformed block");
1173 case BitstreamEntry::EndBlock:
1174 return std::error_code();
1175 case BitstreamEntry::Record:
1176 // The interesting case.
1182 switch (Stream.readRecord(Entry.ID, Record)) {
1183 default: // Default behavior: ignore.
1185 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1186 // FIXME: Remove in 4.0.
1187 if (Record.size() & 1)
1188 return error("Invalid record");
1190 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1192 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1193 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1196 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1200 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1201 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1202 Attrs.push_back(MAttributeGroups[Record[i]]);
1204 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1212 // Returns Attribute::None on unrecognized codes.
1213 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1216 return Attribute::None;
1217 case bitc::ATTR_KIND_ALIGNMENT:
1218 return Attribute::Alignment;
1219 case bitc::ATTR_KIND_ALWAYS_INLINE:
1220 return Attribute::AlwaysInline;
1221 case bitc::ATTR_KIND_ARGMEMONLY:
1222 return Attribute::ArgMemOnly;
1223 case bitc::ATTR_KIND_BUILTIN:
1224 return Attribute::Builtin;
1225 case bitc::ATTR_KIND_BY_VAL:
1226 return Attribute::ByVal;
1227 case bitc::ATTR_KIND_IN_ALLOCA:
1228 return Attribute::InAlloca;
1229 case bitc::ATTR_KIND_COLD:
1230 return Attribute::Cold;
1231 case bitc::ATTR_KIND_CONVERGENT:
1232 return Attribute::Convergent;
1233 case bitc::ATTR_KIND_INLINE_HINT:
1234 return Attribute::InlineHint;
1235 case bitc::ATTR_KIND_IN_REG:
1236 return Attribute::InReg;
1237 case bitc::ATTR_KIND_JUMP_TABLE:
1238 return Attribute::JumpTable;
1239 case bitc::ATTR_KIND_MIN_SIZE:
1240 return Attribute::MinSize;
1241 case bitc::ATTR_KIND_NAKED:
1242 return Attribute::Naked;
1243 case bitc::ATTR_KIND_NEST:
1244 return Attribute::Nest;
1245 case bitc::ATTR_KIND_NO_ALIAS:
1246 return Attribute::NoAlias;
1247 case bitc::ATTR_KIND_NO_BUILTIN:
1248 return Attribute::NoBuiltin;
1249 case bitc::ATTR_KIND_NO_CAPTURE:
1250 return Attribute::NoCapture;
1251 case bitc::ATTR_KIND_NO_DUPLICATE:
1252 return Attribute::NoDuplicate;
1253 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1254 return Attribute::NoImplicitFloat;
1255 case bitc::ATTR_KIND_NO_INLINE:
1256 return Attribute::NoInline;
1257 case bitc::ATTR_KIND_NO_RECURSE:
1258 return Attribute::NoRecurse;
1259 case bitc::ATTR_KIND_NON_LAZY_BIND:
1260 return Attribute::NonLazyBind;
1261 case bitc::ATTR_KIND_NON_NULL:
1262 return Attribute::NonNull;
1263 case bitc::ATTR_KIND_DEREFERENCEABLE:
1264 return Attribute::Dereferenceable;
1265 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1266 return Attribute::DereferenceableOrNull;
1267 case bitc::ATTR_KIND_NO_RED_ZONE:
1268 return Attribute::NoRedZone;
1269 case bitc::ATTR_KIND_NO_RETURN:
1270 return Attribute::NoReturn;
1271 case bitc::ATTR_KIND_NO_UNWIND:
1272 return Attribute::NoUnwind;
1273 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1274 return Attribute::OptimizeForSize;
1275 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1276 return Attribute::OptimizeNone;
1277 case bitc::ATTR_KIND_READ_NONE:
1278 return Attribute::ReadNone;
1279 case bitc::ATTR_KIND_READ_ONLY:
1280 return Attribute::ReadOnly;
1281 case bitc::ATTR_KIND_RETURNED:
1282 return Attribute::Returned;
1283 case bitc::ATTR_KIND_RETURNS_TWICE:
1284 return Attribute::ReturnsTwice;
1285 case bitc::ATTR_KIND_S_EXT:
1286 return Attribute::SExt;
1287 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1288 return Attribute::StackAlignment;
1289 case bitc::ATTR_KIND_STACK_PROTECT:
1290 return Attribute::StackProtect;
1291 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1292 return Attribute::StackProtectReq;
1293 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1294 return Attribute::StackProtectStrong;
1295 case bitc::ATTR_KIND_SAFESTACK:
1296 return Attribute::SafeStack;
1297 case bitc::ATTR_KIND_STRUCT_RET:
1298 return Attribute::StructRet;
1299 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1300 return Attribute::SanitizeAddress;
1301 case bitc::ATTR_KIND_SANITIZE_THREAD:
1302 return Attribute::SanitizeThread;
1303 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1304 return Attribute::SanitizeMemory;
1305 case bitc::ATTR_KIND_UW_TABLE:
1306 return Attribute::UWTable;
1307 case bitc::ATTR_KIND_Z_EXT:
1308 return Attribute::ZExt;
1312 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1313 unsigned &Alignment) {
1314 // Note: Alignment in bitcode files is incremented by 1, so that zero
1315 // can be used for default alignment.
1316 if (Exponent > Value::MaxAlignmentExponent + 1)
1317 return error("Invalid alignment value");
1318 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1319 return std::error_code();
1322 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1323 Attribute::AttrKind *Kind) {
1324 *Kind = getAttrFromCode(Code);
1325 if (*Kind == Attribute::None)
1326 return error(BitcodeError::CorruptedBitcode,
1327 "Unknown attribute kind (" + Twine(Code) + ")");
1328 return std::error_code();
1331 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1332 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1333 return error("Invalid record");
1335 if (!MAttributeGroups.empty())
1336 return error("Invalid multiple blocks");
1338 SmallVector<uint64_t, 64> Record;
1340 // Read all the records.
1342 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1344 switch (Entry.Kind) {
1345 case BitstreamEntry::SubBlock: // Handled for us already.
1346 case BitstreamEntry::Error:
1347 return error("Malformed block");
1348 case BitstreamEntry::EndBlock:
1349 return std::error_code();
1350 case BitstreamEntry::Record:
1351 // The interesting case.
1357 switch (Stream.readRecord(Entry.ID, Record)) {
1358 default: // Default behavior: ignore.
1360 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1361 if (Record.size() < 3)
1362 return error("Invalid record");
1364 uint64_t GrpID = Record[0];
1365 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1368 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1369 if (Record[i] == 0) { // Enum attribute
1370 Attribute::AttrKind Kind;
1371 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1374 B.addAttribute(Kind);
1375 } else if (Record[i] == 1) { // Integer attribute
1376 Attribute::AttrKind Kind;
1377 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1379 if (Kind == Attribute::Alignment)
1380 B.addAlignmentAttr(Record[++i]);
1381 else if (Kind == Attribute::StackAlignment)
1382 B.addStackAlignmentAttr(Record[++i]);
1383 else if (Kind == Attribute::Dereferenceable)
1384 B.addDereferenceableAttr(Record[++i]);
1385 else if (Kind == Attribute::DereferenceableOrNull)
1386 B.addDereferenceableOrNullAttr(Record[++i]);
1387 } else { // String attribute
1388 assert((Record[i] == 3 || Record[i] == 4) &&
1389 "Invalid attribute group entry");
1390 bool HasValue = (Record[i++] == 4);
1391 SmallString<64> KindStr;
1392 SmallString<64> ValStr;
1394 while (Record[i] != 0 && i != e)
1395 KindStr += Record[i++];
1396 assert(Record[i] == 0 && "Kind string not null terminated");
1399 // Has a value associated with it.
1400 ++i; // Skip the '0' that terminates the "kind" string.
1401 while (Record[i] != 0 && i != e)
1402 ValStr += Record[i++];
1403 assert(Record[i] == 0 && "Value string not null terminated");
1406 B.addAttribute(KindStr.str(), ValStr.str());
1410 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1417 std::error_code BitcodeReader::parseTypeTable() {
1418 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1419 return error("Invalid record");
1421 return parseTypeTableBody();
1424 std::error_code BitcodeReader::parseTypeTableBody() {
1425 if (!TypeList.empty())
1426 return error("Invalid multiple blocks");
1428 SmallVector<uint64_t, 64> Record;
1429 unsigned NumRecords = 0;
1431 SmallString<64> TypeName;
1433 // Read all the records for this type table.
1435 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1437 switch (Entry.Kind) {
1438 case BitstreamEntry::SubBlock: // Handled for us already.
1439 case BitstreamEntry::Error:
1440 return error("Malformed block");
1441 case BitstreamEntry::EndBlock:
1442 if (NumRecords != TypeList.size())
1443 return error("Malformed block");
1444 return std::error_code();
1445 case BitstreamEntry::Record:
1446 // The interesting case.
1452 Type *ResultTy = nullptr;
1453 switch (Stream.readRecord(Entry.ID, Record)) {
1455 return error("Invalid value");
1456 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1457 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1458 // type list. This allows us to reserve space.
1459 if (Record.size() < 1)
1460 return error("Invalid record");
1461 TypeList.resize(Record[0]);
1463 case bitc::TYPE_CODE_VOID: // VOID
1464 ResultTy = Type::getVoidTy(Context);
1466 case bitc::TYPE_CODE_HALF: // HALF
1467 ResultTy = Type::getHalfTy(Context);
1469 case bitc::TYPE_CODE_FLOAT: // FLOAT
1470 ResultTy = Type::getFloatTy(Context);
1472 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1473 ResultTy = Type::getDoubleTy(Context);
1475 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1476 ResultTy = Type::getX86_FP80Ty(Context);
1478 case bitc::TYPE_CODE_FP128: // FP128
1479 ResultTy = Type::getFP128Ty(Context);
1481 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1482 ResultTy = Type::getPPC_FP128Ty(Context);
1484 case bitc::TYPE_CODE_LABEL: // LABEL
1485 ResultTy = Type::getLabelTy(Context);
1487 case bitc::TYPE_CODE_METADATA: // METADATA
1488 ResultTy = Type::getMetadataTy(Context);
1490 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1491 ResultTy = Type::getX86_MMXTy(Context);
1493 case bitc::TYPE_CODE_TOKEN: // TOKEN
1494 ResultTy = Type::getTokenTy(Context);
1496 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1497 if (Record.size() < 1)
1498 return error("Invalid record");
1500 uint64_t NumBits = Record[0];
1501 if (NumBits < IntegerType::MIN_INT_BITS ||
1502 NumBits > IntegerType::MAX_INT_BITS)
1503 return error("Bitwidth for integer type out of range");
1504 ResultTy = IntegerType::get(Context, NumBits);
1507 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1508 // [pointee type, address space]
1509 if (Record.size() < 1)
1510 return error("Invalid record");
1511 unsigned AddressSpace = 0;
1512 if (Record.size() == 2)
1513 AddressSpace = Record[1];
1514 ResultTy = getTypeByID(Record[0]);
1516 !PointerType::isValidElementType(ResultTy))
1517 return error("Invalid type");
1518 ResultTy = PointerType::get(ResultTy, AddressSpace);
1521 case bitc::TYPE_CODE_FUNCTION_OLD: {
1522 // FIXME: attrid is dead, remove it in LLVM 4.0
1523 // FUNCTION: [vararg, attrid, retty, paramty x N]
1524 if (Record.size() < 3)
1525 return error("Invalid record");
1526 SmallVector<Type*, 8> ArgTys;
1527 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1528 if (Type *T = getTypeByID(Record[i]))
1529 ArgTys.push_back(T);
1534 ResultTy = getTypeByID(Record[2]);
1535 if (!ResultTy || ArgTys.size() < Record.size()-3)
1536 return error("Invalid type");
1538 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1541 case bitc::TYPE_CODE_FUNCTION: {
1542 // FUNCTION: [vararg, retty, paramty x N]
1543 if (Record.size() < 2)
1544 return error("Invalid record");
1545 SmallVector<Type*, 8> ArgTys;
1546 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1547 if (Type *T = getTypeByID(Record[i])) {
1548 if (!FunctionType::isValidArgumentType(T))
1549 return error("Invalid function argument type");
1550 ArgTys.push_back(T);
1556 ResultTy = getTypeByID(Record[1]);
1557 if (!ResultTy || ArgTys.size() < Record.size()-2)
1558 return error("Invalid type");
1560 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1563 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1564 if (Record.size() < 1)
1565 return error("Invalid record");
1566 SmallVector<Type*, 8> EltTys;
1567 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1568 if (Type *T = getTypeByID(Record[i]))
1569 EltTys.push_back(T);
1573 if (EltTys.size() != Record.size()-1)
1574 return error("Invalid type");
1575 ResultTy = StructType::get(Context, EltTys, Record[0]);
1578 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1579 if (convertToString(Record, 0, TypeName))
1580 return error("Invalid record");
1583 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1584 if (Record.size() < 1)
1585 return error("Invalid record");
1587 if (NumRecords >= TypeList.size())
1588 return error("Invalid TYPE table");
1590 // Check to see if this was forward referenced, if so fill in the temp.
1591 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1593 Res->setName(TypeName);
1594 TypeList[NumRecords] = nullptr;
1595 } else // Otherwise, create a new struct.
1596 Res = createIdentifiedStructType(Context, TypeName);
1599 SmallVector<Type*, 8> EltTys;
1600 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1601 if (Type *T = getTypeByID(Record[i]))
1602 EltTys.push_back(T);
1606 if (EltTys.size() != Record.size()-1)
1607 return error("Invalid record");
1608 Res->setBody(EltTys, Record[0]);
1612 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1613 if (Record.size() != 1)
1614 return error("Invalid record");
1616 if (NumRecords >= TypeList.size())
1617 return error("Invalid TYPE table");
1619 // Check to see if this was forward referenced, if so fill in the temp.
1620 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1622 Res->setName(TypeName);
1623 TypeList[NumRecords] = nullptr;
1624 } else // Otherwise, create a new struct with no body.
1625 Res = createIdentifiedStructType(Context, TypeName);
1630 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1631 if (Record.size() < 2)
1632 return error("Invalid record");
1633 ResultTy = getTypeByID(Record[1]);
1634 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1635 return error("Invalid type");
1636 ResultTy = ArrayType::get(ResultTy, Record[0]);
1638 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1639 if (Record.size() < 2)
1640 return error("Invalid record");
1642 return error("Invalid vector length");
1643 ResultTy = getTypeByID(Record[1]);
1644 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1645 return error("Invalid type");
1646 ResultTy = VectorType::get(ResultTy, Record[0]);
1650 if (NumRecords >= TypeList.size())
1651 return error("Invalid TYPE table");
1652 if (TypeList[NumRecords])
1654 "Invalid TYPE table: Only named structs can be forward referenced");
1655 assert(ResultTy && "Didn't read a type?");
1656 TypeList[NumRecords++] = ResultTy;
1660 std::error_code BitcodeReader::parseOperandBundleTags() {
1661 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1662 return error("Invalid record");
1664 if (!BundleTags.empty())
1665 return error("Invalid multiple blocks");
1667 SmallVector<uint64_t, 64> Record;
1670 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1672 switch (Entry.Kind) {
1673 case BitstreamEntry::SubBlock: // Handled for us already.
1674 case BitstreamEntry::Error:
1675 return error("Malformed block");
1676 case BitstreamEntry::EndBlock:
1677 return std::error_code();
1678 case BitstreamEntry::Record:
1679 // The interesting case.
1683 // Tags are implicitly mapped to integers by their order.
1685 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1686 return error("Invalid record");
1688 // OPERAND_BUNDLE_TAG: [strchr x N]
1689 BundleTags.emplace_back();
1690 if (convertToString(Record, 0, BundleTags.back()))
1691 return error("Invalid record");
1696 /// Associate a value with its name from the given index in the provided record.
1697 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1698 unsigned NameIndex, Triple &TT) {
1699 SmallString<128> ValueName;
1700 if (convertToString(Record, NameIndex, ValueName))
1701 return error("Invalid record");
1702 unsigned ValueID = Record[0];
1703 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1704 return error("Invalid record");
1705 Value *V = ValueList[ValueID];
1707 StringRef NameStr(ValueName.data(), ValueName.size());
1708 if (NameStr.find_first_of(0) != StringRef::npos)
1709 return error("Invalid value name");
1710 V->setName(NameStr);
1711 auto *GO = dyn_cast<GlobalObject>(V);
1713 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1714 if (TT.isOSBinFormatMachO())
1715 GO->setComdat(nullptr);
1717 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1723 /// Parse the value symbol table at either the current parsing location or
1724 /// at the given bit offset if provided.
1725 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1726 uint64_t CurrentBit;
1727 // Pass in the Offset to distinguish between calling for the module-level
1728 // VST (where we want to jump to the VST offset) and the function-level
1729 // VST (where we don't).
1731 // Save the current parsing location so we can jump back at the end
1733 CurrentBit = Stream.GetCurrentBitNo();
1734 Stream.JumpToBit(Offset * 32);
1736 // Do some checking if we are in debug mode.
1737 BitstreamEntry Entry = Stream.advance();
1738 assert(Entry.Kind == BitstreamEntry::SubBlock);
1739 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1741 // In NDEBUG mode ignore the output so we don't get an unused variable
1747 // Compute the delta between the bitcode indices in the VST (the word offset
1748 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1749 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1750 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1751 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1752 // just before entering the VST subblock because: 1) the EnterSubBlock
1753 // changes the AbbrevID width; 2) the VST block is nested within the same
1754 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1755 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1756 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1757 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1758 unsigned FuncBitcodeOffsetDelta =
1759 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1761 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1762 return error("Invalid record");
1764 SmallVector<uint64_t, 64> Record;
1766 Triple TT(TheModule->getTargetTriple());
1768 // Read all the records for this value table.
1769 SmallString<128> ValueName;
1771 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1773 switch (Entry.Kind) {
1774 case BitstreamEntry::SubBlock: // Handled for us already.
1775 case BitstreamEntry::Error:
1776 return error("Malformed block");
1777 case BitstreamEntry::EndBlock:
1779 Stream.JumpToBit(CurrentBit);
1780 return std::error_code();
1781 case BitstreamEntry::Record:
1782 // The interesting case.
1788 switch (Stream.readRecord(Entry.ID, Record)) {
1789 default: // Default behavior: unknown type.
1791 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1792 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1793 if (std::error_code EC = ValOrErr.getError())
1798 case bitc::VST_CODE_FNENTRY: {
1799 // VST_FNENTRY: [valueid, offset, namechar x N]
1800 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1801 if (std::error_code EC = ValOrErr.getError())
1803 Value *V = ValOrErr.get();
1805 auto *GO = dyn_cast<GlobalObject>(V);
1807 // If this is an alias, need to get the actual Function object
1808 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1809 auto *GA = dyn_cast<GlobalAlias>(V);
1811 GO = GA->getBaseObject();
1815 uint64_t FuncWordOffset = Record[1];
1816 Function *F = dyn_cast<Function>(GO);
1818 uint64_t FuncBitOffset = FuncWordOffset * 32;
1819 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1820 // Set the LastFunctionBlockBit to point to the last function block.
1821 // Later when parsing is resumed after function materialization,
1822 // we can simply skip that last function block.
1823 if (FuncBitOffset > LastFunctionBlockBit)
1824 LastFunctionBlockBit = FuncBitOffset;
1827 case bitc::VST_CODE_BBENTRY: {
1828 if (convertToString(Record, 1, ValueName))
1829 return error("Invalid record");
1830 BasicBlock *BB = getBasicBlock(Record[0]);
1832 return error("Invalid record");
1834 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1842 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1844 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1845 if (Record.size() < 2)
1846 return error("Invalid record");
1848 unsigned Kind = Record[0];
1849 SmallString<8> Name(Record.begin() + 1, Record.end());
1851 unsigned NewKind = TheModule->getMDKindID(Name.str());
1852 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1853 return error("Conflicting METADATA_KIND records");
1854 return std::error_code();
1857 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1859 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1860 /// module level metadata.
1861 std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
1862 IsMetadataMaterialized = true;
1863 unsigned NextMDValueNo = MDValueList.size();
1864 if (ModuleLevel && SeenModuleValuesRecord) {
1865 // Now that we are parsing the module level metadata, we want to restart
1866 // the numbering of the MD values, and replace temp MD created earlier
1867 // with their real values. If we saw a METADATA_VALUE record then we
1868 // would have set the MDValueList size to the number specified in that
1869 // record, to support parsing function-level metadata first, and we need
1870 // to reset back to 0 to fill the MDValueList in with the parsed module
1871 // The function-level metadata parsing should have reset the MDValueList
1872 // size back to the value reported by the METADATA_VALUE record, saved in
1874 assert(NumModuleMDs == MDValueList.size() &&
1875 "Expected MDValueList to only contain module level values");
1879 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1880 return error("Invalid record");
1882 SmallVector<uint64_t, 64> Record;
1885 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1886 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1888 return getMD(ID - 1);
1891 auto getMDString = [&](unsigned ID) -> MDString *{
1892 // This requires that the ID is not really a forward reference. In
1893 // particular, the MDString must already have been resolved.
1894 return cast_or_null<MDString>(getMDOrNull(ID));
1897 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1898 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1900 // Read all the records.
1902 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1904 switch (Entry.Kind) {
1905 case BitstreamEntry::SubBlock: // Handled for us already.
1906 case BitstreamEntry::Error:
1907 return error("Malformed block");
1908 case BitstreamEntry::EndBlock:
1909 MDValueList.tryToResolveCycles();
1910 assert((!(ModuleLevel && SeenModuleValuesRecord) ||
1911 NumModuleMDs == MDValueList.size()) &&
1912 "Inconsistent bitcode: METADATA_VALUES mismatch");
1913 return std::error_code();
1914 case BitstreamEntry::Record:
1915 // The interesting case.
1921 unsigned Code = Stream.readRecord(Entry.ID, Record);
1922 bool IsDistinct = false;
1924 default: // Default behavior: ignore.
1926 case bitc::METADATA_NAME: {
1927 // Read name of the named metadata.
1928 SmallString<8> Name(Record.begin(), Record.end());
1930 Code = Stream.ReadCode();
1932 unsigned NextBitCode = Stream.readRecord(Code, Record);
1933 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1934 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1936 // Read named metadata elements.
1937 unsigned Size = Record.size();
1938 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1939 for (unsigned i = 0; i != Size; ++i) {
1940 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1942 return error("Invalid record");
1943 NMD->addOperand(MD);
1947 case bitc::METADATA_OLD_FN_NODE: {
1948 // FIXME: Remove in 4.0.
1949 // This is a LocalAsMetadata record, the only type of function-local
1951 if (Record.size() % 2 == 1)
1952 return error("Invalid record");
1954 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1955 // to be legal, but there's no upgrade path.
1956 auto dropRecord = [&] {
1957 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1959 if (Record.size() != 2) {
1964 Type *Ty = getTypeByID(Record[0]);
1965 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1970 MDValueList.assignValue(
1971 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1975 case bitc::METADATA_OLD_NODE: {
1976 // FIXME: Remove in 4.0.
1977 if (Record.size() % 2 == 1)
1978 return error("Invalid record");
1980 unsigned Size = Record.size();
1981 SmallVector<Metadata *, 8> Elts;
1982 for (unsigned i = 0; i != Size; i += 2) {
1983 Type *Ty = getTypeByID(Record[i]);
1985 return error("Invalid record");
1986 if (Ty->isMetadataTy())
1987 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1988 else if (!Ty->isVoidTy()) {
1990 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1991 assert(isa<ConstantAsMetadata>(MD) &&
1992 "Expected non-function-local metadata");
1995 Elts.push_back(nullptr);
1997 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2000 case bitc::METADATA_VALUE: {
2001 if (Record.size() != 2)
2002 return error("Invalid record");
2004 Type *Ty = getTypeByID(Record[0]);
2005 if (Ty->isMetadataTy() || Ty->isVoidTy())
2006 return error("Invalid record");
2008 MDValueList.assignValue(
2009 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2013 case bitc::METADATA_DISTINCT_NODE:
2016 case bitc::METADATA_NODE: {
2017 SmallVector<Metadata *, 8> Elts;
2018 Elts.reserve(Record.size());
2019 for (unsigned ID : Record)
2020 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2021 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2022 : MDNode::get(Context, Elts),
2026 case bitc::METADATA_LOCATION: {
2027 if (Record.size() != 5)
2028 return error("Invalid record");
2030 unsigned Line = Record[1];
2031 unsigned Column = Record[2];
2032 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2033 Metadata *InlinedAt =
2034 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2035 MDValueList.assignValue(
2036 GET_OR_DISTINCT(DILocation, Record[0],
2037 (Context, Line, Column, Scope, InlinedAt)),
2041 case bitc::METADATA_GENERIC_DEBUG: {
2042 if (Record.size() < 4)
2043 return error("Invalid record");
2045 unsigned Tag = Record[1];
2046 unsigned Version = Record[2];
2048 if (Tag >= 1u << 16 || Version != 0)
2049 return error("Invalid record");
2051 auto *Header = getMDString(Record[3]);
2052 SmallVector<Metadata *, 8> DwarfOps;
2053 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2054 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2056 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2057 (Context, Tag, Header, DwarfOps)),
2061 case bitc::METADATA_SUBRANGE: {
2062 if (Record.size() != 3)
2063 return error("Invalid record");
2065 MDValueList.assignValue(
2066 GET_OR_DISTINCT(DISubrange, Record[0],
2067 (Context, Record[1], unrotateSign(Record[2]))),
2071 case bitc::METADATA_ENUMERATOR: {
2072 if (Record.size() != 3)
2073 return error("Invalid record");
2075 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2076 (Context, unrotateSign(Record[1]),
2077 getMDString(Record[2]))),
2081 case bitc::METADATA_BASIC_TYPE: {
2082 if (Record.size() != 6)
2083 return error("Invalid record");
2085 MDValueList.assignValue(
2086 GET_OR_DISTINCT(DIBasicType, Record[0],
2087 (Context, Record[1], getMDString(Record[2]),
2088 Record[3], Record[4], Record[5])),
2092 case bitc::METADATA_DERIVED_TYPE: {
2093 if (Record.size() != 12)
2094 return error("Invalid record");
2096 MDValueList.assignValue(
2097 GET_OR_DISTINCT(DIDerivedType, Record[0],
2098 (Context, Record[1], getMDString(Record[2]),
2099 getMDOrNull(Record[3]), Record[4],
2100 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2101 Record[7], Record[8], Record[9], Record[10],
2102 getMDOrNull(Record[11]))),
2106 case bitc::METADATA_COMPOSITE_TYPE: {
2107 if (Record.size() != 16)
2108 return error("Invalid record");
2110 MDValueList.assignValue(
2111 GET_OR_DISTINCT(DICompositeType, Record[0],
2112 (Context, Record[1], getMDString(Record[2]),
2113 getMDOrNull(Record[3]), Record[4],
2114 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2115 Record[7], Record[8], Record[9], Record[10],
2116 getMDOrNull(Record[11]), Record[12],
2117 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2118 getMDString(Record[15]))),
2122 case bitc::METADATA_SUBROUTINE_TYPE: {
2123 if (Record.size() != 3)
2124 return error("Invalid record");
2126 MDValueList.assignValue(
2127 GET_OR_DISTINCT(DISubroutineType, Record[0],
2128 (Context, Record[1], getMDOrNull(Record[2]))),
2133 case bitc::METADATA_MODULE: {
2134 if (Record.size() != 6)
2135 return error("Invalid record");
2137 MDValueList.assignValue(
2138 GET_OR_DISTINCT(DIModule, Record[0],
2139 (Context, getMDOrNull(Record[1]),
2140 getMDString(Record[2]), getMDString(Record[3]),
2141 getMDString(Record[4]), getMDString(Record[5]))),
2146 case bitc::METADATA_FILE: {
2147 if (Record.size() != 3)
2148 return error("Invalid record");
2150 MDValueList.assignValue(
2151 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2152 getMDString(Record[2]))),
2156 case bitc::METADATA_COMPILE_UNIT: {
2157 if (Record.size() < 14 || Record.size() > 16)
2158 return error("Invalid record");
2160 // Ignore Record[0], which indicates whether this compile unit is
2161 // distinct. It's always distinct.
2162 MDValueList.assignValue(
2163 DICompileUnit::getDistinct(
2164 Context, Record[1], getMDOrNull(Record[2]),
2165 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2166 Record[6], getMDString(Record[7]), Record[8],
2167 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2168 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2169 getMDOrNull(Record[13]),
2170 Record.size() <= 15 ? 0 : getMDOrNull(Record[15]),
2171 Record.size() <= 14 ? 0 : Record[14]),
2175 case bitc::METADATA_SUBPROGRAM: {
2176 if (Record.size() != 18 && Record.size() != 19)
2177 return error("Invalid record");
2179 bool HasFn = Record.size() == 19;
2180 DISubprogram *SP = GET_OR_DISTINCT(
2182 Record[0] || Record[8], // All definitions should be distinct.
2183 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2184 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2185 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2186 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2187 Record[14], getMDOrNull(Record[15 + HasFn]),
2188 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2189 MDValueList.assignValue(SP, NextMDValueNo++);
2191 // Upgrade sp->function mapping to function->sp mapping.
2192 if (HasFn && Record[15]) {
2193 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2194 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2195 if (F->isMaterializable())
2196 // Defer until materialized; unmaterialized functions may not have
2198 FunctionsWithSPs[F] = SP;
2199 else if (!F->empty())
2200 F->setSubprogram(SP);
2205 case bitc::METADATA_LEXICAL_BLOCK: {
2206 if (Record.size() != 5)
2207 return error("Invalid record");
2209 MDValueList.assignValue(
2210 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2211 (Context, getMDOrNull(Record[1]),
2212 getMDOrNull(Record[2]), Record[3], Record[4])),
2216 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2217 if (Record.size() != 4)
2218 return error("Invalid record");
2220 MDValueList.assignValue(
2221 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2222 (Context, getMDOrNull(Record[1]),
2223 getMDOrNull(Record[2]), Record[3])),
2227 case bitc::METADATA_NAMESPACE: {
2228 if (Record.size() != 5)
2229 return error("Invalid record");
2231 MDValueList.assignValue(
2232 GET_OR_DISTINCT(DINamespace, Record[0],
2233 (Context, getMDOrNull(Record[1]),
2234 getMDOrNull(Record[2]), getMDString(Record[3]),
2239 case bitc::METADATA_MACRO: {
2240 if (Record.size() != 5)
2241 return error("Invalid record");
2243 MDValueList.assignValue(
2244 GET_OR_DISTINCT(DIMacro, Record[0],
2245 (Context, Record[1], Record[2],
2246 getMDString(Record[3]), getMDString(Record[4]))),
2250 case bitc::METADATA_MACRO_FILE: {
2251 if (Record.size() != 5)
2252 return error("Invalid record");
2254 MDValueList.assignValue(
2255 GET_OR_DISTINCT(DIMacroFile, Record[0],
2256 (Context, Record[1], Record[2],
2257 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2261 case bitc::METADATA_TEMPLATE_TYPE: {
2262 if (Record.size() != 3)
2263 return error("Invalid record");
2265 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2267 (Context, getMDString(Record[1]),
2268 getMDOrNull(Record[2]))),
2272 case bitc::METADATA_TEMPLATE_VALUE: {
2273 if (Record.size() != 5)
2274 return error("Invalid record");
2276 MDValueList.assignValue(
2277 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2278 (Context, Record[1], getMDString(Record[2]),
2279 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2283 case bitc::METADATA_GLOBAL_VAR: {
2284 if (Record.size() != 11)
2285 return error("Invalid record");
2287 MDValueList.assignValue(
2288 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2289 (Context, getMDOrNull(Record[1]),
2290 getMDString(Record[2]), getMDString(Record[3]),
2291 getMDOrNull(Record[4]), Record[5],
2292 getMDOrNull(Record[6]), Record[7], Record[8],
2293 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2297 case bitc::METADATA_LOCAL_VAR: {
2298 // 10th field is for the obseleted 'inlinedAt:' field.
2299 if (Record.size() < 8 || Record.size() > 10)
2300 return error("Invalid record");
2302 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2303 // DW_TAG_arg_variable.
2304 bool HasTag = Record.size() > 8;
2305 MDValueList.assignValue(
2306 GET_OR_DISTINCT(DILocalVariable, Record[0],
2307 (Context, getMDOrNull(Record[1 + HasTag]),
2308 getMDString(Record[2 + HasTag]),
2309 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2310 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2311 Record[7 + HasTag])),
2315 case bitc::METADATA_EXPRESSION: {
2316 if (Record.size() < 1)
2317 return error("Invalid record");
2319 MDValueList.assignValue(
2320 GET_OR_DISTINCT(DIExpression, Record[0],
2321 (Context, makeArrayRef(Record).slice(1))),
2325 case bitc::METADATA_OBJC_PROPERTY: {
2326 if (Record.size() != 8)
2327 return error("Invalid record");
2329 MDValueList.assignValue(
2330 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2331 (Context, getMDString(Record[1]),
2332 getMDOrNull(Record[2]), Record[3],
2333 getMDString(Record[4]), getMDString(Record[5]),
2334 Record[6], getMDOrNull(Record[7]))),
2338 case bitc::METADATA_IMPORTED_ENTITY: {
2339 if (Record.size() != 6)
2340 return error("Invalid record");
2342 MDValueList.assignValue(
2343 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2344 (Context, Record[1], getMDOrNull(Record[2]),
2345 getMDOrNull(Record[3]), Record[4],
2346 getMDString(Record[5]))),
2350 case bitc::METADATA_STRING: {
2351 std::string String(Record.begin(), Record.end());
2352 llvm::UpgradeMDStringConstant(String);
2353 Metadata *MD = MDString::get(Context, String);
2354 MDValueList.assignValue(MD, NextMDValueNo++);
2357 case bitc::METADATA_KIND: {
2358 // Support older bitcode files that had METADATA_KIND records in a
2359 // block with METADATA_BLOCK_ID.
2360 if (std::error_code EC = parseMetadataKindRecord(Record))
2366 #undef GET_OR_DISTINCT
2369 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2370 std::error_code BitcodeReader::parseMetadataKinds() {
2371 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2372 return error("Invalid record");
2374 SmallVector<uint64_t, 64> Record;
2376 // Read all the records.
2378 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2380 switch (Entry.Kind) {
2381 case BitstreamEntry::SubBlock: // Handled for us already.
2382 case BitstreamEntry::Error:
2383 return error("Malformed block");
2384 case BitstreamEntry::EndBlock:
2385 return std::error_code();
2386 case BitstreamEntry::Record:
2387 // The interesting case.
2393 unsigned Code = Stream.readRecord(Entry.ID, Record);
2395 default: // Default behavior: ignore.
2397 case bitc::METADATA_KIND: {
2398 if (std::error_code EC = parseMetadataKindRecord(Record))
2406 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2408 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2413 // There is no such thing as -0 with integers. "-0" really means MININT.
2417 /// Resolve all of the initializers for global values and aliases that we can.
2418 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2419 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2420 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2421 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2422 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2423 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2425 GlobalInitWorklist.swap(GlobalInits);
2426 AliasInitWorklist.swap(AliasInits);
2427 FunctionPrefixWorklist.swap(FunctionPrefixes);
2428 FunctionPrologueWorklist.swap(FunctionPrologues);
2429 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2431 while (!GlobalInitWorklist.empty()) {
2432 unsigned ValID = GlobalInitWorklist.back().second;
2433 if (ValID >= ValueList.size()) {
2434 // Not ready to resolve this yet, it requires something later in the file.
2435 GlobalInits.push_back(GlobalInitWorklist.back());
2437 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2438 GlobalInitWorklist.back().first->setInitializer(C);
2440 return error("Expected a constant");
2442 GlobalInitWorklist.pop_back();
2445 while (!AliasInitWorklist.empty()) {
2446 unsigned ValID = AliasInitWorklist.back().second;
2447 if (ValID >= ValueList.size()) {
2448 AliasInits.push_back(AliasInitWorklist.back());
2450 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2452 return error("Expected a constant");
2453 GlobalAlias *Alias = AliasInitWorklist.back().first;
2454 if (C->getType() != Alias->getType())
2455 return error("Alias and aliasee types don't match");
2456 Alias->setAliasee(C);
2458 AliasInitWorklist.pop_back();
2461 while (!FunctionPrefixWorklist.empty()) {
2462 unsigned ValID = FunctionPrefixWorklist.back().second;
2463 if (ValID >= ValueList.size()) {
2464 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2466 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2467 FunctionPrefixWorklist.back().first->setPrefixData(C);
2469 return error("Expected a constant");
2471 FunctionPrefixWorklist.pop_back();
2474 while (!FunctionPrologueWorklist.empty()) {
2475 unsigned ValID = FunctionPrologueWorklist.back().second;
2476 if (ValID >= ValueList.size()) {
2477 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2479 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2480 FunctionPrologueWorklist.back().first->setPrologueData(C);
2482 return error("Expected a constant");
2484 FunctionPrologueWorklist.pop_back();
2487 while (!FunctionPersonalityFnWorklist.empty()) {
2488 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2489 if (ValID >= ValueList.size()) {
2490 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2492 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2493 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2495 return error("Expected a constant");
2497 FunctionPersonalityFnWorklist.pop_back();
2500 return std::error_code();
2503 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2504 SmallVector<uint64_t, 8> Words(Vals.size());
2505 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2506 BitcodeReader::decodeSignRotatedValue);
2508 return APInt(TypeBits, Words);
2511 std::error_code BitcodeReader::parseConstants() {
2512 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2513 return error("Invalid record");
2515 SmallVector<uint64_t, 64> Record;
2517 // Read all the records for this value table.
2518 Type *CurTy = Type::getInt32Ty(Context);
2519 unsigned NextCstNo = ValueList.size();
2521 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2523 switch (Entry.Kind) {
2524 case BitstreamEntry::SubBlock: // Handled for us already.
2525 case BitstreamEntry::Error:
2526 return error("Malformed block");
2527 case BitstreamEntry::EndBlock:
2528 if (NextCstNo != ValueList.size())
2529 return error("Invalid ronstant reference");
2531 // Once all the constants have been read, go through and resolve forward
2533 ValueList.resolveConstantForwardRefs();
2534 return std::error_code();
2535 case BitstreamEntry::Record:
2536 // The interesting case.
2543 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2545 default: // Default behavior: unknown constant
2546 case bitc::CST_CODE_UNDEF: // UNDEF
2547 V = UndefValue::get(CurTy);
2549 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2551 return error("Invalid record");
2552 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2553 return error("Invalid record");
2554 CurTy = TypeList[Record[0]];
2555 continue; // Skip the ValueList manipulation.
2556 case bitc::CST_CODE_NULL: // NULL
2557 V = Constant::getNullValue(CurTy);
2559 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2560 if (!CurTy->isIntegerTy() || Record.empty())
2561 return error("Invalid record");
2562 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2564 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2565 if (!CurTy->isIntegerTy() || Record.empty())
2566 return error("Invalid record");
2569 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2570 V = ConstantInt::get(Context, VInt);
2574 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2576 return error("Invalid record");
2577 if (CurTy->isHalfTy())
2578 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2579 APInt(16, (uint16_t)Record[0])));
2580 else if (CurTy->isFloatTy())
2581 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2582 APInt(32, (uint32_t)Record[0])));
2583 else if (CurTy->isDoubleTy())
2584 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2585 APInt(64, Record[0])));
2586 else if (CurTy->isX86_FP80Ty()) {
2587 // Bits are not stored the same way as a normal i80 APInt, compensate.
2588 uint64_t Rearrange[2];
2589 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2590 Rearrange[1] = Record[0] >> 48;
2591 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2592 APInt(80, Rearrange)));
2593 } else if (CurTy->isFP128Ty())
2594 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2595 APInt(128, Record)));
2596 else if (CurTy->isPPC_FP128Ty())
2597 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2598 APInt(128, Record)));
2600 V = UndefValue::get(CurTy);
2604 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2606 return error("Invalid record");
2608 unsigned Size = Record.size();
2609 SmallVector<Constant*, 16> Elts;
2611 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2612 for (unsigned i = 0; i != Size; ++i)
2613 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2614 STy->getElementType(i)));
2615 V = ConstantStruct::get(STy, Elts);
2616 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2617 Type *EltTy = ATy->getElementType();
2618 for (unsigned i = 0; i != Size; ++i)
2619 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2620 V = ConstantArray::get(ATy, Elts);
2621 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2622 Type *EltTy = VTy->getElementType();
2623 for (unsigned i = 0; i != Size; ++i)
2624 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2625 V = ConstantVector::get(Elts);
2627 V = UndefValue::get(CurTy);
2631 case bitc::CST_CODE_STRING: // STRING: [values]
2632 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2634 return error("Invalid record");
2636 SmallString<16> Elts(Record.begin(), Record.end());
2637 V = ConstantDataArray::getString(Context, Elts,
2638 BitCode == bitc::CST_CODE_CSTRING);
2641 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2643 return error("Invalid record");
2645 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2646 unsigned Size = Record.size();
2648 if (EltTy->isIntegerTy(8)) {
2649 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2650 if (isa<VectorType>(CurTy))
2651 V = ConstantDataVector::get(Context, Elts);
2653 V = ConstantDataArray::get(Context, Elts);
2654 } else if (EltTy->isIntegerTy(16)) {
2655 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2656 if (isa<VectorType>(CurTy))
2657 V = ConstantDataVector::get(Context, Elts);
2659 V = ConstantDataArray::get(Context, Elts);
2660 } else if (EltTy->isIntegerTy(32)) {
2661 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2662 if (isa<VectorType>(CurTy))
2663 V = ConstantDataVector::get(Context, Elts);
2665 V = ConstantDataArray::get(Context, Elts);
2666 } else if (EltTy->isIntegerTy(64)) {
2667 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2668 if (isa<VectorType>(CurTy))
2669 V = ConstantDataVector::get(Context, Elts);
2671 V = ConstantDataArray::get(Context, Elts);
2672 } else if (EltTy->isFloatTy()) {
2673 SmallVector<float, 16> Elts(Size);
2674 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2675 if (isa<VectorType>(CurTy))
2676 V = ConstantDataVector::get(Context, Elts);
2678 V = ConstantDataArray::get(Context, Elts);
2679 } else if (EltTy->isDoubleTy()) {
2680 SmallVector<double, 16> Elts(Size);
2681 std::transform(Record.begin(), Record.end(), Elts.begin(),
2683 if (isa<VectorType>(CurTy))
2684 V = ConstantDataVector::get(Context, Elts);
2686 V = ConstantDataArray::get(Context, Elts);
2688 return error("Invalid type for value");
2693 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2694 if (Record.size() < 3)
2695 return error("Invalid record");
2696 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2698 V = UndefValue::get(CurTy); // Unknown binop.
2700 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2701 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2703 if (Record.size() >= 4) {
2704 if (Opc == Instruction::Add ||
2705 Opc == Instruction::Sub ||
2706 Opc == Instruction::Mul ||
2707 Opc == Instruction::Shl) {
2708 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2709 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2710 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2711 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2712 } else if (Opc == Instruction::SDiv ||
2713 Opc == Instruction::UDiv ||
2714 Opc == Instruction::LShr ||
2715 Opc == Instruction::AShr) {
2716 if (Record[3] & (1 << bitc::PEO_EXACT))
2717 Flags |= SDivOperator::IsExact;
2720 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2724 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2725 if (Record.size() < 3)
2726 return error("Invalid record");
2727 int Opc = getDecodedCastOpcode(Record[0]);
2729 V = UndefValue::get(CurTy); // Unknown cast.
2731 Type *OpTy = getTypeByID(Record[1]);
2733 return error("Invalid record");
2734 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2735 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2736 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2740 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2741 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2743 Type *PointeeType = nullptr;
2744 if (Record.size() % 2)
2745 PointeeType = getTypeByID(Record[OpNum++]);
2746 SmallVector<Constant*, 16> Elts;
2747 while (OpNum != Record.size()) {
2748 Type *ElTy = getTypeByID(Record[OpNum++]);
2750 return error("Invalid record");
2751 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2756 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2758 return error("Explicit gep operator type does not match pointee type "
2759 "of pointer operand");
2761 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2762 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2764 bitc::CST_CODE_CE_INBOUNDS_GEP);
2767 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2768 if (Record.size() < 3)
2769 return error("Invalid record");
2771 Type *SelectorTy = Type::getInt1Ty(Context);
2773 // The selector might be an i1 or an <n x i1>
2774 // Get the type from the ValueList before getting a forward ref.
2775 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2776 if (Value *V = ValueList[Record[0]])
2777 if (SelectorTy != V->getType())
2778 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2780 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2782 ValueList.getConstantFwdRef(Record[1],CurTy),
2783 ValueList.getConstantFwdRef(Record[2],CurTy));
2786 case bitc::CST_CODE_CE_EXTRACTELT
2787 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2788 if (Record.size() < 3)
2789 return error("Invalid record");
2791 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2793 return error("Invalid record");
2794 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2795 Constant *Op1 = nullptr;
2796 if (Record.size() == 4) {
2797 Type *IdxTy = getTypeByID(Record[2]);
2799 return error("Invalid record");
2800 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2801 } else // TODO: Remove with llvm 4.0
2802 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2804 return error("Invalid record");
2805 V = ConstantExpr::getExtractElement(Op0, Op1);
2808 case bitc::CST_CODE_CE_INSERTELT
2809 : { // CE_INSERTELT: [opval, opval, opty, opval]
2810 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2811 if (Record.size() < 3 || !OpTy)
2812 return error("Invalid record");
2813 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2814 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2815 OpTy->getElementType());
2816 Constant *Op2 = nullptr;
2817 if (Record.size() == 4) {
2818 Type *IdxTy = getTypeByID(Record[2]);
2820 return error("Invalid record");
2821 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2822 } else // TODO: Remove with llvm 4.0
2823 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2825 return error("Invalid record");
2826 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2829 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2830 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2831 if (Record.size() < 3 || !OpTy)
2832 return error("Invalid record");
2833 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2834 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2835 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2836 OpTy->getNumElements());
2837 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2838 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2841 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2842 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2844 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2845 if (Record.size() < 4 || !RTy || !OpTy)
2846 return error("Invalid record");
2847 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2848 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2849 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2850 RTy->getNumElements());
2851 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2852 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2855 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2856 if (Record.size() < 4)
2857 return error("Invalid record");
2858 Type *OpTy = getTypeByID(Record[0]);
2860 return error("Invalid record");
2861 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2862 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2864 if (OpTy->isFPOrFPVectorTy())
2865 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2867 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2870 // This maintains backward compatibility, pre-asm dialect keywords.
2871 // FIXME: Remove with the 4.0 release.
2872 case bitc::CST_CODE_INLINEASM_OLD: {
2873 if (Record.size() < 2)
2874 return error("Invalid record");
2875 std::string AsmStr, ConstrStr;
2876 bool HasSideEffects = Record[0] & 1;
2877 bool IsAlignStack = Record[0] >> 1;
2878 unsigned AsmStrSize = Record[1];
2879 if (2+AsmStrSize >= Record.size())
2880 return error("Invalid record");
2881 unsigned ConstStrSize = Record[2+AsmStrSize];
2882 if (3+AsmStrSize+ConstStrSize > Record.size())
2883 return error("Invalid record");
2885 for (unsigned i = 0; i != AsmStrSize; ++i)
2886 AsmStr += (char)Record[2+i];
2887 for (unsigned i = 0; i != ConstStrSize; ++i)
2888 ConstrStr += (char)Record[3+AsmStrSize+i];
2889 PointerType *PTy = cast<PointerType>(CurTy);
2890 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2891 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2894 // This version adds support for the asm dialect keywords (e.g.,
2896 case bitc::CST_CODE_INLINEASM: {
2897 if (Record.size() < 2)
2898 return error("Invalid record");
2899 std::string AsmStr, ConstrStr;
2900 bool HasSideEffects = Record[0] & 1;
2901 bool IsAlignStack = (Record[0] >> 1) & 1;
2902 unsigned AsmDialect = Record[0] >> 2;
2903 unsigned AsmStrSize = Record[1];
2904 if (2+AsmStrSize >= Record.size())
2905 return error("Invalid record");
2906 unsigned ConstStrSize = Record[2+AsmStrSize];
2907 if (3+AsmStrSize+ConstStrSize > Record.size())
2908 return error("Invalid record");
2910 for (unsigned i = 0; i != AsmStrSize; ++i)
2911 AsmStr += (char)Record[2+i];
2912 for (unsigned i = 0; i != ConstStrSize; ++i)
2913 ConstrStr += (char)Record[3+AsmStrSize+i];
2914 PointerType *PTy = cast<PointerType>(CurTy);
2915 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2916 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2917 InlineAsm::AsmDialect(AsmDialect));
2920 case bitc::CST_CODE_BLOCKADDRESS:{
2921 if (Record.size() < 3)
2922 return error("Invalid record");
2923 Type *FnTy = getTypeByID(Record[0]);
2925 return error("Invalid record");
2927 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2929 return error("Invalid record");
2931 // Don't let Fn get dematerialized.
2932 BlockAddressesTaken.insert(Fn);
2934 // If the function is already parsed we can insert the block address right
2937 unsigned BBID = Record[2];
2939 // Invalid reference to entry block.
2940 return error("Invalid ID");
2942 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2943 for (size_t I = 0, E = BBID; I != E; ++I) {
2945 return error("Invalid ID");
2950 // Otherwise insert a placeholder and remember it so it can be inserted
2951 // when the function is parsed.
2952 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2954 BasicBlockFwdRefQueue.push_back(Fn);
2955 if (FwdBBs.size() < BBID + 1)
2956 FwdBBs.resize(BBID + 1);
2958 FwdBBs[BBID] = BasicBlock::Create(Context);
2961 V = BlockAddress::get(Fn, BB);
2966 ValueList.assignValue(V, NextCstNo);
2971 std::error_code BitcodeReader::parseUseLists() {
2972 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2973 return error("Invalid record");
2975 // Read all the records.
2976 SmallVector<uint64_t, 64> Record;
2978 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2980 switch (Entry.Kind) {
2981 case BitstreamEntry::SubBlock: // Handled for us already.
2982 case BitstreamEntry::Error:
2983 return error("Malformed block");
2984 case BitstreamEntry::EndBlock:
2985 return std::error_code();
2986 case BitstreamEntry::Record:
2987 // The interesting case.
2991 // Read a use list record.
2994 switch (Stream.readRecord(Entry.ID, Record)) {
2995 default: // Default behavior: unknown type.
2997 case bitc::USELIST_CODE_BB:
3000 case bitc::USELIST_CODE_DEFAULT: {
3001 unsigned RecordLength = Record.size();
3002 if (RecordLength < 3)
3003 // Records should have at least an ID and two indexes.
3004 return error("Invalid record");
3005 unsigned ID = Record.back();
3010 assert(ID < FunctionBBs.size() && "Basic block not found");
3011 V = FunctionBBs[ID];
3014 unsigned NumUses = 0;
3015 SmallDenseMap<const Use *, unsigned, 16> Order;
3016 for (const Use &U : V->uses()) {
3017 if (++NumUses > Record.size())
3019 Order[&U] = Record[NumUses - 1];
3021 if (Order.size() != Record.size() || NumUses > Record.size())
3022 // Mismatches can happen if the functions are being materialized lazily
3023 // (out-of-order), or a value has been upgraded.
3026 V->sortUseList([&](const Use &L, const Use &R) {
3027 return Order.lookup(&L) < Order.lookup(&R);
3035 /// When we see the block for metadata, remember where it is and then skip it.
3036 /// This lets us lazily deserialize the metadata.
3037 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3038 // Save the current stream state.
3039 uint64_t CurBit = Stream.GetCurrentBitNo();
3040 DeferredMetadataInfo.push_back(CurBit);
3042 // Skip over the block for now.
3043 if (Stream.SkipBlock())
3044 return error("Invalid record");
3045 return std::error_code();
3048 std::error_code BitcodeReader::materializeMetadata() {
3049 for (uint64_t BitPos : DeferredMetadataInfo) {
3050 // Move the bit stream to the saved position.
3051 Stream.JumpToBit(BitPos);
3052 if (std::error_code EC = parseMetadata(true))
3055 DeferredMetadataInfo.clear();
3056 return std::error_code();
3059 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3061 /// When we see the block for a function body, remember where it is and then
3062 /// skip it. This lets us lazily deserialize the functions.
3063 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3064 // Get the function we are talking about.
3065 if (FunctionsWithBodies.empty())
3066 return error("Insufficient function protos");
3068 Function *Fn = FunctionsWithBodies.back();
3069 FunctionsWithBodies.pop_back();
3071 // Save the current stream state.
3072 uint64_t CurBit = Stream.GetCurrentBitNo();
3074 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3075 "Mismatch between VST and scanned function offsets");
3076 DeferredFunctionInfo[Fn] = CurBit;
3078 // Skip over the function block for now.
3079 if (Stream.SkipBlock())
3080 return error("Invalid record");
3081 return std::error_code();
3084 std::error_code BitcodeReader::globalCleanup() {
3085 // Patch the initializers for globals and aliases up.
3086 resolveGlobalAndAliasInits();
3087 if (!GlobalInits.empty() || !AliasInits.empty())
3088 return error("Malformed global initializer set");
3090 // Look for intrinsic functions which need to be upgraded at some point
3091 for (Function &F : *TheModule) {
3093 if (UpgradeIntrinsicFunction(&F, NewFn))
3094 UpgradedIntrinsics[&F] = NewFn;
3097 // Look for global variables which need to be renamed.
3098 for (GlobalVariable &GV : TheModule->globals())
3099 UpgradeGlobalVariable(&GV);
3101 // Force deallocation of memory for these vectors to favor the client that
3102 // want lazy deserialization.
3103 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3104 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3105 return std::error_code();
3108 /// Support for lazy parsing of function bodies. This is required if we
3109 /// either have an old bitcode file without a VST forward declaration record,
3110 /// or if we have an anonymous function being materialized, since anonymous
3111 /// functions do not have a name and are therefore not in the VST.
3112 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3113 Stream.JumpToBit(NextUnreadBit);
3115 if (Stream.AtEndOfStream())
3116 return error("Could not find function in stream");
3118 if (!SeenFirstFunctionBody)
3119 return error("Trying to materialize functions before seeing function blocks");
3121 // An old bitcode file with the symbol table at the end would have
3122 // finished the parse greedily.
3123 assert(SeenValueSymbolTable);
3125 SmallVector<uint64_t, 64> Record;
3128 BitstreamEntry Entry = Stream.advance();
3129 switch (Entry.Kind) {
3131 return error("Expect SubBlock");
3132 case BitstreamEntry::SubBlock:
3135 return error("Expect function block");
3136 case bitc::FUNCTION_BLOCK_ID:
3137 if (std::error_code EC = rememberAndSkipFunctionBody())
3139 NextUnreadBit = Stream.GetCurrentBitNo();
3140 return std::error_code();
3146 std::error_code BitcodeReader::parseBitcodeVersion() {
3147 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3148 return error("Invalid record");
3150 // Read all the records.
3151 SmallVector<uint64_t, 64> Record;
3153 BitstreamEntry Entry = Stream.advance();
3155 switch (Entry.Kind) {
3157 case BitstreamEntry::Error:
3158 return error("Malformed block");
3159 case BitstreamEntry::EndBlock:
3160 return std::error_code();
3161 case BitstreamEntry::Record:
3162 // The interesting case.
3168 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3170 default: // Default behavior: reject
3171 return error("Invalid value");
3172 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3174 convertToString(Record, 0, ProducerIdentification);
3177 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3178 unsigned epoch = (unsigned)Record[0];
3179 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3181 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3182 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3189 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3190 bool ShouldLazyLoadMetadata) {
3192 Stream.JumpToBit(ResumeBit);
3193 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3194 return error("Invalid record");
3196 SmallVector<uint64_t, 64> Record;
3197 std::vector<std::string> SectionTable;
3198 std::vector<std::string> GCTable;
3200 // Read all the records for this module.
3202 BitstreamEntry Entry = Stream.advance();
3204 switch (Entry.Kind) {
3205 case BitstreamEntry::Error:
3206 return error("Malformed block");
3207 case BitstreamEntry::EndBlock:
3208 return globalCleanup();
3210 case BitstreamEntry::SubBlock:
3212 default: // Skip unknown content.
3213 if (Stream.SkipBlock())
3214 return error("Invalid record");
3216 case bitc::BLOCKINFO_BLOCK_ID:
3217 if (Stream.ReadBlockInfoBlock())
3218 return error("Malformed block");
3220 case bitc::PARAMATTR_BLOCK_ID:
3221 if (std::error_code EC = parseAttributeBlock())
3224 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3225 if (std::error_code EC = parseAttributeGroupBlock())
3228 case bitc::TYPE_BLOCK_ID_NEW:
3229 if (std::error_code EC = parseTypeTable())
3232 case bitc::VALUE_SYMTAB_BLOCK_ID:
3233 if (!SeenValueSymbolTable) {
3234 // Either this is an old form VST without function index and an
3235 // associated VST forward declaration record (which would have caused
3236 // the VST to be jumped to and parsed before it was encountered
3237 // normally in the stream), or there were no function blocks to
3238 // trigger an earlier parsing of the VST.
3239 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3240 if (std::error_code EC = parseValueSymbolTable())
3242 SeenValueSymbolTable = true;
3244 // We must have had a VST forward declaration record, which caused
3245 // the parser to jump to and parse the VST earlier.
3246 assert(VSTOffset > 0);
3247 if (Stream.SkipBlock())
3248 return error("Invalid record");
3251 case bitc::CONSTANTS_BLOCK_ID:
3252 if (std::error_code EC = parseConstants())
3254 if (std::error_code EC = resolveGlobalAndAliasInits())
3257 case bitc::METADATA_BLOCK_ID:
3258 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3259 if (std::error_code EC = rememberAndSkipMetadata())
3263 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3264 if (std::error_code EC = parseMetadata(true))
3267 case bitc::METADATA_KIND_BLOCK_ID:
3268 if (std::error_code EC = parseMetadataKinds())
3271 case bitc::FUNCTION_BLOCK_ID:
3272 // If this is the first function body we've seen, reverse the
3273 // FunctionsWithBodies list.
3274 if (!SeenFirstFunctionBody) {
3275 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3276 if (std::error_code EC = globalCleanup())
3278 SeenFirstFunctionBody = true;
3281 if (VSTOffset > 0) {
3282 // If we have a VST forward declaration record, make sure we
3283 // parse the VST now if we haven't already. It is needed to
3284 // set up the DeferredFunctionInfo vector for lazy reading.
3285 if (!SeenValueSymbolTable) {
3286 if (std::error_code EC =
3287 BitcodeReader::parseValueSymbolTable(VSTOffset))
3289 SeenValueSymbolTable = true;
3290 // Fall through so that we record the NextUnreadBit below.
3291 // This is necessary in case we have an anonymous function that
3292 // is later materialized. Since it will not have a VST entry we
3293 // need to fall back to the lazy parse to find its offset.
3295 // If we have a VST forward declaration record, but have already
3296 // parsed the VST (just above, when the first function body was
3297 // encountered here), then we are resuming the parse after
3298 // materializing functions. The ResumeBit points to the
3299 // start of the last function block recorded in the
3300 // DeferredFunctionInfo map. Skip it.
3301 if (Stream.SkipBlock())
3302 return error("Invalid record");
3307 // Support older bitcode files that did not have the function
3308 // index in the VST, nor a VST forward declaration record, as
3309 // well as anonymous functions that do not have VST entries.
3310 // Build the DeferredFunctionInfo vector on the fly.
3311 if (std::error_code EC = rememberAndSkipFunctionBody())
3314 // Suspend parsing when we reach the function bodies. Subsequent
3315 // materialization calls will resume it when necessary. If the bitcode
3316 // file is old, the symbol table will be at the end instead and will not
3317 // have been seen yet. In this case, just finish the parse now.
3318 if (SeenValueSymbolTable) {
3319 NextUnreadBit = Stream.GetCurrentBitNo();
3320 return std::error_code();
3323 case bitc::USELIST_BLOCK_ID:
3324 if (std::error_code EC = parseUseLists())
3327 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3328 if (std::error_code EC = parseOperandBundleTags())
3334 case BitstreamEntry::Record:
3335 // The interesting case.
3341 auto BitCode = Stream.readRecord(Entry.ID, Record);
3343 default: break; // Default behavior, ignore unknown content.
3344 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3345 if (Record.size() < 1)
3346 return error("Invalid record");
3347 // Only version #0 and #1 are supported so far.
3348 unsigned module_version = Record[0];
3349 switch (module_version) {
3351 return error("Invalid value");
3353 UseRelativeIDs = false;
3356 UseRelativeIDs = true;
3361 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3363 if (convertToString(Record, 0, S))
3364 return error("Invalid record");
3365 TheModule->setTargetTriple(S);
3368 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3370 if (convertToString(Record, 0, S))
3371 return error("Invalid record");
3372 TheModule->setDataLayout(S);
3375 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3377 if (convertToString(Record, 0, S))
3378 return error("Invalid record");
3379 TheModule->setModuleInlineAsm(S);
3382 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3383 // FIXME: Remove in 4.0.
3385 if (convertToString(Record, 0, S))
3386 return error("Invalid record");
3390 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3392 if (convertToString(Record, 0, S))
3393 return error("Invalid record");
3394 SectionTable.push_back(S);
3397 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3399 if (convertToString(Record, 0, S))
3400 return error("Invalid record");
3401 GCTable.push_back(S);
3404 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3405 if (Record.size() < 2)
3406 return error("Invalid record");
3407 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3408 unsigned ComdatNameSize = Record[1];
3409 std::string ComdatName;
3410 ComdatName.reserve(ComdatNameSize);
3411 for (unsigned i = 0; i != ComdatNameSize; ++i)
3412 ComdatName += (char)Record[2 + i];
3413 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3414 C->setSelectionKind(SK);
3415 ComdatList.push_back(C);
3418 // GLOBALVAR: [pointer type, isconst, initid,
3419 // linkage, alignment, section, visibility, threadlocal,
3420 // unnamed_addr, externally_initialized, dllstorageclass,
3422 case bitc::MODULE_CODE_GLOBALVAR: {
3423 if (Record.size() < 6)
3424 return error("Invalid record");
3425 Type *Ty = getTypeByID(Record[0]);
3427 return error("Invalid record");
3428 bool isConstant = Record[1] & 1;
3429 bool explicitType = Record[1] & 2;
3430 unsigned AddressSpace;
3432 AddressSpace = Record[1] >> 2;
3434 if (!Ty->isPointerTy())
3435 return error("Invalid type for value");
3436 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3437 Ty = cast<PointerType>(Ty)->getElementType();
3440 uint64_t RawLinkage = Record[3];
3441 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3443 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3445 std::string Section;
3447 if (Record[5]-1 >= SectionTable.size())
3448 return error("Invalid ID");
3449 Section = SectionTable[Record[5]-1];
3451 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3452 // Local linkage must have default visibility.
3453 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3454 // FIXME: Change to an error if non-default in 4.0.
3455 Visibility = getDecodedVisibility(Record[6]);
3457 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3458 if (Record.size() > 7)
3459 TLM = getDecodedThreadLocalMode(Record[7]);
3461 bool UnnamedAddr = false;
3462 if (Record.size() > 8)
3463 UnnamedAddr = Record[8];
3465 bool ExternallyInitialized = false;
3466 if (Record.size() > 9)
3467 ExternallyInitialized = Record[9];
3469 GlobalVariable *NewGV =
3470 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3471 TLM, AddressSpace, ExternallyInitialized);
3472 NewGV->setAlignment(Alignment);
3473 if (!Section.empty())
3474 NewGV->setSection(Section);
3475 NewGV->setVisibility(Visibility);
3476 NewGV->setUnnamedAddr(UnnamedAddr);
3478 if (Record.size() > 10)
3479 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3481 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3483 ValueList.push_back(NewGV);
3485 // Remember which value to use for the global initializer.
3486 if (unsigned InitID = Record[2])
3487 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3489 if (Record.size() > 11) {
3490 if (unsigned ComdatID = Record[11]) {
3491 if (ComdatID > ComdatList.size())
3492 return error("Invalid global variable comdat ID");
3493 NewGV->setComdat(ComdatList[ComdatID - 1]);
3495 } else if (hasImplicitComdat(RawLinkage)) {
3496 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3500 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3501 // alignment, section, visibility, gc, unnamed_addr,
3502 // prologuedata, dllstorageclass, comdat, prefixdata]
3503 case bitc::MODULE_CODE_FUNCTION: {
3504 if (Record.size() < 8)
3505 return error("Invalid record");
3506 Type *Ty = getTypeByID(Record[0]);
3508 return error("Invalid record");
3509 if (auto *PTy = dyn_cast<PointerType>(Ty))
3510 Ty = PTy->getElementType();
3511 auto *FTy = dyn_cast<FunctionType>(Ty);
3513 return error("Invalid type for value");
3514 auto CC = static_cast<CallingConv::ID>(Record[1]);
3515 if (CC & ~CallingConv::MaxID)
3516 return error("Invalid calling convention ID");
3518 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3521 Func->setCallingConv(CC);
3522 bool isProto = Record[2];
3523 uint64_t RawLinkage = Record[3];
3524 Func->setLinkage(getDecodedLinkage(RawLinkage));
3525 Func->setAttributes(getAttributes(Record[4]));
3528 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3530 Func->setAlignment(Alignment);
3532 if (Record[6]-1 >= SectionTable.size())
3533 return error("Invalid ID");
3534 Func->setSection(SectionTable[Record[6]-1]);
3536 // Local linkage must have default visibility.
3537 if (!Func->hasLocalLinkage())
3538 // FIXME: Change to an error if non-default in 4.0.
3539 Func->setVisibility(getDecodedVisibility(Record[7]));
3540 if (Record.size() > 8 && Record[8]) {
3541 if (Record[8]-1 >= GCTable.size())
3542 return error("Invalid ID");
3543 Func->setGC(GCTable[Record[8]-1].c_str());
3545 bool UnnamedAddr = false;
3546 if (Record.size() > 9)
3547 UnnamedAddr = Record[9];
3548 Func->setUnnamedAddr(UnnamedAddr);
3549 if (Record.size() > 10 && Record[10] != 0)
3550 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3552 if (Record.size() > 11)
3553 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3555 upgradeDLLImportExportLinkage(Func, RawLinkage);
3557 if (Record.size() > 12) {
3558 if (unsigned ComdatID = Record[12]) {
3559 if (ComdatID > ComdatList.size())
3560 return error("Invalid function comdat ID");
3561 Func->setComdat(ComdatList[ComdatID - 1]);
3563 } else if (hasImplicitComdat(RawLinkage)) {
3564 Func->setComdat(reinterpret_cast<Comdat *>(1));
3567 if (Record.size() > 13 && Record[13] != 0)
3568 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3570 if (Record.size() > 14 && Record[14] != 0)
3571 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3573 ValueList.push_back(Func);
3575 // If this is a function with a body, remember the prototype we are
3576 // creating now, so that we can match up the body with them later.
3578 Func->setIsMaterializable(true);
3579 FunctionsWithBodies.push_back(Func);
3580 DeferredFunctionInfo[Func] = 0;
3584 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3585 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3586 case bitc::MODULE_CODE_ALIAS:
3587 case bitc::MODULE_CODE_ALIAS_OLD: {
3588 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3589 if (Record.size() < (3 + (unsigned)NewRecord))
3590 return error("Invalid record");
3592 Type *Ty = getTypeByID(Record[OpNum++]);
3594 return error("Invalid record");
3598 auto *PTy = dyn_cast<PointerType>(Ty);
3600 return error("Invalid type for value");
3601 Ty = PTy->getElementType();
3602 AddrSpace = PTy->getAddressSpace();
3604 AddrSpace = Record[OpNum++];
3607 auto Val = Record[OpNum++];
3608 auto Linkage = Record[OpNum++];
3609 auto *NewGA = GlobalAlias::create(
3610 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3611 // Old bitcode files didn't have visibility field.
3612 // Local linkage must have default visibility.
3613 if (OpNum != Record.size()) {
3614 auto VisInd = OpNum++;
3615 if (!NewGA->hasLocalLinkage())
3616 // FIXME: Change to an error if non-default in 4.0.
3617 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3619 if (OpNum != Record.size())
3620 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3622 upgradeDLLImportExportLinkage(NewGA, Linkage);
3623 if (OpNum != Record.size())
3624 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3625 if (OpNum != Record.size())
3626 NewGA->setUnnamedAddr(Record[OpNum++]);
3627 ValueList.push_back(NewGA);
3628 AliasInits.push_back(std::make_pair(NewGA, Val));
3631 /// MODULE_CODE_PURGEVALS: [numvals]
3632 case bitc::MODULE_CODE_PURGEVALS:
3633 // Trim down the value list to the specified size.
3634 if (Record.size() < 1 || Record[0] > ValueList.size())
3635 return error("Invalid record");
3636 ValueList.shrinkTo(Record[0]);
3638 /// MODULE_CODE_VSTOFFSET: [offset]
3639 case bitc::MODULE_CODE_VSTOFFSET:
3640 if (Record.size() < 1)
3641 return error("Invalid record");
3642 VSTOffset = Record[0];
3644 /// MODULE_CODE_METADATA_VALUES: [numvals]
3645 case bitc::MODULE_CODE_METADATA_VALUES:
3646 if (Record.size() < 1)
3647 return error("Invalid record");
3648 assert(!IsMetadataMaterialized);
3649 // This record contains the number of metadata values in the module-level
3650 // METADATA_BLOCK. It is used to support lazy parsing of metadata as
3651 // a postpass, where we will parse function-level metadata first.
3652 // This is needed because the ids of metadata are assigned implicitly
3653 // based on their ordering in the bitcode, with the function-level
3654 // metadata ids starting after the module-level metadata ids. Otherwise,
3655 // we would have to parse the module-level metadata block to prime the
3656 // MDValueList when we are lazy loading metadata during function
3657 // importing. Initialize the MDValueList size here based on the
3658 // record value, regardless of whether we are doing lazy metadata
3659 // loading, so that we have consistent handling and assertion
3660 // checking in parseMetadata for module-level metadata.
3661 NumModuleMDs = Record[0];
3662 SeenModuleValuesRecord = true;
3663 assert(MDValueList.size() == 0);
3664 MDValueList.resize(NumModuleMDs);
3671 /// Helper to read the header common to all bitcode files.
3672 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3673 // Sniff for the signature.
3674 if (Stream.Read(8) != 'B' ||
3675 Stream.Read(8) != 'C' ||
3676 Stream.Read(4) != 0x0 ||
3677 Stream.Read(4) != 0xC ||
3678 Stream.Read(4) != 0xE ||
3679 Stream.Read(4) != 0xD)
3685 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3686 Module *M, bool ShouldLazyLoadMetadata) {
3689 if (std::error_code EC = initStream(std::move(Streamer)))
3692 // Sniff for the signature.
3693 if (!hasValidBitcodeHeader(Stream))
3694 return error("Invalid bitcode signature");
3696 // We expect a number of well-defined blocks, though we don't necessarily
3697 // need to understand them all.
3699 if (Stream.AtEndOfStream()) {
3700 // We didn't really read a proper Module.
3701 return error("Malformed IR file");
3704 BitstreamEntry Entry =
3705 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3707 if (Entry.Kind != BitstreamEntry::SubBlock)
3708 return error("Malformed block");
3710 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3711 parseBitcodeVersion();
3715 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3716 return parseModule(0, ShouldLazyLoadMetadata);
3718 if (Stream.SkipBlock())
3719 return error("Invalid record");
3723 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3724 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3725 return error("Invalid record");
3727 SmallVector<uint64_t, 64> Record;
3730 // Read all the records for this module.
3732 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3734 switch (Entry.Kind) {
3735 case BitstreamEntry::SubBlock: // Handled for us already.
3736 case BitstreamEntry::Error:
3737 return error("Malformed block");
3738 case BitstreamEntry::EndBlock:
3740 case BitstreamEntry::Record:
3741 // The interesting case.
3746 switch (Stream.readRecord(Entry.ID, Record)) {
3747 default: break; // Default behavior, ignore unknown content.
3748 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3750 if (convertToString(Record, 0, S))
3751 return error("Invalid record");
3758 llvm_unreachable("Exit infinite loop");
3761 ErrorOr<std::string> BitcodeReader::parseTriple() {
3762 if (std::error_code EC = initStream(nullptr))
3765 // Sniff for the signature.
3766 if (!hasValidBitcodeHeader(Stream))
3767 return error("Invalid bitcode signature");
3769 // We expect a number of well-defined blocks, though we don't necessarily
3770 // need to understand them all.
3772 BitstreamEntry Entry = Stream.advance();
3774 switch (Entry.Kind) {
3775 case BitstreamEntry::Error:
3776 return error("Malformed block");
3777 case BitstreamEntry::EndBlock:
3778 return std::error_code();
3780 case BitstreamEntry::SubBlock:
3781 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3782 return parseModuleTriple();
3784 // Ignore other sub-blocks.
3785 if (Stream.SkipBlock())
3786 return error("Malformed block");
3789 case BitstreamEntry::Record:
3790 Stream.skipRecord(Entry.ID);
3796 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3797 if (std::error_code EC = initStream(nullptr))
3800 // Sniff for the signature.
3801 if (!hasValidBitcodeHeader(Stream))
3802 return error("Invalid bitcode signature");
3804 // We expect a number of well-defined blocks, though we don't necessarily
3805 // need to understand them all.
3807 BitstreamEntry Entry = Stream.advance();
3808 switch (Entry.Kind) {
3809 case BitstreamEntry::Error:
3810 return error("Malformed block");
3811 case BitstreamEntry::EndBlock:
3812 return std::error_code();
3814 case BitstreamEntry::SubBlock:
3815 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3816 if (std::error_code EC = parseBitcodeVersion())
3818 return ProducerIdentification;
3820 // Ignore other sub-blocks.
3821 if (Stream.SkipBlock())
3822 return error("Malformed block");
3824 case BitstreamEntry::Record:
3825 Stream.skipRecord(Entry.ID);
3831 /// Parse metadata attachments.
3832 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3833 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3834 return error("Invalid record");
3836 SmallVector<uint64_t, 64> Record;
3838 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3840 switch (Entry.Kind) {
3841 case BitstreamEntry::SubBlock: // Handled for us already.
3842 case BitstreamEntry::Error:
3843 return error("Malformed block");
3844 case BitstreamEntry::EndBlock:
3845 return std::error_code();
3846 case BitstreamEntry::Record:
3847 // The interesting case.
3851 // Read a metadata attachment record.
3853 switch (Stream.readRecord(Entry.ID, Record)) {
3854 default: // Default behavior: ignore.
3856 case bitc::METADATA_ATTACHMENT: {
3857 unsigned RecordLength = Record.size();
3859 return error("Invalid record");
3860 if (RecordLength % 2 == 0) {
3861 // A function attachment.
3862 for (unsigned I = 0; I != RecordLength; I += 2) {
3863 auto K = MDKindMap.find(Record[I]);
3864 if (K == MDKindMap.end())
3865 return error("Invalid ID");
3866 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3867 F.setMetadata(K->second, cast<MDNode>(MD));
3872 // An instruction attachment.
3873 Instruction *Inst = InstructionList[Record[0]];
3874 for (unsigned i = 1; i != RecordLength; i = i+2) {
3875 unsigned Kind = Record[i];
3876 DenseMap<unsigned, unsigned>::iterator I =
3877 MDKindMap.find(Kind);
3878 if (I == MDKindMap.end())
3879 return error("Invalid ID");
3880 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3881 if (isa<LocalAsMetadata>(Node))
3882 // Drop the attachment. This used to be legal, but there's no
3885 Inst->setMetadata(I->second, cast<MDNode>(Node));
3886 if (I->second == LLVMContext::MD_tbaa)
3887 InstsWithTBAATag.push_back(Inst);
3895 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3896 LLVMContext &Context = PtrType->getContext();
3897 if (!isa<PointerType>(PtrType))
3898 return error(Context, "Load/Store operand is not a pointer type");
3899 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3901 if (ValType && ValType != ElemType)
3902 return error(Context, "Explicit load/store type does not match pointee "
3903 "type of pointer operand");
3904 if (!PointerType::isLoadableOrStorableType(ElemType))
3905 return error(Context, "Cannot load/store from pointer");
3906 return std::error_code();
3909 /// Lazily parse the specified function body block.
3910 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3911 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3912 return error("Invalid record");
3914 InstructionList.clear();
3915 unsigned ModuleValueListSize = ValueList.size();
3916 unsigned ModuleMDValueListSize = MDValueList.size();
3918 // Add all the function arguments to the value table.
3919 for (Argument &I : F->args())
3920 ValueList.push_back(&I);
3922 unsigned NextValueNo = ValueList.size();
3923 BasicBlock *CurBB = nullptr;
3924 unsigned CurBBNo = 0;
3927 auto getLastInstruction = [&]() -> Instruction * {
3928 if (CurBB && !CurBB->empty())
3929 return &CurBB->back();
3930 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3931 !FunctionBBs[CurBBNo - 1]->empty())
3932 return &FunctionBBs[CurBBNo - 1]->back();
3936 std::vector<OperandBundleDef> OperandBundles;
3938 // Read all the records.
3939 SmallVector<uint64_t, 64> Record;
3941 BitstreamEntry Entry = Stream.advance();
3943 switch (Entry.Kind) {
3944 case BitstreamEntry::Error:
3945 return error("Malformed block");
3946 case BitstreamEntry::EndBlock:
3947 goto OutOfRecordLoop;
3949 case BitstreamEntry::SubBlock:
3951 default: // Skip unknown content.
3952 if (Stream.SkipBlock())
3953 return error("Invalid record");
3955 case bitc::CONSTANTS_BLOCK_ID:
3956 if (std::error_code EC = parseConstants())
3958 NextValueNo = ValueList.size();
3960 case bitc::VALUE_SYMTAB_BLOCK_ID:
3961 if (std::error_code EC = parseValueSymbolTable())
3964 case bitc::METADATA_ATTACHMENT_ID:
3965 if (std::error_code EC = parseMetadataAttachment(*F))
3968 case bitc::METADATA_BLOCK_ID:
3969 if (std::error_code EC = parseMetadata())
3972 case bitc::USELIST_BLOCK_ID:
3973 if (std::error_code EC = parseUseLists())
3979 case BitstreamEntry::Record:
3980 // The interesting case.
3986 Instruction *I = nullptr;
3987 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3989 default: // Default behavior: reject
3990 return error("Invalid value");
3991 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3992 if (Record.size() < 1 || Record[0] == 0)
3993 return error("Invalid record");
3994 // Create all the basic blocks for the function.
3995 FunctionBBs.resize(Record[0]);
3997 // See if anything took the address of blocks in this function.
3998 auto BBFRI = BasicBlockFwdRefs.find(F);
3999 if (BBFRI == BasicBlockFwdRefs.end()) {
4000 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4001 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4003 auto &BBRefs = BBFRI->second;
4004 // Check for invalid basic block references.
4005 if (BBRefs.size() > FunctionBBs.size())
4006 return error("Invalid ID");
4007 assert(!BBRefs.empty() && "Unexpected empty array");
4008 assert(!BBRefs.front() && "Invalid reference to entry block");
4009 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4011 if (I < RE && BBRefs[I]) {
4012 BBRefs[I]->insertInto(F);
4013 FunctionBBs[I] = BBRefs[I];
4015 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4018 // Erase from the table.
4019 BasicBlockFwdRefs.erase(BBFRI);
4022 CurBB = FunctionBBs[0];
4026 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4027 // This record indicates that the last instruction is at the same
4028 // location as the previous instruction with a location.
4029 I = getLastInstruction();
4032 return error("Invalid record");
4033 I->setDebugLoc(LastLoc);
4037 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4038 I = getLastInstruction();
4039 if (!I || Record.size() < 4)
4040 return error("Invalid record");
4042 unsigned Line = Record[0], Col = Record[1];
4043 unsigned ScopeID = Record[2], IAID = Record[3];
4045 MDNode *Scope = nullptr, *IA = nullptr;
4046 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
4047 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
4048 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4049 I->setDebugLoc(LastLoc);
4054 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4057 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4058 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4059 OpNum+1 > Record.size())
4060 return error("Invalid record");
4062 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4064 return error("Invalid record");
4065 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4066 InstructionList.push_back(I);
4067 if (OpNum < Record.size()) {
4068 if (Opc == Instruction::Add ||
4069 Opc == Instruction::Sub ||
4070 Opc == Instruction::Mul ||
4071 Opc == Instruction::Shl) {
4072 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4073 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4074 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4075 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4076 } else if (Opc == Instruction::SDiv ||
4077 Opc == Instruction::UDiv ||
4078 Opc == Instruction::LShr ||
4079 Opc == Instruction::AShr) {
4080 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4081 cast<BinaryOperator>(I)->setIsExact(true);
4082 } else if (isa<FPMathOperator>(I)) {
4083 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4085 I->setFastMathFlags(FMF);
4091 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4094 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4095 OpNum+2 != Record.size())
4096 return error("Invalid record");
4098 Type *ResTy = getTypeByID(Record[OpNum]);
4099 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4100 if (Opc == -1 || !ResTy)
4101 return error("Invalid record");
4102 Instruction *Temp = nullptr;
4103 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4105 InstructionList.push_back(Temp);
4106 CurBB->getInstList().push_back(Temp);
4109 auto CastOp = (Instruction::CastOps)Opc;
4110 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4111 return error("Invalid cast");
4112 I = CastInst::Create(CastOp, Op, ResTy);
4114 InstructionList.push_back(I);
4117 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4118 case bitc::FUNC_CODE_INST_GEP_OLD:
4119 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4125 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4126 InBounds = Record[OpNum++];
4127 Ty = getTypeByID(Record[OpNum++]);
4129 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4134 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4135 return error("Invalid record");
4138 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4141 cast<SequentialType>(BasePtr->getType()->getScalarType())
4144 "Explicit gep type does not match pointee type of pointer operand");
4146 SmallVector<Value*, 16> GEPIdx;
4147 while (OpNum != Record.size()) {
4149 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4150 return error("Invalid record");
4151 GEPIdx.push_back(Op);
4154 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4156 InstructionList.push_back(I);
4158 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4162 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4163 // EXTRACTVAL: [opty, opval, n x indices]
4166 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4167 return error("Invalid record");
4169 unsigned RecSize = Record.size();
4170 if (OpNum == RecSize)
4171 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4173 SmallVector<unsigned, 4> EXTRACTVALIdx;
4174 Type *CurTy = Agg->getType();
4175 for (; OpNum != RecSize; ++OpNum) {
4176 bool IsArray = CurTy->isArrayTy();
4177 bool IsStruct = CurTy->isStructTy();
4178 uint64_t Index = Record[OpNum];
4180 if (!IsStruct && !IsArray)
4181 return error("EXTRACTVAL: Invalid type");
4182 if ((unsigned)Index != Index)
4183 return error("Invalid value");
4184 if (IsStruct && Index >= CurTy->subtypes().size())
4185 return error("EXTRACTVAL: Invalid struct index");
4186 if (IsArray && Index >= CurTy->getArrayNumElements())
4187 return error("EXTRACTVAL: Invalid array index");
4188 EXTRACTVALIdx.push_back((unsigned)Index);
4191 CurTy = CurTy->subtypes()[Index];
4193 CurTy = CurTy->subtypes()[0];
4196 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4197 InstructionList.push_back(I);
4201 case bitc::FUNC_CODE_INST_INSERTVAL: {
4202 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4205 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4206 return error("Invalid record");
4208 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4209 return error("Invalid record");
4211 unsigned RecSize = Record.size();
4212 if (OpNum == RecSize)
4213 return error("INSERTVAL: Invalid instruction with 0 indices");
4215 SmallVector<unsigned, 4> INSERTVALIdx;
4216 Type *CurTy = Agg->getType();
4217 for (; OpNum != RecSize; ++OpNum) {
4218 bool IsArray = CurTy->isArrayTy();
4219 bool IsStruct = CurTy->isStructTy();
4220 uint64_t Index = Record[OpNum];
4222 if (!IsStruct && !IsArray)
4223 return error("INSERTVAL: Invalid type");
4224 if ((unsigned)Index != Index)
4225 return error("Invalid value");
4226 if (IsStruct && Index >= CurTy->subtypes().size())
4227 return error("INSERTVAL: Invalid struct index");
4228 if (IsArray && Index >= CurTy->getArrayNumElements())
4229 return error("INSERTVAL: Invalid array index");
4231 INSERTVALIdx.push_back((unsigned)Index);
4233 CurTy = CurTy->subtypes()[Index];
4235 CurTy = CurTy->subtypes()[0];
4238 if (CurTy != Val->getType())
4239 return error("Inserted value type doesn't match aggregate type");
4241 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4242 InstructionList.push_back(I);
4246 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4247 // obsolete form of select
4248 // handles select i1 ... in old bitcode
4250 Value *TrueVal, *FalseVal, *Cond;
4251 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4252 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4253 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4254 return error("Invalid record");
4256 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4257 InstructionList.push_back(I);
4261 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4262 // new form of select
4263 // handles select i1 or select [N x i1]
4265 Value *TrueVal, *FalseVal, *Cond;
4266 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4267 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4268 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4269 return error("Invalid record");
4271 // select condition can be either i1 or [N x i1]
4272 if (VectorType* vector_type =
4273 dyn_cast<VectorType>(Cond->getType())) {
4275 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4276 return error("Invalid type for value");
4279 if (Cond->getType() != Type::getInt1Ty(Context))
4280 return error("Invalid type for value");
4283 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4284 InstructionList.push_back(I);
4288 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4291 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4292 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4293 return error("Invalid record");
4294 if (!Vec->getType()->isVectorTy())
4295 return error("Invalid type for value");
4296 I = ExtractElementInst::Create(Vec, Idx);
4297 InstructionList.push_back(I);
4301 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4303 Value *Vec, *Elt, *Idx;
4304 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4305 return error("Invalid record");
4306 if (!Vec->getType()->isVectorTy())
4307 return error("Invalid type for value");
4308 if (popValue(Record, OpNum, NextValueNo,
4309 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4310 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4311 return error("Invalid record");
4312 I = InsertElementInst::Create(Vec, Elt, Idx);
4313 InstructionList.push_back(I);
4317 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4319 Value *Vec1, *Vec2, *Mask;
4320 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4321 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4322 return error("Invalid record");
4324 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4325 return error("Invalid record");
4326 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4327 return error("Invalid type for value");
4328 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4329 InstructionList.push_back(I);
4333 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4334 // Old form of ICmp/FCmp returning bool
4335 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4336 // both legal on vectors but had different behaviour.
4337 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4338 // FCmp/ICmp returning bool or vector of bool
4342 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4343 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4344 return error("Invalid record");
4346 unsigned PredVal = Record[OpNum];
4347 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4349 if (IsFP && Record.size() > OpNum+1)
4350 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4352 if (OpNum+1 != Record.size())
4353 return error("Invalid record");
4355 if (LHS->getType()->isFPOrFPVectorTy())
4356 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4358 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4361 I->setFastMathFlags(FMF);
4362 InstructionList.push_back(I);
4366 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4368 unsigned Size = Record.size();
4370 I = ReturnInst::Create(Context);
4371 InstructionList.push_back(I);
4376 Value *Op = nullptr;
4377 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4378 return error("Invalid record");
4379 if (OpNum != Record.size())
4380 return error("Invalid record");
4382 I = ReturnInst::Create(Context, Op);
4383 InstructionList.push_back(I);
4386 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4387 if (Record.size() != 1 && Record.size() != 3)
4388 return error("Invalid record");
4389 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4391 return error("Invalid record");
4393 if (Record.size() == 1) {
4394 I = BranchInst::Create(TrueDest);
4395 InstructionList.push_back(I);
4398 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4399 Value *Cond = getValue(Record, 2, NextValueNo,
4400 Type::getInt1Ty(Context));
4401 if (!FalseDest || !Cond)
4402 return error("Invalid record");
4403 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4404 InstructionList.push_back(I);
4408 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4409 if (Record.size() != 1 && Record.size() != 2)
4410 return error("Invalid record");
4413 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4415 return error("Invalid record");
4416 BasicBlock *UnwindDest = nullptr;
4417 if (Record.size() == 2) {
4418 UnwindDest = getBasicBlock(Record[Idx++]);
4420 return error("Invalid record");
4423 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4424 InstructionList.push_back(I);
4427 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4428 if (Record.size() != 2)
4429 return error("Invalid record");
4432 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4434 return error("Invalid record");
4435 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4437 return error("Invalid record");
4439 I = CatchReturnInst::Create(CatchPad, BB);
4440 InstructionList.push_back(I);
4443 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4444 // We must have, at minimum, the outer scope and the number of arguments.
4445 if (Record.size() < 2)
4446 return error("Invalid record");
4451 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4453 unsigned NumHandlers = Record[Idx++];
4455 SmallVector<BasicBlock *, 2> Handlers;
4456 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4457 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4459 return error("Invalid record");
4460 Handlers.push_back(BB);
4463 BasicBlock *UnwindDest = nullptr;
4464 if (Idx + 1 == Record.size()) {
4465 UnwindDest = getBasicBlock(Record[Idx++]);
4467 return error("Invalid record");
4470 if (Record.size() != Idx)
4471 return error("Invalid record");
4474 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4475 for (BasicBlock *Handler : Handlers)
4476 CatchSwitch->addHandler(Handler);
4478 InstructionList.push_back(I);
4481 case bitc::FUNC_CODE_INST_CATCHPAD:
4482 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4483 // We must have, at minimum, the outer scope and the number of arguments.
4484 if (Record.size() < 2)
4485 return error("Invalid record");
4490 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4492 unsigned NumArgOperands = Record[Idx++];
4494 SmallVector<Value *, 2> Args;
4495 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4497 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4498 return error("Invalid record");
4499 Args.push_back(Val);
4502 if (Record.size() != Idx)
4503 return error("Invalid record");
4505 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4506 I = CleanupPadInst::Create(ParentPad, Args);
4508 I = CatchPadInst::Create(ParentPad, Args);
4509 InstructionList.push_back(I);
4512 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4514 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4515 // "New" SwitchInst format with case ranges. The changes to write this
4516 // format were reverted but we still recognize bitcode that uses it.
4517 // Hopefully someday we will have support for case ranges and can use
4518 // this format again.
4520 Type *OpTy = getTypeByID(Record[1]);
4521 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4523 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4524 BasicBlock *Default = getBasicBlock(Record[3]);
4525 if (!OpTy || !Cond || !Default)
4526 return error("Invalid record");
4528 unsigned NumCases = Record[4];
4530 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4531 InstructionList.push_back(SI);
4533 unsigned CurIdx = 5;
4534 for (unsigned i = 0; i != NumCases; ++i) {
4535 SmallVector<ConstantInt*, 1> CaseVals;
4536 unsigned NumItems = Record[CurIdx++];
4537 for (unsigned ci = 0; ci != NumItems; ++ci) {
4538 bool isSingleNumber = Record[CurIdx++];
4541 unsigned ActiveWords = 1;
4542 if (ValueBitWidth > 64)
4543 ActiveWords = Record[CurIdx++];
4544 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4546 CurIdx += ActiveWords;
4548 if (!isSingleNumber) {
4550 if (ValueBitWidth > 64)
4551 ActiveWords = Record[CurIdx++];
4552 APInt High = readWideAPInt(
4553 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4554 CurIdx += ActiveWords;
4556 // FIXME: It is not clear whether values in the range should be
4557 // compared as signed or unsigned values. The partially
4558 // implemented changes that used this format in the past used
4559 // unsigned comparisons.
4560 for ( ; Low.ule(High); ++Low)
4561 CaseVals.push_back(ConstantInt::get(Context, Low));
4563 CaseVals.push_back(ConstantInt::get(Context, Low));
4565 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4566 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4567 cve = CaseVals.end(); cvi != cve; ++cvi)
4568 SI->addCase(*cvi, DestBB);
4574 // Old SwitchInst format without case ranges.
4576 if (Record.size() < 3 || (Record.size() & 1) == 0)
4577 return error("Invalid record");
4578 Type *OpTy = getTypeByID(Record[0]);
4579 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4580 BasicBlock *Default = getBasicBlock(Record[2]);
4581 if (!OpTy || !Cond || !Default)
4582 return error("Invalid record");
4583 unsigned NumCases = (Record.size()-3)/2;
4584 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4585 InstructionList.push_back(SI);
4586 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4587 ConstantInt *CaseVal =
4588 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4589 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4590 if (!CaseVal || !DestBB) {
4592 return error("Invalid record");
4594 SI->addCase(CaseVal, DestBB);
4599 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4600 if (Record.size() < 2)
4601 return error("Invalid record");
4602 Type *OpTy = getTypeByID(Record[0]);
4603 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4604 if (!OpTy || !Address)
4605 return error("Invalid record");
4606 unsigned NumDests = Record.size()-2;
4607 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4608 InstructionList.push_back(IBI);
4609 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4610 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4611 IBI->addDestination(DestBB);
4614 return error("Invalid record");
4621 case bitc::FUNC_CODE_INST_INVOKE: {
4622 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4623 if (Record.size() < 4)
4624 return error("Invalid record");
4626 AttributeSet PAL = getAttributes(Record[OpNum++]);
4627 unsigned CCInfo = Record[OpNum++];
4628 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4629 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4631 FunctionType *FTy = nullptr;
4632 if (CCInfo >> 13 & 1 &&
4633 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4634 return error("Explicit invoke type is not a function type");
4637 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4638 return error("Invalid record");
4640 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4642 return error("Callee is not a pointer");
4644 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4646 return error("Callee is not of pointer to function type");
4647 } else if (CalleeTy->getElementType() != FTy)
4648 return error("Explicit invoke type does not match pointee type of "
4650 if (Record.size() < FTy->getNumParams() + OpNum)
4651 return error("Insufficient operands to call");
4653 SmallVector<Value*, 16> Ops;
4654 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4655 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4656 FTy->getParamType(i)));
4658 return error("Invalid record");
4661 if (!FTy->isVarArg()) {
4662 if (Record.size() != OpNum)
4663 return error("Invalid record");
4665 // Read type/value pairs for varargs params.
4666 while (OpNum != Record.size()) {
4668 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4669 return error("Invalid record");
4674 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4675 OperandBundles.clear();
4676 InstructionList.push_back(I);
4677 cast<InvokeInst>(I)->setCallingConv(
4678 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4679 cast<InvokeInst>(I)->setAttributes(PAL);
4682 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4684 Value *Val = nullptr;
4685 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4686 return error("Invalid record");
4687 I = ResumeInst::Create(Val);
4688 InstructionList.push_back(I);
4691 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4692 I = new UnreachableInst(Context);
4693 InstructionList.push_back(I);
4695 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4696 if (Record.size() < 1 || ((Record.size()-1)&1))
4697 return error("Invalid record");
4698 Type *Ty = getTypeByID(Record[0]);
4700 return error("Invalid record");
4702 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4703 InstructionList.push_back(PN);
4705 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4707 // With the new function encoding, it is possible that operands have
4708 // negative IDs (for forward references). Use a signed VBR
4709 // representation to keep the encoding small.
4711 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4713 V = getValue(Record, 1+i, NextValueNo, Ty);
4714 BasicBlock *BB = getBasicBlock(Record[2+i]);
4716 return error("Invalid record");
4717 PN->addIncoming(V, BB);
4723 case bitc::FUNC_CODE_INST_LANDINGPAD:
4724 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4725 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4727 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4728 if (Record.size() < 3)
4729 return error("Invalid record");
4731 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4732 if (Record.size() < 4)
4733 return error("Invalid record");
4735 Type *Ty = getTypeByID(Record[Idx++]);
4737 return error("Invalid record");
4738 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4739 Value *PersFn = nullptr;
4740 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4741 return error("Invalid record");
4743 if (!F->hasPersonalityFn())
4744 F->setPersonalityFn(cast<Constant>(PersFn));
4745 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4746 return error("Personality function mismatch");
4749 bool IsCleanup = !!Record[Idx++];
4750 unsigned NumClauses = Record[Idx++];
4751 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4752 LP->setCleanup(IsCleanup);
4753 for (unsigned J = 0; J != NumClauses; ++J) {
4754 LandingPadInst::ClauseType CT =
4755 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4758 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4760 return error("Invalid record");
4763 assert((CT != LandingPadInst::Catch ||
4764 !isa<ArrayType>(Val->getType())) &&
4765 "Catch clause has a invalid type!");
4766 assert((CT != LandingPadInst::Filter ||
4767 isa<ArrayType>(Val->getType())) &&
4768 "Filter clause has invalid type!");
4769 LP->addClause(cast<Constant>(Val));
4773 InstructionList.push_back(I);
4777 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4778 if (Record.size() != 4)
4779 return error("Invalid record");
4780 uint64_t AlignRecord = Record[3];
4781 const uint64_t InAllocaMask = uint64_t(1) << 5;
4782 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4783 // Reserve bit 7 for SwiftError flag.
4784 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4785 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4786 bool InAlloca = AlignRecord & InAllocaMask;
4787 Type *Ty = getTypeByID(Record[0]);
4788 if ((AlignRecord & ExplicitTypeMask) == 0) {
4789 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4791 return error("Old-style alloca with a non-pointer type");
4792 Ty = PTy->getElementType();
4794 Type *OpTy = getTypeByID(Record[1]);
4795 Value *Size = getFnValueByID(Record[2], OpTy);
4797 if (std::error_code EC =
4798 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4802 return error("Invalid record");
4803 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4804 AI->setUsedWithInAlloca(InAlloca);
4806 InstructionList.push_back(I);
4809 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4812 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4813 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4814 return error("Invalid record");
4817 if (OpNum + 3 == Record.size())
4818 Ty = getTypeByID(Record[OpNum++]);
4819 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4822 Ty = cast<PointerType>(Op->getType())->getElementType();
4825 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4827 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4829 InstructionList.push_back(I);
4832 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4833 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4836 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4837 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4838 return error("Invalid record");
4841 if (OpNum + 5 == Record.size())
4842 Ty = getTypeByID(Record[OpNum++]);
4843 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4846 Ty = cast<PointerType>(Op->getType())->getElementType();
4848 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4849 if (Ordering == NotAtomic || Ordering == Release ||
4850 Ordering == AcquireRelease)
4851 return error("Invalid record");
4852 if (Ordering != NotAtomic && Record[OpNum] == 0)
4853 return error("Invalid record");
4854 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4857 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4859 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4861 InstructionList.push_back(I);
4864 case bitc::FUNC_CODE_INST_STORE:
4865 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4868 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4869 (BitCode == bitc::FUNC_CODE_INST_STORE
4870 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4871 : popValue(Record, OpNum, NextValueNo,
4872 cast<PointerType>(Ptr->getType())->getElementType(),
4874 OpNum + 2 != Record.size())
4875 return error("Invalid record");
4877 if (std::error_code EC =
4878 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4881 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4883 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4884 InstructionList.push_back(I);
4887 case bitc::FUNC_CODE_INST_STOREATOMIC:
4888 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4889 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4892 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4893 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4894 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4895 : popValue(Record, OpNum, NextValueNo,
4896 cast<PointerType>(Ptr->getType())->getElementType(),
4898 OpNum + 4 != Record.size())
4899 return error("Invalid record");
4901 if (std::error_code EC =
4902 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4904 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4905 if (Ordering == NotAtomic || Ordering == Acquire ||
4906 Ordering == AcquireRelease)
4907 return error("Invalid record");
4908 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4909 if (Ordering != NotAtomic && Record[OpNum] == 0)
4910 return error("Invalid record");
4913 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4915 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4916 InstructionList.push_back(I);
4919 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4920 case bitc::FUNC_CODE_INST_CMPXCHG: {
4921 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4922 // failureordering?, isweak?]
4924 Value *Ptr, *Cmp, *New;
4925 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4926 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4927 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4928 : popValue(Record, OpNum, NextValueNo,
4929 cast<PointerType>(Ptr->getType())->getElementType(),
4931 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4932 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4933 return error("Invalid record");
4934 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4935 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4936 return error("Invalid record");
4937 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4939 if (std::error_code EC =
4940 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4942 AtomicOrdering FailureOrdering;
4943 if (Record.size() < 7)
4945 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4947 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4949 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4951 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4953 if (Record.size() < 8) {
4954 // Before weak cmpxchgs existed, the instruction simply returned the
4955 // value loaded from memory, so bitcode files from that era will be
4956 // expecting the first component of a modern cmpxchg.
4957 CurBB->getInstList().push_back(I);
4958 I = ExtractValueInst::Create(I, 0);
4960 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4963 InstructionList.push_back(I);
4966 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4967 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4970 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4971 popValue(Record, OpNum, NextValueNo,
4972 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4973 OpNum+4 != Record.size())
4974 return error("Invalid record");
4975 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4976 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4977 Operation > AtomicRMWInst::LAST_BINOP)
4978 return error("Invalid record");
4979 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4980 if (Ordering == NotAtomic || Ordering == Unordered)
4981 return error("Invalid record");
4982 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4983 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4984 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4985 InstructionList.push_back(I);
4988 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4989 if (2 != Record.size())
4990 return error("Invalid record");
4991 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4992 if (Ordering == NotAtomic || Ordering == Unordered ||
4993 Ordering == Monotonic)
4994 return error("Invalid record");
4995 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4996 I = new FenceInst(Context, Ordering, SynchScope);
4997 InstructionList.push_back(I);
5000 case bitc::FUNC_CODE_INST_CALL: {
5001 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5002 if (Record.size() < 3)
5003 return error("Invalid record");
5006 AttributeSet PAL = getAttributes(Record[OpNum++]);
5007 unsigned CCInfo = Record[OpNum++];
5010 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5011 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5013 return error("Fast math flags indicator set for call with no FMF");
5016 FunctionType *FTy = nullptr;
5017 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5018 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5019 return error("Explicit call type is not a function type");
5022 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5023 return error("Invalid record");
5025 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5027 return error("Callee is not a pointer type");
5029 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5031 return error("Callee is not of pointer to function type");
5032 } else if (OpTy->getElementType() != FTy)
5033 return error("Explicit call type does not match pointee type of "
5035 if (Record.size() < FTy->getNumParams() + OpNum)
5036 return error("Insufficient operands to call");
5038 SmallVector<Value*, 16> Args;
5039 // Read the fixed params.
5040 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5041 if (FTy->getParamType(i)->isLabelTy())
5042 Args.push_back(getBasicBlock(Record[OpNum]));
5044 Args.push_back(getValue(Record, OpNum, NextValueNo,
5045 FTy->getParamType(i)));
5047 return error("Invalid record");
5050 // Read type/value pairs for varargs params.
5051 if (!FTy->isVarArg()) {
5052 if (OpNum != Record.size())
5053 return error("Invalid record");
5055 while (OpNum != Record.size()) {
5057 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5058 return error("Invalid record");
5063 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5064 OperandBundles.clear();
5065 InstructionList.push_back(I);
5066 cast<CallInst>(I)->setCallingConv(
5067 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5068 CallInst::TailCallKind TCK = CallInst::TCK_None;
5069 if (CCInfo & 1 << bitc::CALL_TAIL)
5070 TCK = CallInst::TCK_Tail;
5071 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5072 TCK = CallInst::TCK_MustTail;
5073 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5074 TCK = CallInst::TCK_NoTail;
5075 cast<CallInst>(I)->setTailCallKind(TCK);
5076 cast<CallInst>(I)->setAttributes(PAL);
5078 if (!isa<FPMathOperator>(I))
5079 return error("Fast-math-flags specified for call without "
5080 "floating-point scalar or vector return type");
5081 I->setFastMathFlags(FMF);
5085 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5086 if (Record.size() < 3)
5087 return error("Invalid record");
5088 Type *OpTy = getTypeByID(Record[0]);
5089 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5090 Type *ResTy = getTypeByID(Record[2]);
5091 if (!OpTy || !Op || !ResTy)
5092 return error("Invalid record");
5093 I = new VAArgInst(Op, ResTy);
5094 InstructionList.push_back(I);
5098 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5099 // A call or an invoke can be optionally prefixed with some variable
5100 // number of operand bundle blocks. These blocks are read into
5101 // OperandBundles and consumed at the next call or invoke instruction.
5103 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5104 return error("Invalid record");
5106 std::vector<Value *> Inputs;
5109 while (OpNum != Record.size()) {
5111 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5112 return error("Invalid record");
5113 Inputs.push_back(Op);
5116 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5121 // Add instruction to end of current BB. If there is no current BB, reject
5125 return error("Invalid instruction with no BB");
5127 if (!OperandBundles.empty()) {
5129 return error("Operand bundles found with no consumer");
5131 CurBB->getInstList().push_back(I);
5133 // If this was a terminator instruction, move to the next block.
5134 if (isa<TerminatorInst>(I)) {
5136 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5139 // Non-void values get registered in the value table for future use.
5140 if (I && !I->getType()->isVoidTy())
5141 ValueList.assignValue(I, NextValueNo++);
5146 if (!OperandBundles.empty())
5147 return error("Operand bundles found with no consumer");
5149 // Check the function list for unresolved values.
5150 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5151 if (!A->getParent()) {
5152 // We found at least one unresolved value. Nuke them all to avoid leaks.
5153 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5154 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5155 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5159 return error("Never resolved value found in function");
5163 // FIXME: Check for unresolved forward-declared metadata references
5164 // and clean up leaks.
5166 // Trim the value list down to the size it was before we parsed this function.
5167 ValueList.shrinkTo(ModuleValueListSize);
5168 MDValueList.shrinkTo(ModuleMDValueListSize);
5169 std::vector<BasicBlock*>().swap(FunctionBBs);
5170 return std::error_code();
5173 /// Find the function body in the bitcode stream
5174 std::error_code BitcodeReader::findFunctionInStream(
5176 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5177 while (DeferredFunctionInfoIterator->second == 0) {
5178 // This is the fallback handling for the old format bitcode that
5179 // didn't contain the function index in the VST, or when we have
5180 // an anonymous function which would not have a VST entry.
5181 // Assert that we have one of those two cases.
5182 assert(VSTOffset == 0 || !F->hasName());
5183 // Parse the next body in the stream and set its position in the
5184 // DeferredFunctionInfo map.
5185 if (std::error_code EC = rememberAndSkipFunctionBodies())
5188 return std::error_code();
5191 //===----------------------------------------------------------------------===//
5192 // GVMaterializer implementation
5193 //===----------------------------------------------------------------------===//
5195 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5197 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5198 // In older bitcode we must materialize the metadata before parsing
5199 // any functions, in order to set up the MDValueList properly.
5200 if (!SeenModuleValuesRecord) {
5201 if (std::error_code EC = materializeMetadata())
5205 Function *F = dyn_cast<Function>(GV);
5206 // If it's not a function or is already material, ignore the request.
5207 if (!F || !F->isMaterializable())
5208 return std::error_code();
5210 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5211 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5212 // If its position is recorded as 0, its body is somewhere in the stream
5213 // but we haven't seen it yet.
5214 if (DFII->second == 0)
5215 if (std::error_code EC = findFunctionInStream(F, DFII))
5218 // Move the bit stream to the saved position of the deferred function body.
5219 Stream.JumpToBit(DFII->second);
5221 if (std::error_code EC = parseFunctionBody(F))
5223 F->setIsMaterializable(false);
5228 // Upgrade any old intrinsic calls in the function.
5229 for (auto &I : UpgradedIntrinsics) {
5230 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5233 if (CallInst *CI = dyn_cast<CallInst>(U))
5234 UpgradeIntrinsicCall(CI, I.second);
5238 // Finish fn->subprogram upgrade for materialized functions.
5239 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5240 F->setSubprogram(SP);
5242 // Bring in any functions that this function forward-referenced via
5244 return materializeForwardReferencedFunctions();
5247 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5248 const Function *F = dyn_cast<Function>(GV);
5249 if (!F || F->isDeclaration())
5252 // Dematerializing F would leave dangling references that wouldn't be
5253 // reconnected on re-materialization.
5254 if (BlockAddressesTaken.count(F))
5257 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5260 void BitcodeReader::dematerialize(GlobalValue *GV) {
5261 Function *F = dyn_cast<Function>(GV);
5262 // If this function isn't dematerializable, this is a noop.
5263 if (!F || !isDematerializable(F))
5266 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5268 // Just forget the function body, we can remat it later.
5269 F->dropAllReferences();
5270 F->setIsMaterializable(true);
5273 std::error_code BitcodeReader::materializeModule(Module *M) {
5274 assert(M == TheModule &&
5275 "Can only Materialize the Module this BitcodeReader is attached to.");
5277 if (std::error_code EC = materializeMetadata())
5280 // Promise to materialize all forward references.
5281 WillMaterializeAllForwardRefs = true;
5283 // Iterate over the module, deserializing any functions that are still on
5285 for (Function &F : *TheModule) {
5286 if (std::error_code EC = materialize(&F))
5289 // At this point, if there are any function bodies, parse the rest of
5290 // the bits in the module past the last function block we have recorded
5291 // through either lazy scanning or the VST.
5292 if (LastFunctionBlockBit || NextUnreadBit)
5293 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5296 // Check that all block address forward references got resolved (as we
5298 if (!BasicBlockFwdRefs.empty())
5299 return error("Never resolved function from blockaddress");
5301 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5302 // delete the old functions to clean up. We can't do this unless the entire
5303 // module is materialized because there could always be another function body
5304 // with calls to the old function.
5305 for (auto &I : UpgradedIntrinsics) {
5306 for (auto *U : I.first->users()) {
5307 if (CallInst *CI = dyn_cast<CallInst>(U))
5308 UpgradeIntrinsicCall(CI, I.second);
5310 if (!I.first->use_empty())
5311 I.first->replaceAllUsesWith(I.second);
5312 I.first->eraseFromParent();
5314 UpgradedIntrinsics.clear();
5316 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5317 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5319 UpgradeDebugInfo(*M);
5320 return std::error_code();
5323 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5324 return IdentifiedStructTypes;
5328 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5330 return initLazyStream(std::move(Streamer));
5331 return initStreamFromBuffer();
5334 std::error_code BitcodeReader::initStreamFromBuffer() {
5335 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5336 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5338 if (Buffer->getBufferSize() & 3)
5339 return error("Invalid bitcode signature");
5341 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5342 // The magic number is 0x0B17C0DE stored in little endian.
5343 if (isBitcodeWrapper(BufPtr, BufEnd))
5344 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5345 return error("Invalid bitcode wrapper header");
5347 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5348 Stream.init(&*StreamFile);
5350 return std::error_code();
5354 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5355 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5358 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5359 StreamingMemoryObject &Bytes = *OwnedBytes;
5360 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5361 Stream.init(&*StreamFile);
5363 unsigned char buf[16];
5364 if (Bytes.readBytes(buf, 16, 0) != 16)
5365 return error("Invalid bitcode signature");
5367 if (!isBitcode(buf, buf + 16))
5368 return error("Invalid bitcode signature");
5370 if (isBitcodeWrapper(buf, buf + 4)) {
5371 const unsigned char *bitcodeStart = buf;
5372 const unsigned char *bitcodeEnd = buf + 16;
5373 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5374 Bytes.dropLeadingBytes(bitcodeStart - buf);
5375 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5377 return std::error_code();
5380 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5381 const Twine &Message) {
5382 return ::error(DiagnosticHandler, make_error_code(E), Message);
5385 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5386 return ::error(DiagnosticHandler,
5387 make_error_code(BitcodeError::CorruptedBitcode), Message);
5390 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5391 return ::error(DiagnosticHandler, make_error_code(E));
5394 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5395 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5396 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5397 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
5398 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5400 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5401 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5402 bool CheckFuncSummaryPresenceOnly)
5403 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
5404 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5406 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5408 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5410 // Specialized value symbol table parser used when reading function index
5411 // blocks where we don't actually create global values.
5412 // At the end of this routine the function index is populated with a map
5413 // from function name to FunctionInfo. The function info contains
5414 // the function block's bitcode offset as well as the offset into the
5415 // function summary section.
5416 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5417 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5418 return error("Invalid record");
5420 SmallVector<uint64_t, 64> Record;
5422 // Read all the records for this value table.
5423 SmallString<128> ValueName;
5425 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5427 switch (Entry.Kind) {
5428 case BitstreamEntry::SubBlock: // Handled for us already.
5429 case BitstreamEntry::Error:
5430 return error("Malformed block");
5431 case BitstreamEntry::EndBlock:
5432 return std::error_code();
5433 case BitstreamEntry::Record:
5434 // The interesting case.
5440 switch (Stream.readRecord(Entry.ID, Record)) {
5441 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5443 case bitc::VST_CODE_FNENTRY: {
5444 // VST_FNENTRY: [valueid, offset, namechar x N]
5445 if (convertToString(Record, 2, ValueName))
5446 return error("Invalid record");
5447 unsigned ValueID = Record[0];
5448 uint64_t FuncOffset = Record[1];
5449 std::unique_ptr<FunctionInfo> FuncInfo =
5450 llvm::make_unique<FunctionInfo>(FuncOffset);
5451 if (foundFuncSummary() && !IsLazy) {
5452 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5453 SummaryMap.find(ValueID);
5454 assert(SMI != SummaryMap.end() && "Summary info not found");
5455 FuncInfo->setFunctionSummary(std::move(SMI->second));
5457 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5462 case bitc::VST_CODE_COMBINED_FNENTRY: {
5463 // VST_FNENTRY: [offset, namechar x N]
5464 if (convertToString(Record, 1, ValueName))
5465 return error("Invalid record");
5466 uint64_t FuncSummaryOffset = Record[0];
5467 std::unique_ptr<FunctionInfo> FuncInfo =
5468 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5469 if (foundFuncSummary() && !IsLazy) {
5470 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5471 SummaryMap.find(FuncSummaryOffset);
5472 assert(SMI != SummaryMap.end() && "Summary info not found");
5473 FuncInfo->setFunctionSummary(std::move(SMI->second));
5475 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5484 // Parse just the blocks needed for function index building out of the module.
5485 // At the end of this routine the function Index is populated with a map
5486 // from function name to FunctionInfo. The function info contains
5487 // either the parsed function summary information (when parsing summaries
5488 // eagerly), or just to the function summary record's offset
5489 // if parsing lazily (IsLazy).
5490 std::error_code FunctionIndexBitcodeReader::parseModule() {
5491 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5492 return error("Invalid record");
5494 // Read the function index for this module.
5496 BitstreamEntry Entry = Stream.advance();
5498 switch (Entry.Kind) {
5499 case BitstreamEntry::Error:
5500 return error("Malformed block");
5501 case BitstreamEntry::EndBlock:
5502 return std::error_code();
5504 case BitstreamEntry::SubBlock:
5505 if (CheckFuncSummaryPresenceOnly) {
5506 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) {
5507 SeenFuncSummary = true;
5508 // No need to parse the rest since we found the summary.
5509 return std::error_code();
5511 if (Stream.SkipBlock())
5512 return error("Invalid record");
5516 default: // Skip unknown content.
5517 if (Stream.SkipBlock())
5518 return error("Invalid record");
5520 case bitc::BLOCKINFO_BLOCK_ID:
5521 // Need to parse these to get abbrev ids (e.g. for VST)
5522 if (Stream.ReadBlockInfoBlock())
5523 return error("Malformed block");
5525 case bitc::VALUE_SYMTAB_BLOCK_ID:
5526 if (std::error_code EC = parseValueSymbolTable())
5529 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5530 SeenFuncSummary = true;
5532 // Lazy parsing of summary info, skip it.
5533 if (Stream.SkipBlock())
5534 return error("Invalid record");
5535 } else if (std::error_code EC = parseEntireSummary())
5538 case bitc::MODULE_STRTAB_BLOCK_ID:
5539 if (std::error_code EC = parseModuleStringTable())
5545 case BitstreamEntry::Record:
5546 Stream.skipRecord(Entry.ID);
5552 // Eagerly parse the entire function summary block (i.e. for all functions
5553 // in the index). This populates the FunctionSummary objects in
5555 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5556 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5557 return error("Invalid record");
5559 SmallVector<uint64_t, 64> Record;
5562 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5564 switch (Entry.Kind) {
5565 case BitstreamEntry::SubBlock: // Handled for us already.
5566 case BitstreamEntry::Error:
5567 return error("Malformed block");
5568 case BitstreamEntry::EndBlock:
5569 return std::error_code();
5570 case BitstreamEntry::Record:
5571 // The interesting case.
5575 // Read a record. The record format depends on whether this
5576 // is a per-module index or a combined index file. In the per-module
5577 // case the records contain the associated value's ID for correlation
5578 // with VST entries. In the combined index the correlation is done
5579 // via the bitcode offset of the summary records (which were saved
5580 // in the combined index VST entries). The records also contain
5581 // information used for ThinLTO renaming and importing.
5583 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5584 switch (Stream.readRecord(Entry.ID, Record)) {
5585 default: // Default behavior: ignore.
5587 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5588 case bitc::FS_CODE_PERMODULE_ENTRY: {
5589 unsigned ValueID = Record[0];
5590 bool IsLocal = Record[1];
5591 unsigned InstCount = Record[2];
5592 std::unique_ptr<FunctionSummary> FS =
5593 llvm::make_unique<FunctionSummary>(InstCount);
5594 FS->setLocalFunction(IsLocal);
5595 // The module path string ref set in the summary must be owned by the
5596 // index's module string table. Since we don't have a module path
5597 // string table section in the per-module index, we create a single
5598 // module path string table entry with an empty (0) ID to take
5601 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5602 SummaryMap[ValueID] = std::move(FS);
5604 // FS_COMBINED_ENTRY: [modid, instcount]
5605 case bitc::FS_CODE_COMBINED_ENTRY: {
5606 uint64_t ModuleId = Record[0];
5607 unsigned InstCount = Record[1];
5608 std::unique_ptr<FunctionSummary> FS =
5609 llvm::make_unique<FunctionSummary>(InstCount);
5610 FS->setModulePath(ModuleIdMap[ModuleId]);
5611 SummaryMap[CurRecordBit] = std::move(FS);
5615 llvm_unreachable("Exit infinite loop");
5618 // Parse the module string table block into the Index.
5619 // This populates the ModulePathStringTable map in the index.
5620 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5621 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5622 return error("Invalid record");
5624 SmallVector<uint64_t, 64> Record;
5626 SmallString<128> ModulePath;
5628 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5630 switch (Entry.Kind) {
5631 case BitstreamEntry::SubBlock: // Handled for us already.
5632 case BitstreamEntry::Error:
5633 return error("Malformed block");
5634 case BitstreamEntry::EndBlock:
5635 return std::error_code();
5636 case BitstreamEntry::Record:
5637 // The interesting case.
5642 switch (Stream.readRecord(Entry.ID, Record)) {
5643 default: // Default behavior: ignore.
5645 case bitc::MST_CODE_ENTRY: {
5646 // MST_ENTRY: [modid, namechar x N]
5647 if (convertToString(Record, 1, ModulePath))
5648 return error("Invalid record");
5649 uint64_t ModuleId = Record[0];
5650 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5651 ModuleIdMap[ModuleId] = ModulePathInMap;
5657 llvm_unreachable("Exit infinite loop");
5660 // Parse the function info index from the bitcode streamer into the given index.
5661 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5662 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5665 if (std::error_code EC = initStream(std::move(Streamer)))
5668 // Sniff for the signature.
5669 if (!hasValidBitcodeHeader(Stream))
5670 return error("Invalid bitcode signature");
5672 // We expect a number of well-defined blocks, though we don't necessarily
5673 // need to understand them all.
5675 if (Stream.AtEndOfStream()) {
5676 // We didn't really read a proper Module block.
5677 return error("Malformed block");
5680 BitstreamEntry Entry =
5681 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5683 if (Entry.Kind != BitstreamEntry::SubBlock)
5684 return error("Malformed block");
5686 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5687 // building the function summary index.
5688 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5689 return parseModule();
5691 if (Stream.SkipBlock())
5692 return error("Invalid record");
5696 // Parse the function information at the given offset in the buffer into
5697 // the index. Used to support lazy parsing of function summaries from the
5698 // combined index during importing.
5699 // TODO: This function is not yet complete as it won't have a consumer
5700 // until ThinLTO function importing is added.
5701 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5702 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5703 size_t FunctionSummaryOffset) {
5706 if (std::error_code EC = initStream(std::move(Streamer)))
5709 // Sniff for the signature.
5710 if (!hasValidBitcodeHeader(Stream))
5711 return error("Invalid bitcode signature");
5713 Stream.JumpToBit(FunctionSummaryOffset);
5715 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5717 switch (Entry.Kind) {
5719 return error("Malformed block");
5720 case BitstreamEntry::Record:
5721 // The expected case.
5725 // TODO: Read a record. This interface will be completed when ThinLTO
5726 // importing is added so that it can be tested.
5727 SmallVector<uint64_t, 64> Record;
5728 switch (Stream.readRecord(Entry.ID, Record)) {
5729 case bitc::FS_CODE_COMBINED_ENTRY:
5731 return error("Invalid record");
5734 return std::error_code();
5738 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5740 return initLazyStream(std::move(Streamer));
5741 return initStreamFromBuffer();
5744 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5745 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5746 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5748 if (Buffer->getBufferSize() & 3)
5749 return error("Invalid bitcode signature");
5751 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5752 // The magic number is 0x0B17C0DE stored in little endian.
5753 if (isBitcodeWrapper(BufPtr, BufEnd))
5754 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5755 return error("Invalid bitcode wrapper header");
5757 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5758 Stream.init(&*StreamFile);
5760 return std::error_code();
5763 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5764 std::unique_ptr<DataStreamer> Streamer) {
5765 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5768 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5769 StreamingMemoryObject &Bytes = *OwnedBytes;
5770 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5771 Stream.init(&*StreamFile);
5773 unsigned char buf[16];
5774 if (Bytes.readBytes(buf, 16, 0) != 16)
5775 return error("Invalid bitcode signature");
5777 if (!isBitcode(buf, buf + 16))
5778 return error("Invalid bitcode signature");
5780 if (isBitcodeWrapper(buf, buf + 4)) {
5781 const unsigned char *bitcodeStart = buf;
5782 const unsigned char *bitcodeEnd = buf + 16;
5783 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5784 Bytes.dropLeadingBytes(bitcodeStart - buf);
5785 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5787 return std::error_code();
5791 class BitcodeErrorCategoryType : public std::error_category {
5792 const char *name() const LLVM_NOEXCEPT override {
5793 return "llvm.bitcode";
5795 std::string message(int IE) const override {
5796 BitcodeError E = static_cast<BitcodeError>(IE);
5798 case BitcodeError::InvalidBitcodeSignature:
5799 return "Invalid bitcode signature";
5800 case BitcodeError::CorruptedBitcode:
5801 return "Corrupted bitcode";
5803 llvm_unreachable("Unknown error type!");
5808 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5810 const std::error_category &llvm::BitcodeErrorCategory() {
5811 return *ErrorCategory;
5814 //===----------------------------------------------------------------------===//
5815 // External interface
5816 //===----------------------------------------------------------------------===//
5818 static ErrorOr<std::unique_ptr<Module>>
5819 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5820 BitcodeReader *R, LLVMContext &Context,
5821 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5822 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5823 M->setMaterializer(R);
5825 auto cleanupOnError = [&](std::error_code EC) {
5826 R->releaseBuffer(); // Never take ownership on error.
5830 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5831 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5832 ShouldLazyLoadMetadata))
5833 return cleanupOnError(EC);
5835 if (MaterializeAll) {
5836 // Read in the entire module, and destroy the BitcodeReader.
5837 if (std::error_code EC = M->materializeAllPermanently())
5838 return cleanupOnError(EC);
5840 // Resolve forward references from blockaddresses.
5841 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5842 return cleanupOnError(EC);
5844 return std::move(M);
5847 /// \brief Get a lazy one-at-time loading module from bitcode.
5849 /// This isn't always used in a lazy context. In particular, it's also used by
5850 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5851 /// in forward-referenced functions from block address references.
5853 /// \param[in] MaterializeAll Set to \c true if we should materialize
5855 static ErrorOr<std::unique_ptr<Module>>
5856 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5857 LLVMContext &Context, bool MaterializeAll,
5858 bool ShouldLazyLoadMetadata = false) {
5859 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
5861 ErrorOr<std::unique_ptr<Module>> Ret =
5862 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5863 MaterializeAll, ShouldLazyLoadMetadata);
5867 Buffer.release(); // The BitcodeReader owns it now.
5871 ErrorOr<std::unique_ptr<Module>>
5872 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
5873 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
5874 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5875 ShouldLazyLoadMetadata);
5878 ErrorOr<std::unique_ptr<Module>>
5879 llvm::getStreamedBitcodeModule(StringRef Name,
5880 std::unique_ptr<DataStreamer> Streamer,
5881 LLVMContext &Context) {
5882 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5883 BitcodeReader *R = new BitcodeReader(Context);
5885 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5889 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5890 LLVMContext &Context) {
5891 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5892 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
5893 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5894 // written. We must defer until the Module has been fully materialized.
5897 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
5898 LLVMContext &Context) {
5899 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5900 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
5901 ErrorOr<std::string> Triple = R->parseTriple();
5902 if (Triple.getError())
5904 return Triple.get();
5907 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
5908 LLVMContext &Context) {
5909 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5910 BitcodeReader R(Buf.release(), Context);
5911 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5912 if (ProducerString.getError())
5914 return ProducerString.get();
5917 // Parse the specified bitcode buffer, returning the function info index.
5918 // If IsLazy is false, parse the entire function summary into
5919 // the index. Otherwise skip the function summary section, and only create
5920 // an index object with a map from function name to function summary offset.
5921 // The index is used to perform lazy function summary reading later.
5922 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5923 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer,
5924 DiagnosticHandlerFunction DiagnosticHandler,
5926 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5927 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
5929 auto Index = llvm::make_unique<FunctionInfoIndex>();
5931 auto cleanupOnError = [&](std::error_code EC) {
5932 R.releaseBuffer(); // Never take ownership on error.
5936 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5937 return cleanupOnError(EC);
5939 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5940 return std::move(Index);
5943 // Check if the given bitcode buffer contains a function summary block.
5944 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer,
5945 DiagnosticHandlerFunction DiagnosticHandler) {
5946 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5947 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
5949 auto cleanupOnError = [&](std::error_code EC) {
5950 R.releaseBuffer(); // Never take ownership on error.
5954 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5955 return cleanupOnError(EC);
5957 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5958 return R.foundFuncSummary();
5961 // This method supports lazy reading of function summary data from the combined
5962 // index during ThinLTO function importing. When reading the combined index
5963 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5964 // Then this method is called for each function considered for importing,
5965 // to parse the summary information for the given function name into
5967 std::error_code llvm::readFunctionSummary(
5968 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5969 StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) {
5970 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5971 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
5973 auto cleanupOnError = [&](std::error_code EC) {
5974 R.releaseBuffer(); // Never take ownership on error.
5978 // Lookup the given function name in the FunctionMap, which may
5979 // contain a list of function infos in the case of a COMDAT. Walk through
5980 // and parse each function summary info at the function summary offset
5981 // recorded when parsing the value symbol table.
5982 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5983 size_t FunctionSummaryOffset = FI->bitcodeIndex();
5984 if (std::error_code EC =
5985 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5986 return cleanupOnError(EC);
5989 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5990 return std::error_code();