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_INACCESSIBLEMEM_ONLY:
1234 return Attribute::InaccessibleMemOnly;
1235 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1236 return Attribute::InaccessibleMemOrArgMemOnly;
1237 case bitc::ATTR_KIND_INLINE_HINT:
1238 return Attribute::InlineHint;
1239 case bitc::ATTR_KIND_IN_REG:
1240 return Attribute::InReg;
1241 case bitc::ATTR_KIND_JUMP_TABLE:
1242 return Attribute::JumpTable;
1243 case bitc::ATTR_KIND_MIN_SIZE:
1244 return Attribute::MinSize;
1245 case bitc::ATTR_KIND_NAKED:
1246 return Attribute::Naked;
1247 case bitc::ATTR_KIND_NEST:
1248 return Attribute::Nest;
1249 case bitc::ATTR_KIND_NO_ALIAS:
1250 return Attribute::NoAlias;
1251 case bitc::ATTR_KIND_NO_BUILTIN:
1252 return Attribute::NoBuiltin;
1253 case bitc::ATTR_KIND_NO_CAPTURE:
1254 return Attribute::NoCapture;
1255 case bitc::ATTR_KIND_NO_DUPLICATE:
1256 return Attribute::NoDuplicate;
1257 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1258 return Attribute::NoImplicitFloat;
1259 case bitc::ATTR_KIND_NO_INLINE:
1260 return Attribute::NoInline;
1261 case bitc::ATTR_KIND_NO_RECURSE:
1262 return Attribute::NoRecurse;
1263 case bitc::ATTR_KIND_NON_LAZY_BIND:
1264 return Attribute::NonLazyBind;
1265 case bitc::ATTR_KIND_NON_NULL:
1266 return Attribute::NonNull;
1267 case bitc::ATTR_KIND_DEREFERENCEABLE:
1268 return Attribute::Dereferenceable;
1269 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1270 return Attribute::DereferenceableOrNull;
1271 case bitc::ATTR_KIND_NO_RED_ZONE:
1272 return Attribute::NoRedZone;
1273 case bitc::ATTR_KIND_NO_RETURN:
1274 return Attribute::NoReturn;
1275 case bitc::ATTR_KIND_NO_UNWIND:
1276 return Attribute::NoUnwind;
1277 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1278 return Attribute::OptimizeForSize;
1279 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1280 return Attribute::OptimizeNone;
1281 case bitc::ATTR_KIND_READ_NONE:
1282 return Attribute::ReadNone;
1283 case bitc::ATTR_KIND_READ_ONLY:
1284 return Attribute::ReadOnly;
1285 case bitc::ATTR_KIND_RETURNED:
1286 return Attribute::Returned;
1287 case bitc::ATTR_KIND_RETURNS_TWICE:
1288 return Attribute::ReturnsTwice;
1289 case bitc::ATTR_KIND_S_EXT:
1290 return Attribute::SExt;
1291 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1292 return Attribute::StackAlignment;
1293 case bitc::ATTR_KIND_STACK_PROTECT:
1294 return Attribute::StackProtect;
1295 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1296 return Attribute::StackProtectReq;
1297 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1298 return Attribute::StackProtectStrong;
1299 case bitc::ATTR_KIND_SAFESTACK:
1300 return Attribute::SafeStack;
1301 case bitc::ATTR_KIND_STRUCT_RET:
1302 return Attribute::StructRet;
1303 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1304 return Attribute::SanitizeAddress;
1305 case bitc::ATTR_KIND_SANITIZE_THREAD:
1306 return Attribute::SanitizeThread;
1307 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1308 return Attribute::SanitizeMemory;
1309 case bitc::ATTR_KIND_UW_TABLE:
1310 return Attribute::UWTable;
1311 case bitc::ATTR_KIND_Z_EXT:
1312 return Attribute::ZExt;
1316 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1317 unsigned &Alignment) {
1318 // Note: Alignment in bitcode files is incremented by 1, so that zero
1319 // can be used for default alignment.
1320 if (Exponent > Value::MaxAlignmentExponent + 1)
1321 return error("Invalid alignment value");
1322 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1323 return std::error_code();
1326 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1327 Attribute::AttrKind *Kind) {
1328 *Kind = getAttrFromCode(Code);
1329 if (*Kind == Attribute::None)
1330 return error(BitcodeError::CorruptedBitcode,
1331 "Unknown attribute kind (" + Twine(Code) + ")");
1332 return std::error_code();
1335 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1336 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1337 return error("Invalid record");
1339 if (!MAttributeGroups.empty())
1340 return error("Invalid multiple blocks");
1342 SmallVector<uint64_t, 64> Record;
1344 // Read all the records.
1346 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1348 switch (Entry.Kind) {
1349 case BitstreamEntry::SubBlock: // Handled for us already.
1350 case BitstreamEntry::Error:
1351 return error("Malformed block");
1352 case BitstreamEntry::EndBlock:
1353 return std::error_code();
1354 case BitstreamEntry::Record:
1355 // The interesting case.
1361 switch (Stream.readRecord(Entry.ID, Record)) {
1362 default: // Default behavior: ignore.
1364 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1365 if (Record.size() < 3)
1366 return error("Invalid record");
1368 uint64_t GrpID = Record[0];
1369 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1372 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1373 if (Record[i] == 0) { // Enum attribute
1374 Attribute::AttrKind Kind;
1375 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1378 B.addAttribute(Kind);
1379 } else if (Record[i] == 1) { // Integer attribute
1380 Attribute::AttrKind Kind;
1381 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1383 if (Kind == Attribute::Alignment)
1384 B.addAlignmentAttr(Record[++i]);
1385 else if (Kind == Attribute::StackAlignment)
1386 B.addStackAlignmentAttr(Record[++i]);
1387 else if (Kind == Attribute::Dereferenceable)
1388 B.addDereferenceableAttr(Record[++i]);
1389 else if (Kind == Attribute::DereferenceableOrNull)
1390 B.addDereferenceableOrNullAttr(Record[++i]);
1391 } else { // String attribute
1392 assert((Record[i] == 3 || Record[i] == 4) &&
1393 "Invalid attribute group entry");
1394 bool HasValue = (Record[i++] == 4);
1395 SmallString<64> KindStr;
1396 SmallString<64> ValStr;
1398 while (Record[i] != 0 && i != e)
1399 KindStr += Record[i++];
1400 assert(Record[i] == 0 && "Kind string not null terminated");
1403 // Has a value associated with it.
1404 ++i; // Skip the '0' that terminates the "kind" string.
1405 while (Record[i] != 0 && i != e)
1406 ValStr += Record[i++];
1407 assert(Record[i] == 0 && "Value string not null terminated");
1410 B.addAttribute(KindStr.str(), ValStr.str());
1414 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1421 std::error_code BitcodeReader::parseTypeTable() {
1422 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1423 return error("Invalid record");
1425 return parseTypeTableBody();
1428 std::error_code BitcodeReader::parseTypeTableBody() {
1429 if (!TypeList.empty())
1430 return error("Invalid multiple blocks");
1432 SmallVector<uint64_t, 64> Record;
1433 unsigned NumRecords = 0;
1435 SmallString<64> TypeName;
1437 // Read all the records for this type table.
1439 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1441 switch (Entry.Kind) {
1442 case BitstreamEntry::SubBlock: // Handled for us already.
1443 case BitstreamEntry::Error:
1444 return error("Malformed block");
1445 case BitstreamEntry::EndBlock:
1446 if (NumRecords != TypeList.size())
1447 return error("Malformed block");
1448 return std::error_code();
1449 case BitstreamEntry::Record:
1450 // The interesting case.
1456 Type *ResultTy = nullptr;
1457 switch (Stream.readRecord(Entry.ID, Record)) {
1459 return error("Invalid value");
1460 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1461 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1462 // type list. This allows us to reserve space.
1463 if (Record.size() < 1)
1464 return error("Invalid record");
1465 TypeList.resize(Record[0]);
1467 case bitc::TYPE_CODE_VOID: // VOID
1468 ResultTy = Type::getVoidTy(Context);
1470 case bitc::TYPE_CODE_HALF: // HALF
1471 ResultTy = Type::getHalfTy(Context);
1473 case bitc::TYPE_CODE_FLOAT: // FLOAT
1474 ResultTy = Type::getFloatTy(Context);
1476 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1477 ResultTy = Type::getDoubleTy(Context);
1479 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1480 ResultTy = Type::getX86_FP80Ty(Context);
1482 case bitc::TYPE_CODE_FP128: // FP128
1483 ResultTy = Type::getFP128Ty(Context);
1485 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1486 ResultTy = Type::getPPC_FP128Ty(Context);
1488 case bitc::TYPE_CODE_LABEL: // LABEL
1489 ResultTy = Type::getLabelTy(Context);
1491 case bitc::TYPE_CODE_METADATA: // METADATA
1492 ResultTy = Type::getMetadataTy(Context);
1494 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1495 ResultTy = Type::getX86_MMXTy(Context);
1497 case bitc::TYPE_CODE_TOKEN: // TOKEN
1498 ResultTy = Type::getTokenTy(Context);
1500 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1501 if (Record.size() < 1)
1502 return error("Invalid record");
1504 uint64_t NumBits = Record[0];
1505 if (NumBits < IntegerType::MIN_INT_BITS ||
1506 NumBits > IntegerType::MAX_INT_BITS)
1507 return error("Bitwidth for integer type out of range");
1508 ResultTy = IntegerType::get(Context, NumBits);
1511 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1512 // [pointee type, address space]
1513 if (Record.size() < 1)
1514 return error("Invalid record");
1515 unsigned AddressSpace = 0;
1516 if (Record.size() == 2)
1517 AddressSpace = Record[1];
1518 ResultTy = getTypeByID(Record[0]);
1520 !PointerType::isValidElementType(ResultTy))
1521 return error("Invalid type");
1522 ResultTy = PointerType::get(ResultTy, AddressSpace);
1525 case bitc::TYPE_CODE_FUNCTION_OLD: {
1526 // FIXME: attrid is dead, remove it in LLVM 4.0
1527 // FUNCTION: [vararg, attrid, retty, paramty x N]
1528 if (Record.size() < 3)
1529 return error("Invalid record");
1530 SmallVector<Type*, 8> ArgTys;
1531 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1532 if (Type *T = getTypeByID(Record[i]))
1533 ArgTys.push_back(T);
1538 ResultTy = getTypeByID(Record[2]);
1539 if (!ResultTy || ArgTys.size() < Record.size()-3)
1540 return error("Invalid type");
1542 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1545 case bitc::TYPE_CODE_FUNCTION: {
1546 // FUNCTION: [vararg, retty, paramty x N]
1547 if (Record.size() < 2)
1548 return error("Invalid record");
1549 SmallVector<Type*, 8> ArgTys;
1550 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1551 if (Type *T = getTypeByID(Record[i])) {
1552 if (!FunctionType::isValidArgumentType(T))
1553 return error("Invalid function argument type");
1554 ArgTys.push_back(T);
1560 ResultTy = getTypeByID(Record[1]);
1561 if (!ResultTy || ArgTys.size() < Record.size()-2)
1562 return error("Invalid type");
1564 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1567 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1568 if (Record.size() < 1)
1569 return error("Invalid record");
1570 SmallVector<Type*, 8> EltTys;
1571 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1572 if (Type *T = getTypeByID(Record[i]))
1573 EltTys.push_back(T);
1577 if (EltTys.size() != Record.size()-1)
1578 return error("Invalid type");
1579 ResultTy = StructType::get(Context, EltTys, Record[0]);
1582 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1583 if (convertToString(Record, 0, TypeName))
1584 return error("Invalid record");
1587 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1588 if (Record.size() < 1)
1589 return error("Invalid record");
1591 if (NumRecords >= TypeList.size())
1592 return error("Invalid TYPE table");
1594 // Check to see if this was forward referenced, if so fill in the temp.
1595 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1597 Res->setName(TypeName);
1598 TypeList[NumRecords] = nullptr;
1599 } else // Otherwise, create a new struct.
1600 Res = createIdentifiedStructType(Context, TypeName);
1603 SmallVector<Type*, 8> EltTys;
1604 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1605 if (Type *T = getTypeByID(Record[i]))
1606 EltTys.push_back(T);
1610 if (EltTys.size() != Record.size()-1)
1611 return error("Invalid record");
1612 Res->setBody(EltTys, Record[0]);
1616 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1617 if (Record.size() != 1)
1618 return error("Invalid record");
1620 if (NumRecords >= TypeList.size())
1621 return error("Invalid TYPE table");
1623 // Check to see if this was forward referenced, if so fill in the temp.
1624 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1626 Res->setName(TypeName);
1627 TypeList[NumRecords] = nullptr;
1628 } else // Otherwise, create a new struct with no body.
1629 Res = createIdentifiedStructType(Context, TypeName);
1634 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1635 if (Record.size() < 2)
1636 return error("Invalid record");
1637 ResultTy = getTypeByID(Record[1]);
1638 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1639 return error("Invalid type");
1640 ResultTy = ArrayType::get(ResultTy, Record[0]);
1642 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1643 if (Record.size() < 2)
1644 return error("Invalid record");
1646 return error("Invalid vector length");
1647 ResultTy = getTypeByID(Record[1]);
1648 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1649 return error("Invalid type");
1650 ResultTy = VectorType::get(ResultTy, Record[0]);
1654 if (NumRecords >= TypeList.size())
1655 return error("Invalid TYPE table");
1656 if (TypeList[NumRecords])
1658 "Invalid TYPE table: Only named structs can be forward referenced");
1659 assert(ResultTy && "Didn't read a type?");
1660 TypeList[NumRecords++] = ResultTy;
1664 std::error_code BitcodeReader::parseOperandBundleTags() {
1665 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1666 return error("Invalid record");
1668 if (!BundleTags.empty())
1669 return error("Invalid multiple blocks");
1671 SmallVector<uint64_t, 64> Record;
1674 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1676 switch (Entry.Kind) {
1677 case BitstreamEntry::SubBlock: // Handled for us already.
1678 case BitstreamEntry::Error:
1679 return error("Malformed block");
1680 case BitstreamEntry::EndBlock:
1681 return std::error_code();
1682 case BitstreamEntry::Record:
1683 // The interesting case.
1687 // Tags are implicitly mapped to integers by their order.
1689 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1690 return error("Invalid record");
1692 // OPERAND_BUNDLE_TAG: [strchr x N]
1693 BundleTags.emplace_back();
1694 if (convertToString(Record, 0, BundleTags.back()))
1695 return error("Invalid record");
1700 /// Associate a value with its name from the given index in the provided record.
1701 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1702 unsigned NameIndex, Triple &TT) {
1703 SmallString<128> ValueName;
1704 if (convertToString(Record, NameIndex, ValueName))
1705 return error("Invalid record");
1706 unsigned ValueID = Record[0];
1707 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1708 return error("Invalid record");
1709 Value *V = ValueList[ValueID];
1711 StringRef NameStr(ValueName.data(), ValueName.size());
1712 if (NameStr.find_first_of(0) != StringRef::npos)
1713 return error("Invalid value name");
1714 V->setName(NameStr);
1715 auto *GO = dyn_cast<GlobalObject>(V);
1717 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1718 if (TT.isOSBinFormatMachO())
1719 GO->setComdat(nullptr);
1721 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1727 /// Parse the value symbol table at either the current parsing location or
1728 /// at the given bit offset if provided.
1729 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1730 uint64_t CurrentBit;
1731 // Pass in the Offset to distinguish between calling for the module-level
1732 // VST (where we want to jump to the VST offset) and the function-level
1733 // VST (where we don't).
1735 // Save the current parsing location so we can jump back at the end
1737 CurrentBit = Stream.GetCurrentBitNo();
1738 Stream.JumpToBit(Offset * 32);
1740 // Do some checking if we are in debug mode.
1741 BitstreamEntry Entry = Stream.advance();
1742 assert(Entry.Kind == BitstreamEntry::SubBlock);
1743 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1745 // In NDEBUG mode ignore the output so we don't get an unused variable
1751 // Compute the delta between the bitcode indices in the VST (the word offset
1752 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1753 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1754 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1755 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1756 // just before entering the VST subblock because: 1) the EnterSubBlock
1757 // changes the AbbrevID width; 2) the VST block is nested within the same
1758 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1759 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1760 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1761 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1762 unsigned FuncBitcodeOffsetDelta =
1763 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1765 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1766 return error("Invalid record");
1768 SmallVector<uint64_t, 64> Record;
1770 Triple TT(TheModule->getTargetTriple());
1772 // Read all the records for this value table.
1773 SmallString<128> ValueName;
1775 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1777 switch (Entry.Kind) {
1778 case BitstreamEntry::SubBlock: // Handled for us already.
1779 case BitstreamEntry::Error:
1780 return error("Malformed block");
1781 case BitstreamEntry::EndBlock:
1783 Stream.JumpToBit(CurrentBit);
1784 return std::error_code();
1785 case BitstreamEntry::Record:
1786 // The interesting case.
1792 switch (Stream.readRecord(Entry.ID, Record)) {
1793 default: // Default behavior: unknown type.
1795 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1796 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1797 if (std::error_code EC = ValOrErr.getError())
1802 case bitc::VST_CODE_FNENTRY: {
1803 // VST_FNENTRY: [valueid, offset, namechar x N]
1804 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1805 if (std::error_code EC = ValOrErr.getError())
1807 Value *V = ValOrErr.get();
1809 auto *GO = dyn_cast<GlobalObject>(V);
1811 // If this is an alias, need to get the actual Function object
1812 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1813 auto *GA = dyn_cast<GlobalAlias>(V);
1815 GO = GA->getBaseObject();
1819 uint64_t FuncWordOffset = Record[1];
1820 Function *F = dyn_cast<Function>(GO);
1822 uint64_t FuncBitOffset = FuncWordOffset * 32;
1823 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1824 // Set the LastFunctionBlockBit to point to the last function block.
1825 // Later when parsing is resumed after function materialization,
1826 // we can simply skip that last function block.
1827 if (FuncBitOffset > LastFunctionBlockBit)
1828 LastFunctionBlockBit = FuncBitOffset;
1831 case bitc::VST_CODE_BBENTRY: {
1832 if (convertToString(Record, 1, ValueName))
1833 return error("Invalid record");
1834 BasicBlock *BB = getBasicBlock(Record[0]);
1836 return error("Invalid record");
1838 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1846 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1848 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1849 if (Record.size() < 2)
1850 return error("Invalid record");
1852 unsigned Kind = Record[0];
1853 SmallString<8> Name(Record.begin() + 1, Record.end());
1855 unsigned NewKind = TheModule->getMDKindID(Name.str());
1856 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1857 return error("Conflicting METADATA_KIND records");
1858 return std::error_code();
1861 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1863 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1864 /// module level metadata.
1865 std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
1866 IsMetadataMaterialized = true;
1867 unsigned NextMDValueNo = MDValueList.size();
1868 if (ModuleLevel && SeenModuleValuesRecord) {
1869 // Now that we are parsing the module level metadata, we want to restart
1870 // the numbering of the MD values, and replace temp MD created earlier
1871 // with their real values. If we saw a METADATA_VALUE record then we
1872 // would have set the MDValueList size to the number specified in that
1873 // record, to support parsing function-level metadata first, and we need
1874 // to reset back to 0 to fill the MDValueList in with the parsed module
1875 // The function-level metadata parsing should have reset the MDValueList
1876 // size back to the value reported by the METADATA_VALUE record, saved in
1878 assert(NumModuleMDs == MDValueList.size() &&
1879 "Expected MDValueList to only contain module level values");
1883 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1884 return error("Invalid record");
1886 SmallVector<uint64_t, 64> Record;
1889 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1890 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1892 return getMD(ID - 1);
1895 auto getMDString = [&](unsigned ID) -> MDString *{
1896 // This requires that the ID is not really a forward reference. In
1897 // particular, the MDString must already have been resolved.
1898 return cast_or_null<MDString>(getMDOrNull(ID));
1901 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1902 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1904 // Read all the records.
1906 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1908 switch (Entry.Kind) {
1909 case BitstreamEntry::SubBlock: // Handled for us already.
1910 case BitstreamEntry::Error:
1911 return error("Malformed block");
1912 case BitstreamEntry::EndBlock:
1913 MDValueList.tryToResolveCycles();
1914 assert((!(ModuleLevel && SeenModuleValuesRecord) ||
1915 NumModuleMDs == MDValueList.size()) &&
1916 "Inconsistent bitcode: METADATA_VALUES mismatch");
1917 return std::error_code();
1918 case BitstreamEntry::Record:
1919 // The interesting case.
1925 unsigned Code = Stream.readRecord(Entry.ID, Record);
1926 bool IsDistinct = false;
1928 default: // Default behavior: ignore.
1930 case bitc::METADATA_NAME: {
1931 // Read name of the named metadata.
1932 SmallString<8> Name(Record.begin(), Record.end());
1934 Code = Stream.ReadCode();
1936 unsigned NextBitCode = Stream.readRecord(Code, Record);
1937 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1938 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1940 // Read named metadata elements.
1941 unsigned Size = Record.size();
1942 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1943 for (unsigned i = 0; i != Size; ++i) {
1944 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1946 return error("Invalid record");
1947 NMD->addOperand(MD);
1951 case bitc::METADATA_OLD_FN_NODE: {
1952 // FIXME: Remove in 4.0.
1953 // This is a LocalAsMetadata record, the only type of function-local
1955 if (Record.size() % 2 == 1)
1956 return error("Invalid record");
1958 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1959 // to be legal, but there's no upgrade path.
1960 auto dropRecord = [&] {
1961 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1963 if (Record.size() != 2) {
1968 Type *Ty = getTypeByID(Record[0]);
1969 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1974 MDValueList.assignValue(
1975 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1979 case bitc::METADATA_OLD_NODE: {
1980 // FIXME: Remove in 4.0.
1981 if (Record.size() % 2 == 1)
1982 return error("Invalid record");
1984 unsigned Size = Record.size();
1985 SmallVector<Metadata *, 8> Elts;
1986 for (unsigned i = 0; i != Size; i += 2) {
1987 Type *Ty = getTypeByID(Record[i]);
1989 return error("Invalid record");
1990 if (Ty->isMetadataTy())
1991 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1992 else if (!Ty->isVoidTy()) {
1994 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1995 assert(isa<ConstantAsMetadata>(MD) &&
1996 "Expected non-function-local metadata");
1999 Elts.push_back(nullptr);
2001 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2004 case bitc::METADATA_VALUE: {
2005 if (Record.size() != 2)
2006 return error("Invalid record");
2008 Type *Ty = getTypeByID(Record[0]);
2009 if (Ty->isMetadataTy() || Ty->isVoidTy())
2010 return error("Invalid record");
2012 MDValueList.assignValue(
2013 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2017 case bitc::METADATA_DISTINCT_NODE:
2020 case bitc::METADATA_NODE: {
2021 SmallVector<Metadata *, 8> Elts;
2022 Elts.reserve(Record.size());
2023 for (unsigned ID : Record)
2024 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2025 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2026 : MDNode::get(Context, Elts),
2030 case bitc::METADATA_LOCATION: {
2031 if (Record.size() != 5)
2032 return error("Invalid record");
2034 unsigned Line = Record[1];
2035 unsigned Column = Record[2];
2036 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2037 Metadata *InlinedAt =
2038 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2039 MDValueList.assignValue(
2040 GET_OR_DISTINCT(DILocation, Record[0],
2041 (Context, Line, Column, Scope, InlinedAt)),
2045 case bitc::METADATA_GENERIC_DEBUG: {
2046 if (Record.size() < 4)
2047 return error("Invalid record");
2049 unsigned Tag = Record[1];
2050 unsigned Version = Record[2];
2052 if (Tag >= 1u << 16 || Version != 0)
2053 return error("Invalid record");
2055 auto *Header = getMDString(Record[3]);
2056 SmallVector<Metadata *, 8> DwarfOps;
2057 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2058 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2060 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2061 (Context, Tag, Header, DwarfOps)),
2065 case bitc::METADATA_SUBRANGE: {
2066 if (Record.size() != 3)
2067 return error("Invalid record");
2069 MDValueList.assignValue(
2070 GET_OR_DISTINCT(DISubrange, Record[0],
2071 (Context, Record[1], unrotateSign(Record[2]))),
2075 case bitc::METADATA_ENUMERATOR: {
2076 if (Record.size() != 3)
2077 return error("Invalid record");
2079 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2080 (Context, unrotateSign(Record[1]),
2081 getMDString(Record[2]))),
2085 case bitc::METADATA_BASIC_TYPE: {
2086 if (Record.size() != 6)
2087 return error("Invalid record");
2089 MDValueList.assignValue(
2090 GET_OR_DISTINCT(DIBasicType, Record[0],
2091 (Context, Record[1], getMDString(Record[2]),
2092 Record[3], Record[4], Record[5])),
2096 case bitc::METADATA_DERIVED_TYPE: {
2097 if (Record.size() != 12)
2098 return error("Invalid record");
2100 MDValueList.assignValue(
2101 GET_OR_DISTINCT(DIDerivedType, Record[0],
2102 (Context, Record[1], getMDString(Record[2]),
2103 getMDOrNull(Record[3]), Record[4],
2104 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2105 Record[7], Record[8], Record[9], Record[10],
2106 getMDOrNull(Record[11]))),
2110 case bitc::METADATA_COMPOSITE_TYPE: {
2111 if (Record.size() != 16)
2112 return error("Invalid record");
2114 MDValueList.assignValue(
2115 GET_OR_DISTINCT(DICompositeType, Record[0],
2116 (Context, Record[1], getMDString(Record[2]),
2117 getMDOrNull(Record[3]), Record[4],
2118 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2119 Record[7], Record[8], Record[9], Record[10],
2120 getMDOrNull(Record[11]), Record[12],
2121 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2122 getMDString(Record[15]))),
2126 case bitc::METADATA_SUBROUTINE_TYPE: {
2127 if (Record.size() != 3)
2128 return error("Invalid record");
2130 MDValueList.assignValue(
2131 GET_OR_DISTINCT(DISubroutineType, Record[0],
2132 (Context, Record[1], getMDOrNull(Record[2]))),
2137 case bitc::METADATA_MODULE: {
2138 if (Record.size() != 6)
2139 return error("Invalid record");
2141 MDValueList.assignValue(
2142 GET_OR_DISTINCT(DIModule, Record[0],
2143 (Context, getMDOrNull(Record[1]),
2144 getMDString(Record[2]), getMDString(Record[3]),
2145 getMDString(Record[4]), getMDString(Record[5]))),
2150 case bitc::METADATA_FILE: {
2151 if (Record.size() != 3)
2152 return error("Invalid record");
2154 MDValueList.assignValue(
2155 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2156 getMDString(Record[2]))),
2160 case bitc::METADATA_COMPILE_UNIT: {
2161 if (Record.size() < 14 || Record.size() > 16)
2162 return error("Invalid record");
2164 // Ignore Record[0], which indicates whether this compile unit is
2165 // distinct. It's always distinct.
2166 MDValueList.assignValue(
2167 DICompileUnit::getDistinct(
2168 Context, Record[1], getMDOrNull(Record[2]),
2169 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2170 Record[6], getMDString(Record[7]), Record[8],
2171 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2172 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2173 getMDOrNull(Record[13]),
2174 Record.size() <= 15 ? 0 : getMDOrNull(Record[15]),
2175 Record.size() <= 14 ? 0 : Record[14]),
2179 case bitc::METADATA_SUBPROGRAM: {
2180 if (Record.size() != 18 && Record.size() != 19)
2181 return error("Invalid record");
2183 bool HasFn = Record.size() == 19;
2184 DISubprogram *SP = GET_OR_DISTINCT(
2186 Record[0] || Record[8], // All definitions should be distinct.
2187 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2188 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2189 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2190 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2191 Record[14], getMDOrNull(Record[15 + HasFn]),
2192 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2193 MDValueList.assignValue(SP, NextMDValueNo++);
2195 // Upgrade sp->function mapping to function->sp mapping.
2196 if (HasFn && Record[15]) {
2197 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2198 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2199 if (F->isMaterializable())
2200 // Defer until materialized; unmaterialized functions may not have
2202 FunctionsWithSPs[F] = SP;
2203 else if (!F->empty())
2204 F->setSubprogram(SP);
2209 case bitc::METADATA_LEXICAL_BLOCK: {
2210 if (Record.size() != 5)
2211 return error("Invalid record");
2213 MDValueList.assignValue(
2214 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2215 (Context, getMDOrNull(Record[1]),
2216 getMDOrNull(Record[2]), Record[3], Record[4])),
2220 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2221 if (Record.size() != 4)
2222 return error("Invalid record");
2224 MDValueList.assignValue(
2225 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2226 (Context, getMDOrNull(Record[1]),
2227 getMDOrNull(Record[2]), Record[3])),
2231 case bitc::METADATA_NAMESPACE: {
2232 if (Record.size() != 5)
2233 return error("Invalid record");
2235 MDValueList.assignValue(
2236 GET_OR_DISTINCT(DINamespace, Record[0],
2237 (Context, getMDOrNull(Record[1]),
2238 getMDOrNull(Record[2]), getMDString(Record[3]),
2243 case bitc::METADATA_MACRO: {
2244 if (Record.size() != 5)
2245 return error("Invalid record");
2247 MDValueList.assignValue(
2248 GET_OR_DISTINCT(DIMacro, Record[0],
2249 (Context, Record[1], Record[2],
2250 getMDString(Record[3]), getMDString(Record[4]))),
2254 case bitc::METADATA_MACRO_FILE: {
2255 if (Record.size() != 5)
2256 return error("Invalid record");
2258 MDValueList.assignValue(
2259 GET_OR_DISTINCT(DIMacroFile, Record[0],
2260 (Context, Record[1], Record[2],
2261 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2265 case bitc::METADATA_TEMPLATE_TYPE: {
2266 if (Record.size() != 3)
2267 return error("Invalid record");
2269 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2271 (Context, getMDString(Record[1]),
2272 getMDOrNull(Record[2]))),
2276 case bitc::METADATA_TEMPLATE_VALUE: {
2277 if (Record.size() != 5)
2278 return error("Invalid record");
2280 MDValueList.assignValue(
2281 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2282 (Context, Record[1], getMDString(Record[2]),
2283 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2287 case bitc::METADATA_GLOBAL_VAR: {
2288 if (Record.size() != 11)
2289 return error("Invalid record");
2291 MDValueList.assignValue(
2292 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2293 (Context, getMDOrNull(Record[1]),
2294 getMDString(Record[2]), getMDString(Record[3]),
2295 getMDOrNull(Record[4]), Record[5],
2296 getMDOrNull(Record[6]), Record[7], Record[8],
2297 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2301 case bitc::METADATA_LOCAL_VAR: {
2302 // 10th field is for the obseleted 'inlinedAt:' field.
2303 if (Record.size() < 8 || Record.size() > 10)
2304 return error("Invalid record");
2306 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2307 // DW_TAG_arg_variable.
2308 bool HasTag = Record.size() > 8;
2309 MDValueList.assignValue(
2310 GET_OR_DISTINCT(DILocalVariable, Record[0],
2311 (Context, getMDOrNull(Record[1 + HasTag]),
2312 getMDString(Record[2 + HasTag]),
2313 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2314 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2315 Record[7 + HasTag])),
2319 case bitc::METADATA_EXPRESSION: {
2320 if (Record.size() < 1)
2321 return error("Invalid record");
2323 MDValueList.assignValue(
2324 GET_OR_DISTINCT(DIExpression, Record[0],
2325 (Context, makeArrayRef(Record).slice(1))),
2329 case bitc::METADATA_OBJC_PROPERTY: {
2330 if (Record.size() != 8)
2331 return error("Invalid record");
2333 MDValueList.assignValue(
2334 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2335 (Context, getMDString(Record[1]),
2336 getMDOrNull(Record[2]), Record[3],
2337 getMDString(Record[4]), getMDString(Record[5]),
2338 Record[6], getMDOrNull(Record[7]))),
2342 case bitc::METADATA_IMPORTED_ENTITY: {
2343 if (Record.size() != 6)
2344 return error("Invalid record");
2346 MDValueList.assignValue(
2347 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2348 (Context, Record[1], getMDOrNull(Record[2]),
2349 getMDOrNull(Record[3]), Record[4],
2350 getMDString(Record[5]))),
2354 case bitc::METADATA_STRING: {
2355 std::string String(Record.begin(), Record.end());
2356 llvm::UpgradeMDStringConstant(String);
2357 Metadata *MD = MDString::get(Context, String);
2358 MDValueList.assignValue(MD, NextMDValueNo++);
2361 case bitc::METADATA_KIND: {
2362 // Support older bitcode files that had METADATA_KIND records in a
2363 // block with METADATA_BLOCK_ID.
2364 if (std::error_code EC = parseMetadataKindRecord(Record))
2370 #undef GET_OR_DISTINCT
2373 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2374 std::error_code BitcodeReader::parseMetadataKinds() {
2375 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2376 return error("Invalid record");
2378 SmallVector<uint64_t, 64> Record;
2380 // Read all the records.
2382 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2384 switch (Entry.Kind) {
2385 case BitstreamEntry::SubBlock: // Handled for us already.
2386 case BitstreamEntry::Error:
2387 return error("Malformed block");
2388 case BitstreamEntry::EndBlock:
2389 return std::error_code();
2390 case BitstreamEntry::Record:
2391 // The interesting case.
2397 unsigned Code = Stream.readRecord(Entry.ID, Record);
2399 default: // Default behavior: ignore.
2401 case bitc::METADATA_KIND: {
2402 if (std::error_code EC = parseMetadataKindRecord(Record))
2410 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2412 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2417 // There is no such thing as -0 with integers. "-0" really means MININT.
2421 /// Resolve all of the initializers for global values and aliases that we can.
2422 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2423 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2424 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2425 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2426 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2427 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2429 GlobalInitWorklist.swap(GlobalInits);
2430 AliasInitWorklist.swap(AliasInits);
2431 FunctionPrefixWorklist.swap(FunctionPrefixes);
2432 FunctionPrologueWorklist.swap(FunctionPrologues);
2433 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2435 while (!GlobalInitWorklist.empty()) {
2436 unsigned ValID = GlobalInitWorklist.back().second;
2437 if (ValID >= ValueList.size()) {
2438 // Not ready to resolve this yet, it requires something later in the file.
2439 GlobalInits.push_back(GlobalInitWorklist.back());
2441 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2442 GlobalInitWorklist.back().first->setInitializer(C);
2444 return error("Expected a constant");
2446 GlobalInitWorklist.pop_back();
2449 while (!AliasInitWorklist.empty()) {
2450 unsigned ValID = AliasInitWorklist.back().second;
2451 if (ValID >= ValueList.size()) {
2452 AliasInits.push_back(AliasInitWorklist.back());
2454 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2456 return error("Expected a constant");
2457 GlobalAlias *Alias = AliasInitWorklist.back().first;
2458 if (C->getType() != Alias->getType())
2459 return error("Alias and aliasee types don't match");
2460 Alias->setAliasee(C);
2462 AliasInitWorklist.pop_back();
2465 while (!FunctionPrefixWorklist.empty()) {
2466 unsigned ValID = FunctionPrefixWorklist.back().second;
2467 if (ValID >= ValueList.size()) {
2468 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2470 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2471 FunctionPrefixWorklist.back().first->setPrefixData(C);
2473 return error("Expected a constant");
2475 FunctionPrefixWorklist.pop_back();
2478 while (!FunctionPrologueWorklist.empty()) {
2479 unsigned ValID = FunctionPrologueWorklist.back().second;
2480 if (ValID >= ValueList.size()) {
2481 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2483 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2484 FunctionPrologueWorklist.back().first->setPrologueData(C);
2486 return error("Expected a constant");
2488 FunctionPrologueWorklist.pop_back();
2491 while (!FunctionPersonalityFnWorklist.empty()) {
2492 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2493 if (ValID >= ValueList.size()) {
2494 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2496 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2497 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2499 return error("Expected a constant");
2501 FunctionPersonalityFnWorklist.pop_back();
2504 return std::error_code();
2507 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2508 SmallVector<uint64_t, 8> Words(Vals.size());
2509 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2510 BitcodeReader::decodeSignRotatedValue);
2512 return APInt(TypeBits, Words);
2515 std::error_code BitcodeReader::parseConstants() {
2516 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2517 return error("Invalid record");
2519 SmallVector<uint64_t, 64> Record;
2521 // Read all the records for this value table.
2522 Type *CurTy = Type::getInt32Ty(Context);
2523 unsigned NextCstNo = ValueList.size();
2525 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2527 switch (Entry.Kind) {
2528 case BitstreamEntry::SubBlock: // Handled for us already.
2529 case BitstreamEntry::Error:
2530 return error("Malformed block");
2531 case BitstreamEntry::EndBlock:
2532 if (NextCstNo != ValueList.size())
2533 return error("Invalid ronstant reference");
2535 // Once all the constants have been read, go through and resolve forward
2537 ValueList.resolveConstantForwardRefs();
2538 return std::error_code();
2539 case BitstreamEntry::Record:
2540 // The interesting case.
2547 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2549 default: // Default behavior: unknown constant
2550 case bitc::CST_CODE_UNDEF: // UNDEF
2551 V = UndefValue::get(CurTy);
2553 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2555 return error("Invalid record");
2556 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2557 return error("Invalid record");
2558 CurTy = TypeList[Record[0]];
2559 continue; // Skip the ValueList manipulation.
2560 case bitc::CST_CODE_NULL: // NULL
2561 V = Constant::getNullValue(CurTy);
2563 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2564 if (!CurTy->isIntegerTy() || Record.empty())
2565 return error("Invalid record");
2566 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2568 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2569 if (!CurTy->isIntegerTy() || Record.empty())
2570 return error("Invalid record");
2573 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2574 V = ConstantInt::get(Context, VInt);
2578 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2580 return error("Invalid record");
2581 if (CurTy->isHalfTy())
2582 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2583 APInt(16, (uint16_t)Record[0])));
2584 else if (CurTy->isFloatTy())
2585 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2586 APInt(32, (uint32_t)Record[0])));
2587 else if (CurTy->isDoubleTy())
2588 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2589 APInt(64, Record[0])));
2590 else if (CurTy->isX86_FP80Ty()) {
2591 // Bits are not stored the same way as a normal i80 APInt, compensate.
2592 uint64_t Rearrange[2];
2593 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2594 Rearrange[1] = Record[0] >> 48;
2595 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2596 APInt(80, Rearrange)));
2597 } else if (CurTy->isFP128Ty())
2598 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2599 APInt(128, Record)));
2600 else if (CurTy->isPPC_FP128Ty())
2601 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2602 APInt(128, Record)));
2604 V = UndefValue::get(CurTy);
2608 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2610 return error("Invalid record");
2612 unsigned Size = Record.size();
2613 SmallVector<Constant*, 16> Elts;
2615 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2616 for (unsigned i = 0; i != Size; ++i)
2617 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2618 STy->getElementType(i)));
2619 V = ConstantStruct::get(STy, Elts);
2620 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2621 Type *EltTy = ATy->getElementType();
2622 for (unsigned i = 0; i != Size; ++i)
2623 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2624 V = ConstantArray::get(ATy, Elts);
2625 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2626 Type *EltTy = VTy->getElementType();
2627 for (unsigned i = 0; i != Size; ++i)
2628 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2629 V = ConstantVector::get(Elts);
2631 V = UndefValue::get(CurTy);
2635 case bitc::CST_CODE_STRING: // STRING: [values]
2636 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2638 return error("Invalid record");
2640 SmallString<16> Elts(Record.begin(), Record.end());
2641 V = ConstantDataArray::getString(Context, Elts,
2642 BitCode == bitc::CST_CODE_CSTRING);
2645 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2647 return error("Invalid record");
2649 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2650 unsigned Size = Record.size();
2652 if (EltTy->isIntegerTy(8)) {
2653 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2654 if (isa<VectorType>(CurTy))
2655 V = ConstantDataVector::get(Context, Elts);
2657 V = ConstantDataArray::get(Context, Elts);
2658 } else if (EltTy->isIntegerTy(16)) {
2659 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2660 if (isa<VectorType>(CurTy))
2661 V = ConstantDataVector::get(Context, Elts);
2663 V = ConstantDataArray::get(Context, Elts);
2664 } else if (EltTy->isIntegerTy(32)) {
2665 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2666 if (isa<VectorType>(CurTy))
2667 V = ConstantDataVector::get(Context, Elts);
2669 V = ConstantDataArray::get(Context, Elts);
2670 } else if (EltTy->isIntegerTy(64)) {
2671 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2672 if (isa<VectorType>(CurTy))
2673 V = ConstantDataVector::get(Context, Elts);
2675 V = ConstantDataArray::get(Context, Elts);
2676 } else if (EltTy->isFloatTy()) {
2677 SmallVector<float, 16> Elts(Size);
2678 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2679 if (isa<VectorType>(CurTy))
2680 V = ConstantDataVector::get(Context, Elts);
2682 V = ConstantDataArray::get(Context, Elts);
2683 } else if (EltTy->isDoubleTy()) {
2684 SmallVector<double, 16> Elts(Size);
2685 std::transform(Record.begin(), Record.end(), Elts.begin(),
2687 if (isa<VectorType>(CurTy))
2688 V = ConstantDataVector::get(Context, Elts);
2690 V = ConstantDataArray::get(Context, Elts);
2692 return error("Invalid type for value");
2697 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2698 if (Record.size() < 3)
2699 return error("Invalid record");
2700 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2702 V = UndefValue::get(CurTy); // Unknown binop.
2704 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2705 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2707 if (Record.size() >= 4) {
2708 if (Opc == Instruction::Add ||
2709 Opc == Instruction::Sub ||
2710 Opc == Instruction::Mul ||
2711 Opc == Instruction::Shl) {
2712 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2713 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2714 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2715 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2716 } else if (Opc == Instruction::SDiv ||
2717 Opc == Instruction::UDiv ||
2718 Opc == Instruction::LShr ||
2719 Opc == Instruction::AShr) {
2720 if (Record[3] & (1 << bitc::PEO_EXACT))
2721 Flags |= SDivOperator::IsExact;
2724 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2728 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2729 if (Record.size() < 3)
2730 return error("Invalid record");
2731 int Opc = getDecodedCastOpcode(Record[0]);
2733 V = UndefValue::get(CurTy); // Unknown cast.
2735 Type *OpTy = getTypeByID(Record[1]);
2737 return error("Invalid record");
2738 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2739 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2740 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2744 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2745 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2747 Type *PointeeType = nullptr;
2748 if (Record.size() % 2)
2749 PointeeType = getTypeByID(Record[OpNum++]);
2750 SmallVector<Constant*, 16> Elts;
2751 while (OpNum != Record.size()) {
2752 Type *ElTy = getTypeByID(Record[OpNum++]);
2754 return error("Invalid record");
2755 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2760 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2762 return error("Explicit gep operator type does not match pointee type "
2763 "of pointer operand");
2765 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2766 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2768 bitc::CST_CODE_CE_INBOUNDS_GEP);
2771 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2772 if (Record.size() < 3)
2773 return error("Invalid record");
2775 Type *SelectorTy = Type::getInt1Ty(Context);
2777 // The selector might be an i1 or an <n x i1>
2778 // Get the type from the ValueList before getting a forward ref.
2779 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2780 if (Value *V = ValueList[Record[0]])
2781 if (SelectorTy != V->getType())
2782 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2784 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2786 ValueList.getConstantFwdRef(Record[1],CurTy),
2787 ValueList.getConstantFwdRef(Record[2],CurTy));
2790 case bitc::CST_CODE_CE_EXTRACTELT
2791 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2792 if (Record.size() < 3)
2793 return error("Invalid record");
2795 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2797 return error("Invalid record");
2798 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2799 Constant *Op1 = nullptr;
2800 if (Record.size() == 4) {
2801 Type *IdxTy = getTypeByID(Record[2]);
2803 return error("Invalid record");
2804 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2805 } else // TODO: Remove with llvm 4.0
2806 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2808 return error("Invalid record");
2809 V = ConstantExpr::getExtractElement(Op0, Op1);
2812 case bitc::CST_CODE_CE_INSERTELT
2813 : { // CE_INSERTELT: [opval, opval, opty, opval]
2814 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2815 if (Record.size() < 3 || !OpTy)
2816 return error("Invalid record");
2817 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2818 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2819 OpTy->getElementType());
2820 Constant *Op2 = nullptr;
2821 if (Record.size() == 4) {
2822 Type *IdxTy = getTypeByID(Record[2]);
2824 return error("Invalid record");
2825 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2826 } else // TODO: Remove with llvm 4.0
2827 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2829 return error("Invalid record");
2830 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2833 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2834 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2835 if (Record.size() < 3 || !OpTy)
2836 return error("Invalid record");
2837 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2838 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2839 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2840 OpTy->getNumElements());
2841 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2842 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2845 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2846 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2848 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2849 if (Record.size() < 4 || !RTy || !OpTy)
2850 return error("Invalid record");
2851 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2852 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2853 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2854 RTy->getNumElements());
2855 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2856 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2859 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2860 if (Record.size() < 4)
2861 return error("Invalid record");
2862 Type *OpTy = getTypeByID(Record[0]);
2864 return error("Invalid record");
2865 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2866 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2868 if (OpTy->isFPOrFPVectorTy())
2869 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2871 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2874 // This maintains backward compatibility, pre-asm dialect keywords.
2875 // FIXME: Remove with the 4.0 release.
2876 case bitc::CST_CODE_INLINEASM_OLD: {
2877 if (Record.size() < 2)
2878 return error("Invalid record");
2879 std::string AsmStr, ConstrStr;
2880 bool HasSideEffects = Record[0] & 1;
2881 bool IsAlignStack = Record[0] >> 1;
2882 unsigned AsmStrSize = Record[1];
2883 if (2+AsmStrSize >= Record.size())
2884 return error("Invalid record");
2885 unsigned ConstStrSize = Record[2+AsmStrSize];
2886 if (3+AsmStrSize+ConstStrSize > Record.size())
2887 return error("Invalid record");
2889 for (unsigned i = 0; i != AsmStrSize; ++i)
2890 AsmStr += (char)Record[2+i];
2891 for (unsigned i = 0; i != ConstStrSize; ++i)
2892 ConstrStr += (char)Record[3+AsmStrSize+i];
2893 PointerType *PTy = cast<PointerType>(CurTy);
2894 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2895 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2898 // This version adds support for the asm dialect keywords (e.g.,
2900 case bitc::CST_CODE_INLINEASM: {
2901 if (Record.size() < 2)
2902 return error("Invalid record");
2903 std::string AsmStr, ConstrStr;
2904 bool HasSideEffects = Record[0] & 1;
2905 bool IsAlignStack = (Record[0] >> 1) & 1;
2906 unsigned AsmDialect = Record[0] >> 2;
2907 unsigned AsmStrSize = Record[1];
2908 if (2+AsmStrSize >= Record.size())
2909 return error("Invalid record");
2910 unsigned ConstStrSize = Record[2+AsmStrSize];
2911 if (3+AsmStrSize+ConstStrSize > Record.size())
2912 return error("Invalid record");
2914 for (unsigned i = 0; i != AsmStrSize; ++i)
2915 AsmStr += (char)Record[2+i];
2916 for (unsigned i = 0; i != ConstStrSize; ++i)
2917 ConstrStr += (char)Record[3+AsmStrSize+i];
2918 PointerType *PTy = cast<PointerType>(CurTy);
2919 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2920 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2921 InlineAsm::AsmDialect(AsmDialect));
2924 case bitc::CST_CODE_BLOCKADDRESS:{
2925 if (Record.size() < 3)
2926 return error("Invalid record");
2927 Type *FnTy = getTypeByID(Record[0]);
2929 return error("Invalid record");
2931 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2933 return error("Invalid record");
2935 // Don't let Fn get dematerialized.
2936 BlockAddressesTaken.insert(Fn);
2938 // If the function is already parsed we can insert the block address right
2941 unsigned BBID = Record[2];
2943 // Invalid reference to entry block.
2944 return error("Invalid ID");
2946 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2947 for (size_t I = 0, E = BBID; I != E; ++I) {
2949 return error("Invalid ID");
2954 // Otherwise insert a placeholder and remember it so it can be inserted
2955 // when the function is parsed.
2956 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2958 BasicBlockFwdRefQueue.push_back(Fn);
2959 if (FwdBBs.size() < BBID + 1)
2960 FwdBBs.resize(BBID + 1);
2962 FwdBBs[BBID] = BasicBlock::Create(Context);
2965 V = BlockAddress::get(Fn, BB);
2970 ValueList.assignValue(V, NextCstNo);
2975 std::error_code BitcodeReader::parseUseLists() {
2976 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2977 return error("Invalid record");
2979 // Read all the records.
2980 SmallVector<uint64_t, 64> Record;
2982 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2984 switch (Entry.Kind) {
2985 case BitstreamEntry::SubBlock: // Handled for us already.
2986 case BitstreamEntry::Error:
2987 return error("Malformed block");
2988 case BitstreamEntry::EndBlock:
2989 return std::error_code();
2990 case BitstreamEntry::Record:
2991 // The interesting case.
2995 // Read a use list record.
2998 switch (Stream.readRecord(Entry.ID, Record)) {
2999 default: // Default behavior: unknown type.
3001 case bitc::USELIST_CODE_BB:
3004 case bitc::USELIST_CODE_DEFAULT: {
3005 unsigned RecordLength = Record.size();
3006 if (RecordLength < 3)
3007 // Records should have at least an ID and two indexes.
3008 return error("Invalid record");
3009 unsigned ID = Record.back();
3014 assert(ID < FunctionBBs.size() && "Basic block not found");
3015 V = FunctionBBs[ID];
3018 unsigned NumUses = 0;
3019 SmallDenseMap<const Use *, unsigned, 16> Order;
3020 for (const Use &U : V->uses()) {
3021 if (++NumUses > Record.size())
3023 Order[&U] = Record[NumUses - 1];
3025 if (Order.size() != Record.size() || NumUses > Record.size())
3026 // Mismatches can happen if the functions are being materialized lazily
3027 // (out-of-order), or a value has been upgraded.
3030 V->sortUseList([&](const Use &L, const Use &R) {
3031 return Order.lookup(&L) < Order.lookup(&R);
3039 /// When we see the block for metadata, remember where it is and then skip it.
3040 /// This lets us lazily deserialize the metadata.
3041 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3042 // Save the current stream state.
3043 uint64_t CurBit = Stream.GetCurrentBitNo();
3044 DeferredMetadataInfo.push_back(CurBit);
3046 // Skip over the block for now.
3047 if (Stream.SkipBlock())
3048 return error("Invalid record");
3049 return std::error_code();
3052 std::error_code BitcodeReader::materializeMetadata() {
3053 for (uint64_t BitPos : DeferredMetadataInfo) {
3054 // Move the bit stream to the saved position.
3055 Stream.JumpToBit(BitPos);
3056 if (std::error_code EC = parseMetadata(true))
3059 DeferredMetadataInfo.clear();
3060 return std::error_code();
3063 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3065 /// When we see the block for a function body, remember where it is and then
3066 /// skip it. This lets us lazily deserialize the functions.
3067 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3068 // Get the function we are talking about.
3069 if (FunctionsWithBodies.empty())
3070 return error("Insufficient function protos");
3072 Function *Fn = FunctionsWithBodies.back();
3073 FunctionsWithBodies.pop_back();
3075 // Save the current stream state.
3076 uint64_t CurBit = Stream.GetCurrentBitNo();
3078 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3079 "Mismatch between VST and scanned function offsets");
3080 DeferredFunctionInfo[Fn] = CurBit;
3082 // Skip over the function block for now.
3083 if (Stream.SkipBlock())
3084 return error("Invalid record");
3085 return std::error_code();
3088 std::error_code BitcodeReader::globalCleanup() {
3089 // Patch the initializers for globals and aliases up.
3090 resolveGlobalAndAliasInits();
3091 if (!GlobalInits.empty() || !AliasInits.empty())
3092 return error("Malformed global initializer set");
3094 // Look for intrinsic functions which need to be upgraded at some point
3095 for (Function &F : *TheModule) {
3097 if (UpgradeIntrinsicFunction(&F, NewFn))
3098 UpgradedIntrinsics[&F] = NewFn;
3101 // Look for global variables which need to be renamed.
3102 for (GlobalVariable &GV : TheModule->globals())
3103 UpgradeGlobalVariable(&GV);
3105 // Force deallocation of memory for these vectors to favor the client that
3106 // want lazy deserialization.
3107 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3108 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3109 return std::error_code();
3112 /// Support for lazy parsing of function bodies. This is required if we
3113 /// either have an old bitcode file without a VST forward declaration record,
3114 /// or if we have an anonymous function being materialized, since anonymous
3115 /// functions do not have a name and are therefore not in the VST.
3116 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3117 Stream.JumpToBit(NextUnreadBit);
3119 if (Stream.AtEndOfStream())
3120 return error("Could not find function in stream");
3122 if (!SeenFirstFunctionBody)
3123 return error("Trying to materialize functions before seeing function blocks");
3125 // An old bitcode file with the symbol table at the end would have
3126 // finished the parse greedily.
3127 assert(SeenValueSymbolTable);
3129 SmallVector<uint64_t, 64> Record;
3132 BitstreamEntry Entry = Stream.advance();
3133 switch (Entry.Kind) {
3135 return error("Expect SubBlock");
3136 case BitstreamEntry::SubBlock:
3139 return error("Expect function block");
3140 case bitc::FUNCTION_BLOCK_ID:
3141 if (std::error_code EC = rememberAndSkipFunctionBody())
3143 NextUnreadBit = Stream.GetCurrentBitNo();
3144 return std::error_code();
3150 std::error_code BitcodeReader::parseBitcodeVersion() {
3151 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3152 return error("Invalid record");
3154 // Read all the records.
3155 SmallVector<uint64_t, 64> Record;
3157 BitstreamEntry Entry = Stream.advance();
3159 switch (Entry.Kind) {
3161 case BitstreamEntry::Error:
3162 return error("Malformed block");
3163 case BitstreamEntry::EndBlock:
3164 return std::error_code();
3165 case BitstreamEntry::Record:
3166 // The interesting case.
3172 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3174 default: // Default behavior: reject
3175 return error("Invalid value");
3176 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3178 convertToString(Record, 0, ProducerIdentification);
3181 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3182 unsigned epoch = (unsigned)Record[0];
3183 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3185 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3186 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3193 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3194 bool ShouldLazyLoadMetadata) {
3196 Stream.JumpToBit(ResumeBit);
3197 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3198 return error("Invalid record");
3200 SmallVector<uint64_t, 64> Record;
3201 std::vector<std::string> SectionTable;
3202 std::vector<std::string> GCTable;
3204 // Read all the records for this module.
3206 BitstreamEntry Entry = Stream.advance();
3208 switch (Entry.Kind) {
3209 case BitstreamEntry::Error:
3210 return error("Malformed block");
3211 case BitstreamEntry::EndBlock:
3212 return globalCleanup();
3214 case BitstreamEntry::SubBlock:
3216 default: // Skip unknown content.
3217 if (Stream.SkipBlock())
3218 return error("Invalid record");
3220 case bitc::BLOCKINFO_BLOCK_ID:
3221 if (Stream.ReadBlockInfoBlock())
3222 return error("Malformed block");
3224 case bitc::PARAMATTR_BLOCK_ID:
3225 if (std::error_code EC = parseAttributeBlock())
3228 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3229 if (std::error_code EC = parseAttributeGroupBlock())
3232 case bitc::TYPE_BLOCK_ID_NEW:
3233 if (std::error_code EC = parseTypeTable())
3236 case bitc::VALUE_SYMTAB_BLOCK_ID:
3237 if (!SeenValueSymbolTable) {
3238 // Either this is an old form VST without function index and an
3239 // associated VST forward declaration record (which would have caused
3240 // the VST to be jumped to and parsed before it was encountered
3241 // normally in the stream), or there were no function blocks to
3242 // trigger an earlier parsing of the VST.
3243 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3244 if (std::error_code EC = parseValueSymbolTable())
3246 SeenValueSymbolTable = true;
3248 // We must have had a VST forward declaration record, which caused
3249 // the parser to jump to and parse the VST earlier.
3250 assert(VSTOffset > 0);
3251 if (Stream.SkipBlock())
3252 return error("Invalid record");
3255 case bitc::CONSTANTS_BLOCK_ID:
3256 if (std::error_code EC = parseConstants())
3258 if (std::error_code EC = resolveGlobalAndAliasInits())
3261 case bitc::METADATA_BLOCK_ID:
3262 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3263 if (std::error_code EC = rememberAndSkipMetadata())
3267 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3268 if (std::error_code EC = parseMetadata(true))
3271 case bitc::METADATA_KIND_BLOCK_ID:
3272 if (std::error_code EC = parseMetadataKinds())
3275 case bitc::FUNCTION_BLOCK_ID:
3276 // If this is the first function body we've seen, reverse the
3277 // FunctionsWithBodies list.
3278 if (!SeenFirstFunctionBody) {
3279 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3280 if (std::error_code EC = globalCleanup())
3282 SeenFirstFunctionBody = true;
3285 if (VSTOffset > 0) {
3286 // If we have a VST forward declaration record, make sure we
3287 // parse the VST now if we haven't already. It is needed to
3288 // set up the DeferredFunctionInfo vector for lazy reading.
3289 if (!SeenValueSymbolTable) {
3290 if (std::error_code EC =
3291 BitcodeReader::parseValueSymbolTable(VSTOffset))
3293 SeenValueSymbolTable = true;
3294 // Fall through so that we record the NextUnreadBit below.
3295 // This is necessary in case we have an anonymous function that
3296 // is later materialized. Since it will not have a VST entry we
3297 // need to fall back to the lazy parse to find its offset.
3299 // If we have a VST forward declaration record, but have already
3300 // parsed the VST (just above, when the first function body was
3301 // encountered here), then we are resuming the parse after
3302 // materializing functions. The ResumeBit points to the
3303 // start of the last function block recorded in the
3304 // DeferredFunctionInfo map. Skip it.
3305 if (Stream.SkipBlock())
3306 return error("Invalid record");
3311 // Support older bitcode files that did not have the function
3312 // index in the VST, nor a VST forward declaration record, as
3313 // well as anonymous functions that do not have VST entries.
3314 // Build the DeferredFunctionInfo vector on the fly.
3315 if (std::error_code EC = rememberAndSkipFunctionBody())
3318 // Suspend parsing when we reach the function bodies. Subsequent
3319 // materialization calls will resume it when necessary. If the bitcode
3320 // file is old, the symbol table will be at the end instead and will not
3321 // have been seen yet. In this case, just finish the parse now.
3322 if (SeenValueSymbolTable) {
3323 NextUnreadBit = Stream.GetCurrentBitNo();
3324 return std::error_code();
3327 case bitc::USELIST_BLOCK_ID:
3328 if (std::error_code EC = parseUseLists())
3331 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3332 if (std::error_code EC = parseOperandBundleTags())
3338 case BitstreamEntry::Record:
3339 // The interesting case.
3345 auto BitCode = Stream.readRecord(Entry.ID, Record);
3347 default: break; // Default behavior, ignore unknown content.
3348 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3349 if (Record.size() < 1)
3350 return error("Invalid record");
3351 // Only version #0 and #1 are supported so far.
3352 unsigned module_version = Record[0];
3353 switch (module_version) {
3355 return error("Invalid value");
3357 UseRelativeIDs = false;
3360 UseRelativeIDs = true;
3365 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3367 if (convertToString(Record, 0, S))
3368 return error("Invalid record");
3369 TheModule->setTargetTriple(S);
3372 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3374 if (convertToString(Record, 0, S))
3375 return error("Invalid record");
3376 TheModule->setDataLayout(S);
3379 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3381 if (convertToString(Record, 0, S))
3382 return error("Invalid record");
3383 TheModule->setModuleInlineAsm(S);
3386 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3387 // FIXME: Remove in 4.0.
3389 if (convertToString(Record, 0, S))
3390 return error("Invalid record");
3394 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3396 if (convertToString(Record, 0, S))
3397 return error("Invalid record");
3398 SectionTable.push_back(S);
3401 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3403 if (convertToString(Record, 0, S))
3404 return error("Invalid record");
3405 GCTable.push_back(S);
3408 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3409 if (Record.size() < 2)
3410 return error("Invalid record");
3411 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3412 unsigned ComdatNameSize = Record[1];
3413 std::string ComdatName;
3414 ComdatName.reserve(ComdatNameSize);
3415 for (unsigned i = 0; i != ComdatNameSize; ++i)
3416 ComdatName += (char)Record[2 + i];
3417 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3418 C->setSelectionKind(SK);
3419 ComdatList.push_back(C);
3422 // GLOBALVAR: [pointer type, isconst, initid,
3423 // linkage, alignment, section, visibility, threadlocal,
3424 // unnamed_addr, externally_initialized, dllstorageclass,
3426 case bitc::MODULE_CODE_GLOBALVAR: {
3427 if (Record.size() < 6)
3428 return error("Invalid record");
3429 Type *Ty = getTypeByID(Record[0]);
3431 return error("Invalid record");
3432 bool isConstant = Record[1] & 1;
3433 bool explicitType = Record[1] & 2;
3434 unsigned AddressSpace;
3436 AddressSpace = Record[1] >> 2;
3438 if (!Ty->isPointerTy())
3439 return error("Invalid type for value");
3440 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3441 Ty = cast<PointerType>(Ty)->getElementType();
3444 uint64_t RawLinkage = Record[3];
3445 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3447 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3449 std::string Section;
3451 if (Record[5]-1 >= SectionTable.size())
3452 return error("Invalid ID");
3453 Section = SectionTable[Record[5]-1];
3455 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3456 // Local linkage must have default visibility.
3457 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3458 // FIXME: Change to an error if non-default in 4.0.
3459 Visibility = getDecodedVisibility(Record[6]);
3461 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3462 if (Record.size() > 7)
3463 TLM = getDecodedThreadLocalMode(Record[7]);
3465 bool UnnamedAddr = false;
3466 if (Record.size() > 8)
3467 UnnamedAddr = Record[8];
3469 bool ExternallyInitialized = false;
3470 if (Record.size() > 9)
3471 ExternallyInitialized = Record[9];
3473 GlobalVariable *NewGV =
3474 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3475 TLM, AddressSpace, ExternallyInitialized);
3476 NewGV->setAlignment(Alignment);
3477 if (!Section.empty())
3478 NewGV->setSection(Section);
3479 NewGV->setVisibility(Visibility);
3480 NewGV->setUnnamedAddr(UnnamedAddr);
3482 if (Record.size() > 10)
3483 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3485 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3487 ValueList.push_back(NewGV);
3489 // Remember which value to use for the global initializer.
3490 if (unsigned InitID = Record[2])
3491 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3493 if (Record.size() > 11) {
3494 if (unsigned ComdatID = Record[11]) {
3495 if (ComdatID > ComdatList.size())
3496 return error("Invalid global variable comdat ID");
3497 NewGV->setComdat(ComdatList[ComdatID - 1]);
3499 } else if (hasImplicitComdat(RawLinkage)) {
3500 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3504 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3505 // alignment, section, visibility, gc, unnamed_addr,
3506 // prologuedata, dllstorageclass, comdat, prefixdata]
3507 case bitc::MODULE_CODE_FUNCTION: {
3508 if (Record.size() < 8)
3509 return error("Invalid record");
3510 Type *Ty = getTypeByID(Record[0]);
3512 return error("Invalid record");
3513 if (auto *PTy = dyn_cast<PointerType>(Ty))
3514 Ty = PTy->getElementType();
3515 auto *FTy = dyn_cast<FunctionType>(Ty);
3517 return error("Invalid type for value");
3518 auto CC = static_cast<CallingConv::ID>(Record[1]);
3519 if (CC & ~CallingConv::MaxID)
3520 return error("Invalid calling convention ID");
3522 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3525 Func->setCallingConv(CC);
3526 bool isProto = Record[2];
3527 uint64_t RawLinkage = Record[3];
3528 Func->setLinkage(getDecodedLinkage(RawLinkage));
3529 Func->setAttributes(getAttributes(Record[4]));
3532 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3534 Func->setAlignment(Alignment);
3536 if (Record[6]-1 >= SectionTable.size())
3537 return error("Invalid ID");
3538 Func->setSection(SectionTable[Record[6]-1]);
3540 // Local linkage must have default visibility.
3541 if (!Func->hasLocalLinkage())
3542 // FIXME: Change to an error if non-default in 4.0.
3543 Func->setVisibility(getDecodedVisibility(Record[7]));
3544 if (Record.size() > 8 && Record[8]) {
3545 if (Record[8]-1 >= GCTable.size())
3546 return error("Invalid ID");
3547 Func->setGC(GCTable[Record[8]-1].c_str());
3549 bool UnnamedAddr = false;
3550 if (Record.size() > 9)
3551 UnnamedAddr = Record[9];
3552 Func->setUnnamedAddr(UnnamedAddr);
3553 if (Record.size() > 10 && Record[10] != 0)
3554 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3556 if (Record.size() > 11)
3557 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3559 upgradeDLLImportExportLinkage(Func, RawLinkage);
3561 if (Record.size() > 12) {
3562 if (unsigned ComdatID = Record[12]) {
3563 if (ComdatID > ComdatList.size())
3564 return error("Invalid function comdat ID");
3565 Func->setComdat(ComdatList[ComdatID - 1]);
3567 } else if (hasImplicitComdat(RawLinkage)) {
3568 Func->setComdat(reinterpret_cast<Comdat *>(1));
3571 if (Record.size() > 13 && Record[13] != 0)
3572 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3574 if (Record.size() > 14 && Record[14] != 0)
3575 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3577 ValueList.push_back(Func);
3579 // If this is a function with a body, remember the prototype we are
3580 // creating now, so that we can match up the body with them later.
3582 Func->setIsMaterializable(true);
3583 FunctionsWithBodies.push_back(Func);
3584 DeferredFunctionInfo[Func] = 0;
3588 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3589 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3590 case bitc::MODULE_CODE_ALIAS:
3591 case bitc::MODULE_CODE_ALIAS_OLD: {
3592 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3593 if (Record.size() < (3 + (unsigned)NewRecord))
3594 return error("Invalid record");
3596 Type *Ty = getTypeByID(Record[OpNum++]);
3598 return error("Invalid record");
3602 auto *PTy = dyn_cast<PointerType>(Ty);
3604 return error("Invalid type for value");
3605 Ty = PTy->getElementType();
3606 AddrSpace = PTy->getAddressSpace();
3608 AddrSpace = Record[OpNum++];
3611 auto Val = Record[OpNum++];
3612 auto Linkage = Record[OpNum++];
3613 auto *NewGA = GlobalAlias::create(
3614 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3615 // Old bitcode files didn't have visibility field.
3616 // Local linkage must have default visibility.
3617 if (OpNum != Record.size()) {
3618 auto VisInd = OpNum++;
3619 if (!NewGA->hasLocalLinkage())
3620 // FIXME: Change to an error if non-default in 4.0.
3621 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3623 if (OpNum != Record.size())
3624 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3626 upgradeDLLImportExportLinkage(NewGA, Linkage);
3627 if (OpNum != Record.size())
3628 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3629 if (OpNum != Record.size())
3630 NewGA->setUnnamedAddr(Record[OpNum++]);
3631 ValueList.push_back(NewGA);
3632 AliasInits.push_back(std::make_pair(NewGA, Val));
3635 /// MODULE_CODE_PURGEVALS: [numvals]
3636 case bitc::MODULE_CODE_PURGEVALS:
3637 // Trim down the value list to the specified size.
3638 if (Record.size() < 1 || Record[0] > ValueList.size())
3639 return error("Invalid record");
3640 ValueList.shrinkTo(Record[0]);
3642 /// MODULE_CODE_VSTOFFSET: [offset]
3643 case bitc::MODULE_CODE_VSTOFFSET:
3644 if (Record.size() < 1)
3645 return error("Invalid record");
3646 VSTOffset = Record[0];
3648 /// MODULE_CODE_METADATA_VALUES: [numvals]
3649 case bitc::MODULE_CODE_METADATA_VALUES:
3650 if (Record.size() < 1)
3651 return error("Invalid record");
3652 assert(!IsMetadataMaterialized);
3653 // This record contains the number of metadata values in the module-level
3654 // METADATA_BLOCK. It is used to support lazy parsing of metadata as
3655 // a postpass, where we will parse function-level metadata first.
3656 // This is needed because the ids of metadata are assigned implicitly
3657 // based on their ordering in the bitcode, with the function-level
3658 // metadata ids starting after the module-level metadata ids. Otherwise,
3659 // we would have to parse the module-level metadata block to prime the
3660 // MDValueList when we are lazy loading metadata during function
3661 // importing. Initialize the MDValueList size here based on the
3662 // record value, regardless of whether we are doing lazy metadata
3663 // loading, so that we have consistent handling and assertion
3664 // checking in parseMetadata for module-level metadata.
3665 NumModuleMDs = Record[0];
3666 SeenModuleValuesRecord = true;
3667 assert(MDValueList.size() == 0);
3668 MDValueList.resize(NumModuleMDs);
3675 /// Helper to read the header common to all bitcode files.
3676 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3677 // Sniff for the signature.
3678 if (Stream.Read(8) != 'B' ||
3679 Stream.Read(8) != 'C' ||
3680 Stream.Read(4) != 0x0 ||
3681 Stream.Read(4) != 0xC ||
3682 Stream.Read(4) != 0xE ||
3683 Stream.Read(4) != 0xD)
3689 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3690 Module *M, bool ShouldLazyLoadMetadata) {
3693 if (std::error_code EC = initStream(std::move(Streamer)))
3696 // Sniff for the signature.
3697 if (!hasValidBitcodeHeader(Stream))
3698 return error("Invalid bitcode signature");
3700 // We expect a number of well-defined blocks, though we don't necessarily
3701 // need to understand them all.
3703 if (Stream.AtEndOfStream()) {
3704 // We didn't really read a proper Module.
3705 return error("Malformed IR file");
3708 BitstreamEntry Entry =
3709 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3711 if (Entry.Kind != BitstreamEntry::SubBlock)
3712 return error("Malformed block");
3714 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3715 parseBitcodeVersion();
3719 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3720 return parseModule(0, ShouldLazyLoadMetadata);
3722 if (Stream.SkipBlock())
3723 return error("Invalid record");
3727 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3728 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3729 return error("Invalid record");
3731 SmallVector<uint64_t, 64> Record;
3734 // Read all the records for this module.
3736 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3738 switch (Entry.Kind) {
3739 case BitstreamEntry::SubBlock: // Handled for us already.
3740 case BitstreamEntry::Error:
3741 return error("Malformed block");
3742 case BitstreamEntry::EndBlock:
3744 case BitstreamEntry::Record:
3745 // The interesting case.
3750 switch (Stream.readRecord(Entry.ID, Record)) {
3751 default: break; // Default behavior, ignore unknown content.
3752 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3754 if (convertToString(Record, 0, S))
3755 return error("Invalid record");
3762 llvm_unreachable("Exit infinite loop");
3765 ErrorOr<std::string> BitcodeReader::parseTriple() {
3766 if (std::error_code EC = initStream(nullptr))
3769 // Sniff for the signature.
3770 if (!hasValidBitcodeHeader(Stream))
3771 return error("Invalid bitcode signature");
3773 // We expect a number of well-defined blocks, though we don't necessarily
3774 // need to understand them all.
3776 BitstreamEntry Entry = Stream.advance();
3778 switch (Entry.Kind) {
3779 case BitstreamEntry::Error:
3780 return error("Malformed block");
3781 case BitstreamEntry::EndBlock:
3782 return std::error_code();
3784 case BitstreamEntry::SubBlock:
3785 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3786 return parseModuleTriple();
3788 // Ignore other sub-blocks.
3789 if (Stream.SkipBlock())
3790 return error("Malformed block");
3793 case BitstreamEntry::Record:
3794 Stream.skipRecord(Entry.ID);
3800 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3801 if (std::error_code EC = initStream(nullptr))
3804 // Sniff for the signature.
3805 if (!hasValidBitcodeHeader(Stream))
3806 return error("Invalid bitcode signature");
3808 // We expect a number of well-defined blocks, though we don't necessarily
3809 // need to understand them all.
3811 BitstreamEntry Entry = Stream.advance();
3812 switch (Entry.Kind) {
3813 case BitstreamEntry::Error:
3814 return error("Malformed block");
3815 case BitstreamEntry::EndBlock:
3816 return std::error_code();
3818 case BitstreamEntry::SubBlock:
3819 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3820 if (std::error_code EC = parseBitcodeVersion())
3822 return ProducerIdentification;
3824 // Ignore other sub-blocks.
3825 if (Stream.SkipBlock())
3826 return error("Malformed block");
3828 case BitstreamEntry::Record:
3829 Stream.skipRecord(Entry.ID);
3835 /// Parse metadata attachments.
3836 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3837 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3838 return error("Invalid record");
3840 SmallVector<uint64_t, 64> Record;
3842 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3844 switch (Entry.Kind) {
3845 case BitstreamEntry::SubBlock: // Handled for us already.
3846 case BitstreamEntry::Error:
3847 return error("Malformed block");
3848 case BitstreamEntry::EndBlock:
3849 return std::error_code();
3850 case BitstreamEntry::Record:
3851 // The interesting case.
3855 // Read a metadata attachment record.
3857 switch (Stream.readRecord(Entry.ID, Record)) {
3858 default: // Default behavior: ignore.
3860 case bitc::METADATA_ATTACHMENT: {
3861 unsigned RecordLength = Record.size();
3863 return error("Invalid record");
3864 if (RecordLength % 2 == 0) {
3865 // A function attachment.
3866 for (unsigned I = 0; I != RecordLength; I += 2) {
3867 auto K = MDKindMap.find(Record[I]);
3868 if (K == MDKindMap.end())
3869 return error("Invalid ID");
3870 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3871 F.setMetadata(K->second, cast<MDNode>(MD));
3876 // An instruction attachment.
3877 Instruction *Inst = InstructionList[Record[0]];
3878 for (unsigned i = 1; i != RecordLength; i = i+2) {
3879 unsigned Kind = Record[i];
3880 DenseMap<unsigned, unsigned>::iterator I =
3881 MDKindMap.find(Kind);
3882 if (I == MDKindMap.end())
3883 return error("Invalid ID");
3884 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3885 if (isa<LocalAsMetadata>(Node))
3886 // Drop the attachment. This used to be legal, but there's no
3889 Inst->setMetadata(I->second, cast<MDNode>(Node));
3890 if (I->second == LLVMContext::MD_tbaa)
3891 InstsWithTBAATag.push_back(Inst);
3899 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3900 LLVMContext &Context = PtrType->getContext();
3901 if (!isa<PointerType>(PtrType))
3902 return error(Context, "Load/Store operand is not a pointer type");
3903 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3905 if (ValType && ValType != ElemType)
3906 return error(Context, "Explicit load/store type does not match pointee "
3907 "type of pointer operand");
3908 if (!PointerType::isLoadableOrStorableType(ElemType))
3909 return error(Context, "Cannot load/store from pointer");
3910 return std::error_code();
3913 /// Lazily parse the specified function body block.
3914 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3915 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3916 return error("Invalid record");
3918 InstructionList.clear();
3919 unsigned ModuleValueListSize = ValueList.size();
3920 unsigned ModuleMDValueListSize = MDValueList.size();
3922 // Add all the function arguments to the value table.
3923 for (Argument &I : F->args())
3924 ValueList.push_back(&I);
3926 unsigned NextValueNo = ValueList.size();
3927 BasicBlock *CurBB = nullptr;
3928 unsigned CurBBNo = 0;
3931 auto getLastInstruction = [&]() -> Instruction * {
3932 if (CurBB && !CurBB->empty())
3933 return &CurBB->back();
3934 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3935 !FunctionBBs[CurBBNo - 1]->empty())
3936 return &FunctionBBs[CurBBNo - 1]->back();
3940 std::vector<OperandBundleDef> OperandBundles;
3942 // Read all the records.
3943 SmallVector<uint64_t, 64> Record;
3945 BitstreamEntry Entry = Stream.advance();
3947 switch (Entry.Kind) {
3948 case BitstreamEntry::Error:
3949 return error("Malformed block");
3950 case BitstreamEntry::EndBlock:
3951 goto OutOfRecordLoop;
3953 case BitstreamEntry::SubBlock:
3955 default: // Skip unknown content.
3956 if (Stream.SkipBlock())
3957 return error("Invalid record");
3959 case bitc::CONSTANTS_BLOCK_ID:
3960 if (std::error_code EC = parseConstants())
3962 NextValueNo = ValueList.size();
3964 case bitc::VALUE_SYMTAB_BLOCK_ID:
3965 if (std::error_code EC = parseValueSymbolTable())
3968 case bitc::METADATA_ATTACHMENT_ID:
3969 if (std::error_code EC = parseMetadataAttachment(*F))
3972 case bitc::METADATA_BLOCK_ID:
3973 if (std::error_code EC = parseMetadata())
3976 case bitc::USELIST_BLOCK_ID:
3977 if (std::error_code EC = parseUseLists())
3983 case BitstreamEntry::Record:
3984 // The interesting case.
3990 Instruction *I = nullptr;
3991 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3993 default: // Default behavior: reject
3994 return error("Invalid value");
3995 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3996 if (Record.size() < 1 || Record[0] == 0)
3997 return error("Invalid record");
3998 // Create all the basic blocks for the function.
3999 FunctionBBs.resize(Record[0]);
4001 // See if anything took the address of blocks in this function.
4002 auto BBFRI = BasicBlockFwdRefs.find(F);
4003 if (BBFRI == BasicBlockFwdRefs.end()) {
4004 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4005 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4007 auto &BBRefs = BBFRI->second;
4008 // Check for invalid basic block references.
4009 if (BBRefs.size() > FunctionBBs.size())
4010 return error("Invalid ID");
4011 assert(!BBRefs.empty() && "Unexpected empty array");
4012 assert(!BBRefs.front() && "Invalid reference to entry block");
4013 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4015 if (I < RE && BBRefs[I]) {
4016 BBRefs[I]->insertInto(F);
4017 FunctionBBs[I] = BBRefs[I];
4019 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4022 // Erase from the table.
4023 BasicBlockFwdRefs.erase(BBFRI);
4026 CurBB = FunctionBBs[0];
4030 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4031 // This record indicates that the last instruction is at the same
4032 // location as the previous instruction with a location.
4033 I = getLastInstruction();
4036 return error("Invalid record");
4037 I->setDebugLoc(LastLoc);
4041 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4042 I = getLastInstruction();
4043 if (!I || Record.size() < 4)
4044 return error("Invalid record");
4046 unsigned Line = Record[0], Col = Record[1];
4047 unsigned ScopeID = Record[2], IAID = Record[3];
4049 MDNode *Scope = nullptr, *IA = nullptr;
4050 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
4051 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
4052 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4053 I->setDebugLoc(LastLoc);
4058 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4061 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4062 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4063 OpNum+1 > Record.size())
4064 return error("Invalid record");
4066 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4068 return error("Invalid record");
4069 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4070 InstructionList.push_back(I);
4071 if (OpNum < Record.size()) {
4072 if (Opc == Instruction::Add ||
4073 Opc == Instruction::Sub ||
4074 Opc == Instruction::Mul ||
4075 Opc == Instruction::Shl) {
4076 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4077 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4078 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4079 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4080 } else if (Opc == Instruction::SDiv ||
4081 Opc == Instruction::UDiv ||
4082 Opc == Instruction::LShr ||
4083 Opc == Instruction::AShr) {
4084 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4085 cast<BinaryOperator>(I)->setIsExact(true);
4086 } else if (isa<FPMathOperator>(I)) {
4087 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4089 I->setFastMathFlags(FMF);
4095 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4098 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4099 OpNum+2 != Record.size())
4100 return error("Invalid record");
4102 Type *ResTy = getTypeByID(Record[OpNum]);
4103 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4104 if (Opc == -1 || !ResTy)
4105 return error("Invalid record");
4106 Instruction *Temp = nullptr;
4107 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4109 InstructionList.push_back(Temp);
4110 CurBB->getInstList().push_back(Temp);
4113 auto CastOp = (Instruction::CastOps)Opc;
4114 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4115 return error("Invalid cast");
4116 I = CastInst::Create(CastOp, Op, ResTy);
4118 InstructionList.push_back(I);
4121 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4122 case bitc::FUNC_CODE_INST_GEP_OLD:
4123 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4129 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4130 InBounds = Record[OpNum++];
4131 Ty = getTypeByID(Record[OpNum++]);
4133 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4138 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4139 return error("Invalid record");
4142 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4145 cast<SequentialType>(BasePtr->getType()->getScalarType())
4148 "Explicit gep type does not match pointee type of pointer operand");
4150 SmallVector<Value*, 16> GEPIdx;
4151 while (OpNum != Record.size()) {
4153 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4154 return error("Invalid record");
4155 GEPIdx.push_back(Op);
4158 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4160 InstructionList.push_back(I);
4162 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4166 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4167 // EXTRACTVAL: [opty, opval, n x indices]
4170 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4171 return error("Invalid record");
4173 unsigned RecSize = Record.size();
4174 if (OpNum == RecSize)
4175 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4177 SmallVector<unsigned, 4> EXTRACTVALIdx;
4178 Type *CurTy = Agg->getType();
4179 for (; OpNum != RecSize; ++OpNum) {
4180 bool IsArray = CurTy->isArrayTy();
4181 bool IsStruct = CurTy->isStructTy();
4182 uint64_t Index = Record[OpNum];
4184 if (!IsStruct && !IsArray)
4185 return error("EXTRACTVAL: Invalid type");
4186 if ((unsigned)Index != Index)
4187 return error("Invalid value");
4188 if (IsStruct && Index >= CurTy->subtypes().size())
4189 return error("EXTRACTVAL: Invalid struct index");
4190 if (IsArray && Index >= CurTy->getArrayNumElements())
4191 return error("EXTRACTVAL: Invalid array index");
4192 EXTRACTVALIdx.push_back((unsigned)Index);
4195 CurTy = CurTy->subtypes()[Index];
4197 CurTy = CurTy->subtypes()[0];
4200 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4201 InstructionList.push_back(I);
4205 case bitc::FUNC_CODE_INST_INSERTVAL: {
4206 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4209 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4210 return error("Invalid record");
4212 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4213 return error("Invalid record");
4215 unsigned RecSize = Record.size();
4216 if (OpNum == RecSize)
4217 return error("INSERTVAL: Invalid instruction with 0 indices");
4219 SmallVector<unsigned, 4> INSERTVALIdx;
4220 Type *CurTy = Agg->getType();
4221 for (; OpNum != RecSize; ++OpNum) {
4222 bool IsArray = CurTy->isArrayTy();
4223 bool IsStruct = CurTy->isStructTy();
4224 uint64_t Index = Record[OpNum];
4226 if (!IsStruct && !IsArray)
4227 return error("INSERTVAL: Invalid type");
4228 if ((unsigned)Index != Index)
4229 return error("Invalid value");
4230 if (IsStruct && Index >= CurTy->subtypes().size())
4231 return error("INSERTVAL: Invalid struct index");
4232 if (IsArray && Index >= CurTy->getArrayNumElements())
4233 return error("INSERTVAL: Invalid array index");
4235 INSERTVALIdx.push_back((unsigned)Index);
4237 CurTy = CurTy->subtypes()[Index];
4239 CurTy = CurTy->subtypes()[0];
4242 if (CurTy != Val->getType())
4243 return error("Inserted value type doesn't match aggregate type");
4245 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4246 InstructionList.push_back(I);
4250 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4251 // obsolete form of select
4252 // handles select i1 ... in old bitcode
4254 Value *TrueVal, *FalseVal, *Cond;
4255 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4256 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4257 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4258 return error("Invalid record");
4260 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4261 InstructionList.push_back(I);
4265 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4266 // new form of select
4267 // handles select i1 or select [N x i1]
4269 Value *TrueVal, *FalseVal, *Cond;
4270 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4271 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4272 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4273 return error("Invalid record");
4275 // select condition can be either i1 or [N x i1]
4276 if (VectorType* vector_type =
4277 dyn_cast<VectorType>(Cond->getType())) {
4279 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4280 return error("Invalid type for value");
4283 if (Cond->getType() != Type::getInt1Ty(Context))
4284 return error("Invalid type for value");
4287 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4288 InstructionList.push_back(I);
4292 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4295 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4296 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4297 return error("Invalid record");
4298 if (!Vec->getType()->isVectorTy())
4299 return error("Invalid type for value");
4300 I = ExtractElementInst::Create(Vec, Idx);
4301 InstructionList.push_back(I);
4305 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4307 Value *Vec, *Elt, *Idx;
4308 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4309 return error("Invalid record");
4310 if (!Vec->getType()->isVectorTy())
4311 return error("Invalid type for value");
4312 if (popValue(Record, OpNum, NextValueNo,
4313 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4314 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4315 return error("Invalid record");
4316 I = InsertElementInst::Create(Vec, Elt, Idx);
4317 InstructionList.push_back(I);
4321 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4323 Value *Vec1, *Vec2, *Mask;
4324 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4325 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4326 return error("Invalid record");
4328 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4329 return error("Invalid record");
4330 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4331 return error("Invalid type for value");
4332 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4333 InstructionList.push_back(I);
4337 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4338 // Old form of ICmp/FCmp returning bool
4339 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4340 // both legal on vectors but had different behaviour.
4341 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4342 // FCmp/ICmp returning bool or vector of bool
4346 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4347 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4348 return error("Invalid record");
4350 unsigned PredVal = Record[OpNum];
4351 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4353 if (IsFP && Record.size() > OpNum+1)
4354 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4356 if (OpNum+1 != Record.size())
4357 return error("Invalid record");
4359 if (LHS->getType()->isFPOrFPVectorTy())
4360 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4362 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4365 I->setFastMathFlags(FMF);
4366 InstructionList.push_back(I);
4370 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4372 unsigned Size = Record.size();
4374 I = ReturnInst::Create(Context);
4375 InstructionList.push_back(I);
4380 Value *Op = nullptr;
4381 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4382 return error("Invalid record");
4383 if (OpNum != Record.size())
4384 return error("Invalid record");
4386 I = ReturnInst::Create(Context, Op);
4387 InstructionList.push_back(I);
4390 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4391 if (Record.size() != 1 && Record.size() != 3)
4392 return error("Invalid record");
4393 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4395 return error("Invalid record");
4397 if (Record.size() == 1) {
4398 I = BranchInst::Create(TrueDest);
4399 InstructionList.push_back(I);
4402 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4403 Value *Cond = getValue(Record, 2, NextValueNo,
4404 Type::getInt1Ty(Context));
4405 if (!FalseDest || !Cond)
4406 return error("Invalid record");
4407 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4408 InstructionList.push_back(I);
4412 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4413 if (Record.size() != 1 && Record.size() != 2)
4414 return error("Invalid record");
4417 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4419 return error("Invalid record");
4420 BasicBlock *UnwindDest = nullptr;
4421 if (Record.size() == 2) {
4422 UnwindDest = getBasicBlock(Record[Idx++]);
4424 return error("Invalid record");
4427 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4428 InstructionList.push_back(I);
4431 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4432 if (Record.size() != 2)
4433 return error("Invalid record");
4436 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4438 return error("Invalid record");
4439 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4441 return error("Invalid record");
4443 I = CatchReturnInst::Create(CatchPad, BB);
4444 InstructionList.push_back(I);
4447 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4448 // We must have, at minimum, the outer scope and the number of arguments.
4449 if (Record.size() < 2)
4450 return error("Invalid record");
4455 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4457 unsigned NumHandlers = Record[Idx++];
4459 SmallVector<BasicBlock *, 2> Handlers;
4460 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4461 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4463 return error("Invalid record");
4464 Handlers.push_back(BB);
4467 BasicBlock *UnwindDest = nullptr;
4468 if (Idx + 1 == Record.size()) {
4469 UnwindDest = getBasicBlock(Record[Idx++]);
4471 return error("Invalid record");
4474 if (Record.size() != Idx)
4475 return error("Invalid record");
4478 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4479 for (BasicBlock *Handler : Handlers)
4480 CatchSwitch->addHandler(Handler);
4482 InstructionList.push_back(I);
4485 case bitc::FUNC_CODE_INST_CATCHPAD:
4486 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4487 // We must have, at minimum, the outer scope and the number of arguments.
4488 if (Record.size() < 2)
4489 return error("Invalid record");
4494 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4496 unsigned NumArgOperands = Record[Idx++];
4498 SmallVector<Value *, 2> Args;
4499 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4501 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4502 return error("Invalid record");
4503 Args.push_back(Val);
4506 if (Record.size() != Idx)
4507 return error("Invalid record");
4509 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4510 I = CleanupPadInst::Create(ParentPad, Args);
4512 I = CatchPadInst::Create(ParentPad, Args);
4513 InstructionList.push_back(I);
4516 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4518 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4519 // "New" SwitchInst format with case ranges. The changes to write this
4520 // format were reverted but we still recognize bitcode that uses it.
4521 // Hopefully someday we will have support for case ranges and can use
4522 // this format again.
4524 Type *OpTy = getTypeByID(Record[1]);
4525 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4527 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4528 BasicBlock *Default = getBasicBlock(Record[3]);
4529 if (!OpTy || !Cond || !Default)
4530 return error("Invalid record");
4532 unsigned NumCases = Record[4];
4534 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4535 InstructionList.push_back(SI);
4537 unsigned CurIdx = 5;
4538 for (unsigned i = 0; i != NumCases; ++i) {
4539 SmallVector<ConstantInt*, 1> CaseVals;
4540 unsigned NumItems = Record[CurIdx++];
4541 for (unsigned ci = 0; ci != NumItems; ++ci) {
4542 bool isSingleNumber = Record[CurIdx++];
4545 unsigned ActiveWords = 1;
4546 if (ValueBitWidth > 64)
4547 ActiveWords = Record[CurIdx++];
4548 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4550 CurIdx += ActiveWords;
4552 if (!isSingleNumber) {
4554 if (ValueBitWidth > 64)
4555 ActiveWords = Record[CurIdx++];
4556 APInt High = readWideAPInt(
4557 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4558 CurIdx += ActiveWords;
4560 // FIXME: It is not clear whether values in the range should be
4561 // compared as signed or unsigned values. The partially
4562 // implemented changes that used this format in the past used
4563 // unsigned comparisons.
4564 for ( ; Low.ule(High); ++Low)
4565 CaseVals.push_back(ConstantInt::get(Context, Low));
4567 CaseVals.push_back(ConstantInt::get(Context, Low));
4569 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4570 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4571 cve = CaseVals.end(); cvi != cve; ++cvi)
4572 SI->addCase(*cvi, DestBB);
4578 // Old SwitchInst format without case ranges.
4580 if (Record.size() < 3 || (Record.size() & 1) == 0)
4581 return error("Invalid record");
4582 Type *OpTy = getTypeByID(Record[0]);
4583 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4584 BasicBlock *Default = getBasicBlock(Record[2]);
4585 if (!OpTy || !Cond || !Default)
4586 return error("Invalid record");
4587 unsigned NumCases = (Record.size()-3)/2;
4588 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4589 InstructionList.push_back(SI);
4590 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4591 ConstantInt *CaseVal =
4592 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4593 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4594 if (!CaseVal || !DestBB) {
4596 return error("Invalid record");
4598 SI->addCase(CaseVal, DestBB);
4603 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4604 if (Record.size() < 2)
4605 return error("Invalid record");
4606 Type *OpTy = getTypeByID(Record[0]);
4607 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4608 if (!OpTy || !Address)
4609 return error("Invalid record");
4610 unsigned NumDests = Record.size()-2;
4611 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4612 InstructionList.push_back(IBI);
4613 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4614 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4615 IBI->addDestination(DestBB);
4618 return error("Invalid record");
4625 case bitc::FUNC_CODE_INST_INVOKE: {
4626 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4627 if (Record.size() < 4)
4628 return error("Invalid record");
4630 AttributeSet PAL = getAttributes(Record[OpNum++]);
4631 unsigned CCInfo = Record[OpNum++];
4632 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4633 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4635 FunctionType *FTy = nullptr;
4636 if (CCInfo >> 13 & 1 &&
4637 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4638 return error("Explicit invoke type is not a function type");
4641 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4642 return error("Invalid record");
4644 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4646 return error("Callee is not a pointer");
4648 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4650 return error("Callee is not of pointer to function type");
4651 } else if (CalleeTy->getElementType() != FTy)
4652 return error("Explicit invoke type does not match pointee type of "
4654 if (Record.size() < FTy->getNumParams() + OpNum)
4655 return error("Insufficient operands to call");
4657 SmallVector<Value*, 16> Ops;
4658 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4659 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4660 FTy->getParamType(i)));
4662 return error("Invalid record");
4665 if (!FTy->isVarArg()) {
4666 if (Record.size() != OpNum)
4667 return error("Invalid record");
4669 // Read type/value pairs for varargs params.
4670 while (OpNum != Record.size()) {
4672 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4673 return error("Invalid record");
4678 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4679 OperandBundles.clear();
4680 InstructionList.push_back(I);
4681 cast<InvokeInst>(I)->setCallingConv(
4682 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4683 cast<InvokeInst>(I)->setAttributes(PAL);
4686 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4688 Value *Val = nullptr;
4689 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4690 return error("Invalid record");
4691 I = ResumeInst::Create(Val);
4692 InstructionList.push_back(I);
4695 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4696 I = new UnreachableInst(Context);
4697 InstructionList.push_back(I);
4699 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4700 if (Record.size() < 1 || ((Record.size()-1)&1))
4701 return error("Invalid record");
4702 Type *Ty = getTypeByID(Record[0]);
4704 return error("Invalid record");
4706 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4707 InstructionList.push_back(PN);
4709 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4711 // With the new function encoding, it is possible that operands have
4712 // negative IDs (for forward references). Use a signed VBR
4713 // representation to keep the encoding small.
4715 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4717 V = getValue(Record, 1+i, NextValueNo, Ty);
4718 BasicBlock *BB = getBasicBlock(Record[2+i]);
4720 return error("Invalid record");
4721 PN->addIncoming(V, BB);
4727 case bitc::FUNC_CODE_INST_LANDINGPAD:
4728 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4729 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4731 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4732 if (Record.size() < 3)
4733 return error("Invalid record");
4735 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4736 if (Record.size() < 4)
4737 return error("Invalid record");
4739 Type *Ty = getTypeByID(Record[Idx++]);
4741 return error("Invalid record");
4742 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4743 Value *PersFn = nullptr;
4744 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4745 return error("Invalid record");
4747 if (!F->hasPersonalityFn())
4748 F->setPersonalityFn(cast<Constant>(PersFn));
4749 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4750 return error("Personality function mismatch");
4753 bool IsCleanup = !!Record[Idx++];
4754 unsigned NumClauses = Record[Idx++];
4755 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4756 LP->setCleanup(IsCleanup);
4757 for (unsigned J = 0; J != NumClauses; ++J) {
4758 LandingPadInst::ClauseType CT =
4759 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4762 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4764 return error("Invalid record");
4767 assert((CT != LandingPadInst::Catch ||
4768 !isa<ArrayType>(Val->getType())) &&
4769 "Catch clause has a invalid type!");
4770 assert((CT != LandingPadInst::Filter ||
4771 isa<ArrayType>(Val->getType())) &&
4772 "Filter clause has invalid type!");
4773 LP->addClause(cast<Constant>(Val));
4777 InstructionList.push_back(I);
4781 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4782 if (Record.size() != 4)
4783 return error("Invalid record");
4784 uint64_t AlignRecord = Record[3];
4785 const uint64_t InAllocaMask = uint64_t(1) << 5;
4786 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4787 // Reserve bit 7 for SwiftError flag.
4788 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4789 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4790 bool InAlloca = AlignRecord & InAllocaMask;
4791 Type *Ty = getTypeByID(Record[0]);
4792 if ((AlignRecord & ExplicitTypeMask) == 0) {
4793 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4795 return error("Old-style alloca with a non-pointer type");
4796 Ty = PTy->getElementType();
4798 Type *OpTy = getTypeByID(Record[1]);
4799 Value *Size = getFnValueByID(Record[2], OpTy);
4801 if (std::error_code EC =
4802 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4806 return error("Invalid record");
4807 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4808 AI->setUsedWithInAlloca(InAlloca);
4810 InstructionList.push_back(I);
4813 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4816 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4817 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4818 return error("Invalid record");
4821 if (OpNum + 3 == Record.size())
4822 Ty = getTypeByID(Record[OpNum++]);
4823 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4826 Ty = cast<PointerType>(Op->getType())->getElementType();
4829 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4831 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4833 InstructionList.push_back(I);
4836 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4837 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4840 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4841 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4842 return error("Invalid record");
4845 if (OpNum + 5 == Record.size())
4846 Ty = getTypeByID(Record[OpNum++]);
4847 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4850 Ty = cast<PointerType>(Op->getType())->getElementType();
4852 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4853 if (Ordering == NotAtomic || Ordering == Release ||
4854 Ordering == AcquireRelease)
4855 return error("Invalid record");
4856 if (Ordering != NotAtomic && Record[OpNum] == 0)
4857 return error("Invalid record");
4858 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4861 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4863 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4865 InstructionList.push_back(I);
4868 case bitc::FUNC_CODE_INST_STORE:
4869 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4872 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4873 (BitCode == bitc::FUNC_CODE_INST_STORE
4874 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4875 : popValue(Record, OpNum, NextValueNo,
4876 cast<PointerType>(Ptr->getType())->getElementType(),
4878 OpNum + 2 != Record.size())
4879 return error("Invalid record");
4881 if (std::error_code EC =
4882 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4885 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4887 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4888 InstructionList.push_back(I);
4891 case bitc::FUNC_CODE_INST_STOREATOMIC:
4892 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4893 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4896 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4897 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4898 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4899 : popValue(Record, OpNum, NextValueNo,
4900 cast<PointerType>(Ptr->getType())->getElementType(),
4902 OpNum + 4 != Record.size())
4903 return error("Invalid record");
4905 if (std::error_code EC =
4906 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4908 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4909 if (Ordering == NotAtomic || Ordering == Acquire ||
4910 Ordering == AcquireRelease)
4911 return error("Invalid record");
4912 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4913 if (Ordering != NotAtomic && Record[OpNum] == 0)
4914 return error("Invalid record");
4917 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4919 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4920 InstructionList.push_back(I);
4923 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4924 case bitc::FUNC_CODE_INST_CMPXCHG: {
4925 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4926 // failureordering?, isweak?]
4928 Value *Ptr, *Cmp, *New;
4929 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4930 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4931 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4932 : popValue(Record, OpNum, NextValueNo,
4933 cast<PointerType>(Ptr->getType())->getElementType(),
4935 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4936 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4937 return error("Invalid record");
4938 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4939 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4940 return error("Invalid record");
4941 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4943 if (std::error_code EC =
4944 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4946 AtomicOrdering FailureOrdering;
4947 if (Record.size() < 7)
4949 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4951 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4953 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4955 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4957 if (Record.size() < 8) {
4958 // Before weak cmpxchgs existed, the instruction simply returned the
4959 // value loaded from memory, so bitcode files from that era will be
4960 // expecting the first component of a modern cmpxchg.
4961 CurBB->getInstList().push_back(I);
4962 I = ExtractValueInst::Create(I, 0);
4964 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4967 InstructionList.push_back(I);
4970 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4971 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4974 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4975 popValue(Record, OpNum, NextValueNo,
4976 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4977 OpNum+4 != Record.size())
4978 return error("Invalid record");
4979 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4980 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4981 Operation > AtomicRMWInst::LAST_BINOP)
4982 return error("Invalid record");
4983 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4984 if (Ordering == NotAtomic || Ordering == Unordered)
4985 return error("Invalid record");
4986 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4987 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4988 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4989 InstructionList.push_back(I);
4992 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4993 if (2 != Record.size())
4994 return error("Invalid record");
4995 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4996 if (Ordering == NotAtomic || Ordering == Unordered ||
4997 Ordering == Monotonic)
4998 return error("Invalid record");
4999 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5000 I = new FenceInst(Context, Ordering, SynchScope);
5001 InstructionList.push_back(I);
5004 case bitc::FUNC_CODE_INST_CALL: {
5005 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5006 if (Record.size() < 3)
5007 return error("Invalid record");
5010 AttributeSet PAL = getAttributes(Record[OpNum++]);
5011 unsigned CCInfo = Record[OpNum++];
5014 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5015 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5017 return error("Fast math flags indicator set for call with no FMF");
5020 FunctionType *FTy = nullptr;
5021 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5022 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5023 return error("Explicit call type is not a function type");
5026 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5027 return error("Invalid record");
5029 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5031 return error("Callee is not a pointer type");
5033 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5035 return error("Callee is not of pointer to function type");
5036 } else if (OpTy->getElementType() != FTy)
5037 return error("Explicit call type does not match pointee type of "
5039 if (Record.size() < FTy->getNumParams() + OpNum)
5040 return error("Insufficient operands to call");
5042 SmallVector<Value*, 16> Args;
5043 // Read the fixed params.
5044 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5045 if (FTy->getParamType(i)->isLabelTy())
5046 Args.push_back(getBasicBlock(Record[OpNum]));
5048 Args.push_back(getValue(Record, OpNum, NextValueNo,
5049 FTy->getParamType(i)));
5051 return error("Invalid record");
5054 // Read type/value pairs for varargs params.
5055 if (!FTy->isVarArg()) {
5056 if (OpNum != Record.size())
5057 return error("Invalid record");
5059 while (OpNum != Record.size()) {
5061 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5062 return error("Invalid record");
5067 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5068 OperandBundles.clear();
5069 InstructionList.push_back(I);
5070 cast<CallInst>(I)->setCallingConv(
5071 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5072 CallInst::TailCallKind TCK = CallInst::TCK_None;
5073 if (CCInfo & 1 << bitc::CALL_TAIL)
5074 TCK = CallInst::TCK_Tail;
5075 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5076 TCK = CallInst::TCK_MustTail;
5077 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5078 TCK = CallInst::TCK_NoTail;
5079 cast<CallInst>(I)->setTailCallKind(TCK);
5080 cast<CallInst>(I)->setAttributes(PAL);
5082 if (!isa<FPMathOperator>(I))
5083 return error("Fast-math-flags specified for call without "
5084 "floating-point scalar or vector return type");
5085 I->setFastMathFlags(FMF);
5089 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5090 if (Record.size() < 3)
5091 return error("Invalid record");
5092 Type *OpTy = getTypeByID(Record[0]);
5093 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5094 Type *ResTy = getTypeByID(Record[2]);
5095 if (!OpTy || !Op || !ResTy)
5096 return error("Invalid record");
5097 I = new VAArgInst(Op, ResTy);
5098 InstructionList.push_back(I);
5102 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5103 // A call or an invoke can be optionally prefixed with some variable
5104 // number of operand bundle blocks. These blocks are read into
5105 // OperandBundles and consumed at the next call or invoke instruction.
5107 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5108 return error("Invalid record");
5110 std::vector<Value *> Inputs;
5113 while (OpNum != Record.size()) {
5115 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5116 return error("Invalid record");
5117 Inputs.push_back(Op);
5120 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5125 // Add instruction to end of current BB. If there is no current BB, reject
5129 return error("Invalid instruction with no BB");
5131 if (!OperandBundles.empty()) {
5133 return error("Operand bundles found with no consumer");
5135 CurBB->getInstList().push_back(I);
5137 // If this was a terminator instruction, move to the next block.
5138 if (isa<TerminatorInst>(I)) {
5140 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5143 // Non-void values get registered in the value table for future use.
5144 if (I && !I->getType()->isVoidTy())
5145 ValueList.assignValue(I, NextValueNo++);
5150 if (!OperandBundles.empty())
5151 return error("Operand bundles found with no consumer");
5153 // Check the function list for unresolved values.
5154 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5155 if (!A->getParent()) {
5156 // We found at least one unresolved value. Nuke them all to avoid leaks.
5157 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5158 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5159 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5163 return error("Never resolved value found in function");
5167 // FIXME: Check for unresolved forward-declared metadata references
5168 // and clean up leaks.
5170 // Trim the value list down to the size it was before we parsed this function.
5171 ValueList.shrinkTo(ModuleValueListSize);
5172 MDValueList.shrinkTo(ModuleMDValueListSize);
5173 std::vector<BasicBlock*>().swap(FunctionBBs);
5174 return std::error_code();
5177 /// Find the function body in the bitcode stream
5178 std::error_code BitcodeReader::findFunctionInStream(
5180 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5181 while (DeferredFunctionInfoIterator->second == 0) {
5182 // This is the fallback handling for the old format bitcode that
5183 // didn't contain the function index in the VST, or when we have
5184 // an anonymous function which would not have a VST entry.
5185 // Assert that we have one of those two cases.
5186 assert(VSTOffset == 0 || !F->hasName());
5187 // Parse the next body in the stream and set its position in the
5188 // DeferredFunctionInfo map.
5189 if (std::error_code EC = rememberAndSkipFunctionBodies())
5192 return std::error_code();
5195 //===----------------------------------------------------------------------===//
5196 // GVMaterializer implementation
5197 //===----------------------------------------------------------------------===//
5199 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5201 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5202 // In older bitcode we must materialize the metadata before parsing
5203 // any functions, in order to set up the MDValueList properly.
5204 if (!SeenModuleValuesRecord) {
5205 if (std::error_code EC = materializeMetadata())
5209 Function *F = dyn_cast<Function>(GV);
5210 // If it's not a function or is already material, ignore the request.
5211 if (!F || !F->isMaterializable())
5212 return std::error_code();
5214 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5215 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5216 // If its position is recorded as 0, its body is somewhere in the stream
5217 // but we haven't seen it yet.
5218 if (DFII->second == 0)
5219 if (std::error_code EC = findFunctionInStream(F, DFII))
5222 // Move the bit stream to the saved position of the deferred function body.
5223 Stream.JumpToBit(DFII->second);
5225 if (std::error_code EC = parseFunctionBody(F))
5227 F->setIsMaterializable(false);
5232 // Upgrade any old intrinsic calls in the function.
5233 for (auto &I : UpgradedIntrinsics) {
5234 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5237 if (CallInst *CI = dyn_cast<CallInst>(U))
5238 UpgradeIntrinsicCall(CI, I.second);
5242 // Finish fn->subprogram upgrade for materialized functions.
5243 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5244 F->setSubprogram(SP);
5246 // Bring in any functions that this function forward-referenced via
5248 return materializeForwardReferencedFunctions();
5251 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5252 const Function *F = dyn_cast<Function>(GV);
5253 if (!F || F->isDeclaration())
5256 // Dematerializing F would leave dangling references that wouldn't be
5257 // reconnected on re-materialization.
5258 if (BlockAddressesTaken.count(F))
5261 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5264 void BitcodeReader::dematerialize(GlobalValue *GV) {
5265 Function *F = dyn_cast<Function>(GV);
5266 // If this function isn't dematerializable, this is a noop.
5267 if (!F || !isDematerializable(F))
5270 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5272 // Just forget the function body, we can remat it later.
5273 F->dropAllReferences();
5274 F->setIsMaterializable(true);
5277 std::error_code BitcodeReader::materializeModule(Module *M) {
5278 assert(M == TheModule &&
5279 "Can only Materialize the Module this BitcodeReader is attached to.");
5281 if (std::error_code EC = materializeMetadata())
5284 // Promise to materialize all forward references.
5285 WillMaterializeAllForwardRefs = true;
5287 // Iterate over the module, deserializing any functions that are still on
5289 for (Function &F : *TheModule) {
5290 if (std::error_code EC = materialize(&F))
5293 // At this point, if there are any function bodies, parse the rest of
5294 // the bits in the module past the last function block we have recorded
5295 // through either lazy scanning or the VST.
5296 if (LastFunctionBlockBit || NextUnreadBit)
5297 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5300 // Check that all block address forward references got resolved (as we
5302 if (!BasicBlockFwdRefs.empty())
5303 return error("Never resolved function from blockaddress");
5305 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5306 // delete the old functions to clean up. We can't do this unless the entire
5307 // module is materialized because there could always be another function body
5308 // with calls to the old function.
5309 for (auto &I : UpgradedIntrinsics) {
5310 for (auto *U : I.first->users()) {
5311 if (CallInst *CI = dyn_cast<CallInst>(U))
5312 UpgradeIntrinsicCall(CI, I.second);
5314 if (!I.first->use_empty())
5315 I.first->replaceAllUsesWith(I.second);
5316 I.first->eraseFromParent();
5318 UpgradedIntrinsics.clear();
5320 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5321 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5323 UpgradeDebugInfo(*M);
5324 return std::error_code();
5327 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5328 return IdentifiedStructTypes;
5332 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5334 return initLazyStream(std::move(Streamer));
5335 return initStreamFromBuffer();
5338 std::error_code BitcodeReader::initStreamFromBuffer() {
5339 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5340 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5342 if (Buffer->getBufferSize() & 3)
5343 return error("Invalid bitcode signature");
5345 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5346 // The magic number is 0x0B17C0DE stored in little endian.
5347 if (isBitcodeWrapper(BufPtr, BufEnd))
5348 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5349 return error("Invalid bitcode wrapper header");
5351 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5352 Stream.init(&*StreamFile);
5354 return std::error_code();
5358 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5359 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5362 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5363 StreamingMemoryObject &Bytes = *OwnedBytes;
5364 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5365 Stream.init(&*StreamFile);
5367 unsigned char buf[16];
5368 if (Bytes.readBytes(buf, 16, 0) != 16)
5369 return error("Invalid bitcode signature");
5371 if (!isBitcode(buf, buf + 16))
5372 return error("Invalid bitcode signature");
5374 if (isBitcodeWrapper(buf, buf + 4)) {
5375 const unsigned char *bitcodeStart = buf;
5376 const unsigned char *bitcodeEnd = buf + 16;
5377 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5378 Bytes.dropLeadingBytes(bitcodeStart - buf);
5379 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5381 return std::error_code();
5384 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5385 const Twine &Message) {
5386 return ::error(DiagnosticHandler, make_error_code(E), Message);
5389 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5390 return ::error(DiagnosticHandler,
5391 make_error_code(BitcodeError::CorruptedBitcode), Message);
5394 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5395 return ::error(DiagnosticHandler, make_error_code(E));
5398 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5399 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5400 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5401 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
5402 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5404 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5405 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5406 bool CheckFuncSummaryPresenceOnly)
5407 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
5408 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5410 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5412 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5414 // Specialized value symbol table parser used when reading function index
5415 // blocks where we don't actually create global values.
5416 // At the end of this routine the function index is populated with a map
5417 // from function name to FunctionInfo. The function info contains
5418 // the function block's bitcode offset as well as the offset into the
5419 // function summary section.
5420 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5421 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5422 return error("Invalid record");
5424 SmallVector<uint64_t, 64> Record;
5426 // Read all the records for this value table.
5427 SmallString<128> ValueName;
5429 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5431 switch (Entry.Kind) {
5432 case BitstreamEntry::SubBlock: // Handled for us already.
5433 case BitstreamEntry::Error:
5434 return error("Malformed block");
5435 case BitstreamEntry::EndBlock:
5436 return std::error_code();
5437 case BitstreamEntry::Record:
5438 // The interesting case.
5444 switch (Stream.readRecord(Entry.ID, Record)) {
5445 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5447 case bitc::VST_CODE_FNENTRY: {
5448 // VST_FNENTRY: [valueid, offset, namechar x N]
5449 if (convertToString(Record, 2, ValueName))
5450 return error("Invalid record");
5451 unsigned ValueID = Record[0];
5452 uint64_t FuncOffset = Record[1];
5453 std::unique_ptr<FunctionInfo> FuncInfo =
5454 llvm::make_unique<FunctionInfo>(FuncOffset);
5455 if (foundFuncSummary() && !IsLazy) {
5456 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5457 SummaryMap.find(ValueID);
5458 assert(SMI != SummaryMap.end() && "Summary info not found");
5459 FuncInfo->setFunctionSummary(std::move(SMI->second));
5461 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5466 case bitc::VST_CODE_COMBINED_FNENTRY: {
5467 // VST_FNENTRY: [offset, namechar x N]
5468 if (convertToString(Record, 1, ValueName))
5469 return error("Invalid record");
5470 uint64_t FuncSummaryOffset = Record[0];
5471 std::unique_ptr<FunctionInfo> FuncInfo =
5472 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5473 if (foundFuncSummary() && !IsLazy) {
5474 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5475 SummaryMap.find(FuncSummaryOffset);
5476 assert(SMI != SummaryMap.end() && "Summary info not found");
5477 FuncInfo->setFunctionSummary(std::move(SMI->second));
5479 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5488 // Parse just the blocks needed for function index building out of the module.
5489 // At the end of this routine the function Index is populated with a map
5490 // from function name to FunctionInfo. The function info contains
5491 // either the parsed function summary information (when parsing summaries
5492 // eagerly), or just to the function summary record's offset
5493 // if parsing lazily (IsLazy).
5494 std::error_code FunctionIndexBitcodeReader::parseModule() {
5495 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5496 return error("Invalid record");
5498 // Read the function index for this module.
5500 BitstreamEntry Entry = Stream.advance();
5502 switch (Entry.Kind) {
5503 case BitstreamEntry::Error:
5504 return error("Malformed block");
5505 case BitstreamEntry::EndBlock:
5506 return std::error_code();
5508 case BitstreamEntry::SubBlock:
5509 if (CheckFuncSummaryPresenceOnly) {
5510 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) {
5511 SeenFuncSummary = true;
5512 // No need to parse the rest since we found the summary.
5513 return std::error_code();
5515 if (Stream.SkipBlock())
5516 return error("Invalid record");
5520 default: // Skip unknown content.
5521 if (Stream.SkipBlock())
5522 return error("Invalid record");
5524 case bitc::BLOCKINFO_BLOCK_ID:
5525 // Need to parse these to get abbrev ids (e.g. for VST)
5526 if (Stream.ReadBlockInfoBlock())
5527 return error("Malformed block");
5529 case bitc::VALUE_SYMTAB_BLOCK_ID:
5530 if (std::error_code EC = parseValueSymbolTable())
5533 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5534 SeenFuncSummary = true;
5536 // Lazy parsing of summary info, skip it.
5537 if (Stream.SkipBlock())
5538 return error("Invalid record");
5539 } else if (std::error_code EC = parseEntireSummary())
5542 case bitc::MODULE_STRTAB_BLOCK_ID:
5543 if (std::error_code EC = parseModuleStringTable())
5549 case BitstreamEntry::Record:
5550 Stream.skipRecord(Entry.ID);
5556 // Eagerly parse the entire function summary block (i.e. for all functions
5557 // in the index). This populates the FunctionSummary objects in
5559 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5560 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5561 return error("Invalid record");
5563 SmallVector<uint64_t, 64> Record;
5566 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5568 switch (Entry.Kind) {
5569 case BitstreamEntry::SubBlock: // Handled for us already.
5570 case BitstreamEntry::Error:
5571 return error("Malformed block");
5572 case BitstreamEntry::EndBlock:
5573 return std::error_code();
5574 case BitstreamEntry::Record:
5575 // The interesting case.
5579 // Read a record. The record format depends on whether this
5580 // is a per-module index or a combined index file. In the per-module
5581 // case the records contain the associated value's ID for correlation
5582 // with VST entries. In the combined index the correlation is done
5583 // via the bitcode offset of the summary records (which were saved
5584 // in the combined index VST entries). The records also contain
5585 // information used for ThinLTO renaming and importing.
5587 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5588 switch (Stream.readRecord(Entry.ID, Record)) {
5589 default: // Default behavior: ignore.
5591 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5592 case bitc::FS_CODE_PERMODULE_ENTRY: {
5593 unsigned ValueID = Record[0];
5594 bool IsLocal = Record[1];
5595 unsigned InstCount = Record[2];
5596 std::unique_ptr<FunctionSummary> FS =
5597 llvm::make_unique<FunctionSummary>(InstCount);
5598 FS->setLocalFunction(IsLocal);
5599 // The module path string ref set in the summary must be owned by the
5600 // index's module string table. Since we don't have a module path
5601 // string table section in the per-module index, we create a single
5602 // module path string table entry with an empty (0) ID to take
5605 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5606 SummaryMap[ValueID] = std::move(FS);
5608 // FS_COMBINED_ENTRY: [modid, instcount]
5609 case bitc::FS_CODE_COMBINED_ENTRY: {
5610 uint64_t ModuleId = Record[0];
5611 unsigned InstCount = Record[1];
5612 std::unique_ptr<FunctionSummary> FS =
5613 llvm::make_unique<FunctionSummary>(InstCount);
5614 FS->setModulePath(ModuleIdMap[ModuleId]);
5615 SummaryMap[CurRecordBit] = std::move(FS);
5619 llvm_unreachable("Exit infinite loop");
5622 // Parse the module string table block into the Index.
5623 // This populates the ModulePathStringTable map in the index.
5624 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5625 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5626 return error("Invalid record");
5628 SmallVector<uint64_t, 64> Record;
5630 SmallString<128> ModulePath;
5632 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5634 switch (Entry.Kind) {
5635 case BitstreamEntry::SubBlock: // Handled for us already.
5636 case BitstreamEntry::Error:
5637 return error("Malformed block");
5638 case BitstreamEntry::EndBlock:
5639 return std::error_code();
5640 case BitstreamEntry::Record:
5641 // The interesting case.
5646 switch (Stream.readRecord(Entry.ID, Record)) {
5647 default: // Default behavior: ignore.
5649 case bitc::MST_CODE_ENTRY: {
5650 // MST_ENTRY: [modid, namechar x N]
5651 if (convertToString(Record, 1, ModulePath))
5652 return error("Invalid record");
5653 uint64_t ModuleId = Record[0];
5654 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5655 ModuleIdMap[ModuleId] = ModulePathInMap;
5661 llvm_unreachable("Exit infinite loop");
5664 // Parse the function info index from the bitcode streamer into the given index.
5665 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5666 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5669 if (std::error_code EC = initStream(std::move(Streamer)))
5672 // Sniff for the signature.
5673 if (!hasValidBitcodeHeader(Stream))
5674 return error("Invalid bitcode signature");
5676 // We expect a number of well-defined blocks, though we don't necessarily
5677 // need to understand them all.
5679 if (Stream.AtEndOfStream()) {
5680 // We didn't really read a proper Module block.
5681 return error("Malformed block");
5684 BitstreamEntry Entry =
5685 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5687 if (Entry.Kind != BitstreamEntry::SubBlock)
5688 return error("Malformed block");
5690 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5691 // building the function summary index.
5692 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5693 return parseModule();
5695 if (Stream.SkipBlock())
5696 return error("Invalid record");
5700 // Parse the function information at the given offset in the buffer into
5701 // the index. Used to support lazy parsing of function summaries from the
5702 // combined index during importing.
5703 // TODO: This function is not yet complete as it won't have a consumer
5704 // until ThinLTO function importing is added.
5705 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5706 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5707 size_t FunctionSummaryOffset) {
5710 if (std::error_code EC = initStream(std::move(Streamer)))
5713 // Sniff for the signature.
5714 if (!hasValidBitcodeHeader(Stream))
5715 return error("Invalid bitcode signature");
5717 Stream.JumpToBit(FunctionSummaryOffset);
5719 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5721 switch (Entry.Kind) {
5723 return error("Malformed block");
5724 case BitstreamEntry::Record:
5725 // The expected case.
5729 // TODO: Read a record. This interface will be completed when ThinLTO
5730 // importing is added so that it can be tested.
5731 SmallVector<uint64_t, 64> Record;
5732 switch (Stream.readRecord(Entry.ID, Record)) {
5733 case bitc::FS_CODE_COMBINED_ENTRY:
5735 return error("Invalid record");
5738 return std::error_code();
5742 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5744 return initLazyStream(std::move(Streamer));
5745 return initStreamFromBuffer();
5748 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5749 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5750 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5752 if (Buffer->getBufferSize() & 3)
5753 return error("Invalid bitcode signature");
5755 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5756 // The magic number is 0x0B17C0DE stored in little endian.
5757 if (isBitcodeWrapper(BufPtr, BufEnd))
5758 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5759 return error("Invalid bitcode wrapper header");
5761 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5762 Stream.init(&*StreamFile);
5764 return std::error_code();
5767 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5768 std::unique_ptr<DataStreamer> Streamer) {
5769 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5772 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5773 StreamingMemoryObject &Bytes = *OwnedBytes;
5774 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5775 Stream.init(&*StreamFile);
5777 unsigned char buf[16];
5778 if (Bytes.readBytes(buf, 16, 0) != 16)
5779 return error("Invalid bitcode signature");
5781 if (!isBitcode(buf, buf + 16))
5782 return error("Invalid bitcode signature");
5784 if (isBitcodeWrapper(buf, buf + 4)) {
5785 const unsigned char *bitcodeStart = buf;
5786 const unsigned char *bitcodeEnd = buf + 16;
5787 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5788 Bytes.dropLeadingBytes(bitcodeStart - buf);
5789 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5791 return std::error_code();
5795 class BitcodeErrorCategoryType : public std::error_category {
5796 const char *name() const LLVM_NOEXCEPT override {
5797 return "llvm.bitcode";
5799 std::string message(int IE) const override {
5800 BitcodeError E = static_cast<BitcodeError>(IE);
5802 case BitcodeError::InvalidBitcodeSignature:
5803 return "Invalid bitcode signature";
5804 case BitcodeError::CorruptedBitcode:
5805 return "Corrupted bitcode";
5807 llvm_unreachable("Unknown error type!");
5812 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5814 const std::error_category &llvm::BitcodeErrorCategory() {
5815 return *ErrorCategory;
5818 //===----------------------------------------------------------------------===//
5819 // External interface
5820 //===----------------------------------------------------------------------===//
5822 static ErrorOr<std::unique_ptr<Module>>
5823 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5824 BitcodeReader *R, LLVMContext &Context,
5825 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5826 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5827 M->setMaterializer(R);
5829 auto cleanupOnError = [&](std::error_code EC) {
5830 R->releaseBuffer(); // Never take ownership on error.
5834 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5835 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5836 ShouldLazyLoadMetadata))
5837 return cleanupOnError(EC);
5839 if (MaterializeAll) {
5840 // Read in the entire module, and destroy the BitcodeReader.
5841 if (std::error_code EC = M->materializeAllPermanently())
5842 return cleanupOnError(EC);
5844 // Resolve forward references from blockaddresses.
5845 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5846 return cleanupOnError(EC);
5848 return std::move(M);
5851 /// \brief Get a lazy one-at-time loading module from bitcode.
5853 /// This isn't always used in a lazy context. In particular, it's also used by
5854 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5855 /// in forward-referenced functions from block address references.
5857 /// \param[in] MaterializeAll Set to \c true if we should materialize
5859 static ErrorOr<std::unique_ptr<Module>>
5860 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5861 LLVMContext &Context, bool MaterializeAll,
5862 bool ShouldLazyLoadMetadata = false) {
5863 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
5865 ErrorOr<std::unique_ptr<Module>> Ret =
5866 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5867 MaterializeAll, ShouldLazyLoadMetadata);
5871 Buffer.release(); // The BitcodeReader owns it now.
5875 ErrorOr<std::unique_ptr<Module>>
5876 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
5877 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
5878 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5879 ShouldLazyLoadMetadata);
5882 ErrorOr<std::unique_ptr<Module>>
5883 llvm::getStreamedBitcodeModule(StringRef Name,
5884 std::unique_ptr<DataStreamer> Streamer,
5885 LLVMContext &Context) {
5886 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5887 BitcodeReader *R = new BitcodeReader(Context);
5889 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5893 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5894 LLVMContext &Context) {
5895 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5896 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
5897 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5898 // written. We must defer until the Module has been fully materialized.
5901 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
5902 LLVMContext &Context) {
5903 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5904 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
5905 ErrorOr<std::string> Triple = R->parseTriple();
5906 if (Triple.getError())
5908 return Triple.get();
5911 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
5912 LLVMContext &Context) {
5913 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5914 BitcodeReader R(Buf.release(), Context);
5915 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5916 if (ProducerString.getError())
5918 return ProducerString.get();
5921 // Parse the specified bitcode buffer, returning the function info index.
5922 // If IsLazy is false, parse the entire function summary into
5923 // the index. Otherwise skip the function summary section, and only create
5924 // an index object with a map from function name to function summary offset.
5925 // The index is used to perform lazy function summary reading later.
5926 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5927 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer,
5928 DiagnosticHandlerFunction DiagnosticHandler,
5930 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5931 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
5933 auto Index = llvm::make_unique<FunctionInfoIndex>();
5935 auto cleanupOnError = [&](std::error_code EC) {
5936 R.releaseBuffer(); // Never take ownership on error.
5940 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5941 return cleanupOnError(EC);
5943 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5944 return std::move(Index);
5947 // Check if the given bitcode buffer contains a function summary block.
5948 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer,
5949 DiagnosticHandlerFunction DiagnosticHandler) {
5950 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5951 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
5953 auto cleanupOnError = [&](std::error_code EC) {
5954 R.releaseBuffer(); // Never take ownership on error.
5958 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5959 return cleanupOnError(EC);
5961 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5962 return R.foundFuncSummary();
5965 // This method supports lazy reading of function summary data from the combined
5966 // index during ThinLTO function importing. When reading the combined index
5967 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5968 // Then this method is called for each function considered for importing,
5969 // to parse the summary information for the given function name into
5971 std::error_code llvm::readFunctionSummary(
5972 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5973 StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) {
5974 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5975 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
5977 auto cleanupOnError = [&](std::error_code EC) {
5978 R.releaseBuffer(); // Never take ownership on error.
5982 // Lookup the given function name in the FunctionMap, which may
5983 // contain a list of function infos in the case of a COMDAT. Walk through
5984 // and parse each function summary info at the function summary offset
5985 // recorded when parsing the value symbol table.
5986 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5987 size_t FunctionSummaryOffset = FI->bitcodeIndex();
5988 if (std::error_code EC =
5989 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5990 return cleanupOnError(EC);
5993 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5994 return std::error_code();