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 {
103 std::vector<TrackingMDRef> MDValuePtrs;
105 LLVMContext &Context;
107 BitcodeReaderMDValueList(LLVMContext &C)
108 : NumFwdRefs(0), AnyFwdRefs(false), SavedFwdRefs(false), Context(C) {}
109 ~BitcodeReaderMDValueList() {
110 // Assert that we either replaced all forward references, or saved
111 // them for later replacement.
112 assert(!NumFwdRefs || SavedFwdRefs);
115 // vector compatibility methods
116 unsigned size() const { return MDValuePtrs.size(); }
117 void resize(unsigned N) { MDValuePtrs.resize(N); }
118 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
119 void clear() { MDValuePtrs.clear(); }
120 Metadata *back() const { return MDValuePtrs.back(); }
121 void pop_back() { MDValuePtrs.pop_back(); }
122 bool empty() const { return MDValuePtrs.empty(); }
124 void savedFwdRefs() { SavedFwdRefs = true; }
126 Metadata *operator[](unsigned i) const {
127 assert(i < MDValuePtrs.size());
128 return MDValuePtrs[i];
131 void shrinkTo(unsigned N) {
132 assert(N <= size() && "Invalid shrinkTo request!");
133 MDValuePtrs.resize(N);
136 Metadata *getValueFwdRef(unsigned Idx);
137 void assignValue(Metadata *MD, unsigned Idx);
138 void tryToResolveCycles();
141 class BitcodeReader : public GVMaterializer {
142 LLVMContext &Context;
143 Module *TheModule = nullptr;
144 std::unique_ptr<MemoryBuffer> Buffer;
145 std::unique_ptr<BitstreamReader> StreamFile;
146 BitstreamCursor Stream;
147 // Next offset to start scanning for lazy parsing of function bodies.
148 uint64_t NextUnreadBit = 0;
149 // Last function offset found in the VST.
150 uint64_t LastFunctionBlockBit = 0;
151 bool SeenValueSymbolTable = false;
152 uint64_t VSTOffset = 0;
153 // Contains an arbitrary and optional string identifying the bitcode producer
154 std::string ProducerIdentification;
155 // Number of module level metadata records specified by the
156 // MODULE_CODE_METADATA_VALUES record.
157 unsigned NumModuleMDs = 0;
158 // Support older bitcode without the MODULE_CODE_METADATA_VALUES record.
159 bool SeenModuleValuesRecord = false;
161 std::vector<Type*> TypeList;
162 BitcodeReaderValueList ValueList;
163 BitcodeReaderMDValueList MDValueList;
164 std::vector<Comdat *> ComdatList;
165 SmallVector<Instruction *, 64> InstructionList;
167 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
168 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
169 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
170 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
171 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
173 SmallVector<Instruction*, 64> InstsWithTBAATag;
175 /// The set of attributes by index. Index zero in the file is for null, and
176 /// is thus not represented here. As such all indices are off by one.
177 std::vector<AttributeSet> MAttributes;
179 /// The set of attribute groups.
180 std::map<unsigned, AttributeSet> MAttributeGroups;
182 /// While parsing a function body, this is a list of the basic blocks for the
184 std::vector<BasicBlock*> FunctionBBs;
186 // When reading the module header, this list is populated with functions that
187 // have bodies later in the file.
188 std::vector<Function*> FunctionsWithBodies;
190 // When intrinsic functions are encountered which require upgrading they are
191 // stored here with their replacement function.
192 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
193 UpgradedIntrinsicMap UpgradedIntrinsics;
195 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
196 DenseMap<unsigned, unsigned> MDKindMap;
198 // Several operations happen after the module header has been read, but
199 // before function bodies are processed. This keeps track of whether
200 // we've done this yet.
201 bool SeenFirstFunctionBody = false;
203 /// When function bodies are initially scanned, this map contains info about
204 /// where to find deferred function body in the stream.
205 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
207 /// When Metadata block is initially scanned when parsing the module, we may
208 /// choose to defer parsing of the metadata. This vector contains info about
209 /// which Metadata blocks are deferred.
210 std::vector<uint64_t> DeferredMetadataInfo;
212 /// These are basic blocks forward-referenced by block addresses. They are
213 /// inserted lazily into functions when they're loaded. The basic block ID is
214 /// its index into the vector.
215 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
216 std::deque<Function *> BasicBlockFwdRefQueue;
218 /// Indicates that we are using a new encoding for instruction operands where
219 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
220 /// instruction number, for a more compact encoding. Some instruction
221 /// operands are not relative to the instruction ID: basic block numbers, and
222 /// types. Once the old style function blocks have been phased out, we would
223 /// not need this flag.
224 bool UseRelativeIDs = false;
226 /// True if all functions will be materialized, negating the need to process
227 /// (e.g.) blockaddress forward references.
228 bool WillMaterializeAllForwardRefs = false;
230 /// Functions that have block addresses taken. This is usually empty.
231 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
233 /// True if any Metadata block has been materialized.
234 bool IsMetadataMaterialized = false;
236 bool StripDebugInfo = false;
238 /// Functions that need to be matched with subprograms when upgrading old
240 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
242 std::vector<std::string> BundleTags;
245 std::error_code error(BitcodeError E, const Twine &Message);
246 std::error_code error(BitcodeError E);
247 std::error_code error(const Twine &Message);
249 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
250 BitcodeReader(LLVMContext &Context);
251 ~BitcodeReader() override { freeState(); }
253 std::error_code materializeForwardReferencedFunctions();
257 void releaseBuffer();
259 bool isDematerializable(const GlobalValue *GV) const override;
260 std::error_code materialize(GlobalValue *GV) override;
261 std::error_code materializeModule(Module *M) override;
262 std::vector<StructType *> getIdentifiedStructTypes() const override;
263 void dematerialize(GlobalValue *GV) override;
265 /// \brief Main interface to parsing a bitcode buffer.
266 /// \returns true if an error occurred.
267 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
269 bool ShouldLazyLoadMetadata = false);
271 /// \brief Cheap mechanism to just extract module triple
272 /// \returns true if an error occurred.
273 ErrorOr<std::string> parseTriple();
275 /// Cheap mechanism to just extract the identification block out of bitcode.
276 ErrorOr<std::string> parseIdentificationBlock();
278 static uint64_t decodeSignRotatedValue(uint64_t V);
280 /// Materialize any deferred Metadata block.
281 std::error_code materializeMetadata() override;
283 void setStripDebugInfo() override;
285 /// Save the mapping between the metadata values and the corresponding
286 /// value id that were recorded in the MDValueList during parsing. If
287 /// OnlyTempMD is true, then only record those entries that are still
288 /// temporary metadata. This interface is used when metadata linking is
289 /// performed as a postpass, such as during function importing.
290 void saveMDValueList(DenseMap<const Metadata *, unsigned> &MDValueToValIDMap,
291 bool OnlyTempMD) override;
294 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
295 // ProducerIdentification data member, and do some basic enforcement on the
296 // "epoch" encoded in the bitcode.
297 std::error_code parseBitcodeVersion();
299 std::vector<StructType *> IdentifiedStructTypes;
300 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
301 StructType *createIdentifiedStructType(LLVMContext &Context);
303 Type *getTypeByID(unsigned ID);
304 Value *getFnValueByID(unsigned ID, Type *Ty) {
305 if (Ty && Ty->isMetadataTy())
306 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
307 return ValueList.getValueFwdRef(ID, Ty);
309 Metadata *getFnMetadataByID(unsigned ID) {
310 return MDValueList.getValueFwdRef(ID);
312 BasicBlock *getBasicBlock(unsigned ID) const {
313 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
314 return FunctionBBs[ID];
316 AttributeSet getAttributes(unsigned i) const {
317 if (i-1 < MAttributes.size())
318 return MAttributes[i-1];
319 return AttributeSet();
322 /// Read a value/type pair out of the specified record from slot 'Slot'.
323 /// Increment Slot past the number of slots used in the record. Return true on
325 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
326 unsigned InstNum, Value *&ResVal) {
327 if (Slot == Record.size()) return true;
328 unsigned ValNo = (unsigned)Record[Slot++];
329 // Adjust the ValNo, if it was encoded relative to the InstNum.
331 ValNo = InstNum - ValNo;
332 if (ValNo < InstNum) {
333 // If this is not a forward reference, just return the value we already
335 ResVal = getFnValueByID(ValNo, nullptr);
336 return ResVal == nullptr;
338 if (Slot == Record.size())
341 unsigned TypeNo = (unsigned)Record[Slot++];
342 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
343 return ResVal == nullptr;
346 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
347 /// past the number of slots used by the value in the record. Return true if
348 /// there is an error.
349 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
350 unsigned InstNum, Type *Ty, Value *&ResVal) {
351 if (getValue(Record, Slot, InstNum, Ty, ResVal))
353 // All values currently take a single record slot.
358 /// Like popValue, but does not increment the Slot number.
359 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
360 unsigned InstNum, Type *Ty, Value *&ResVal) {
361 ResVal = getValue(Record, Slot, InstNum, Ty);
362 return ResVal == nullptr;
365 /// Version of getValue that returns ResVal directly, or 0 if there is an
367 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
368 unsigned InstNum, Type *Ty) {
369 if (Slot == Record.size()) return nullptr;
370 unsigned ValNo = (unsigned)Record[Slot];
371 // Adjust the ValNo, if it was encoded relative to the InstNum.
373 ValNo = InstNum - ValNo;
374 return getFnValueByID(ValNo, Ty);
377 /// Like getValue, but decodes signed VBRs.
378 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
379 unsigned InstNum, Type *Ty) {
380 if (Slot == Record.size()) return nullptr;
381 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
382 // Adjust the ValNo, if it was encoded relative to the InstNum.
384 ValNo = InstNum - ValNo;
385 return getFnValueByID(ValNo, Ty);
388 /// Converts alignment exponent (i.e. power of two (or zero)) to the
389 /// corresponding alignment to use. If alignment is too large, returns
390 /// a corresponding error code.
391 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
392 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
393 std::error_code parseModule(uint64_t ResumeBit,
394 bool ShouldLazyLoadMetadata = false);
395 std::error_code parseAttributeBlock();
396 std::error_code parseAttributeGroupBlock();
397 std::error_code parseTypeTable();
398 std::error_code parseTypeTableBody();
399 std::error_code parseOperandBundleTags();
401 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
402 unsigned NameIndex, Triple &TT);
403 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
404 std::error_code parseConstants();
405 std::error_code rememberAndSkipFunctionBodies();
406 std::error_code rememberAndSkipFunctionBody();
407 /// Save the positions of the Metadata blocks and skip parsing the blocks.
408 std::error_code rememberAndSkipMetadata();
409 std::error_code parseFunctionBody(Function *F);
410 std::error_code globalCleanup();
411 std::error_code resolveGlobalAndAliasInits();
412 std::error_code parseMetadata(bool ModuleLevel = false);
413 std::error_code parseMetadataKinds();
414 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
415 std::error_code parseMetadataAttachment(Function &F);
416 ErrorOr<std::string> parseModuleTriple();
417 std::error_code parseUseLists();
418 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
419 std::error_code initStreamFromBuffer();
420 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
421 std::error_code findFunctionInStream(
423 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
426 /// Class to manage reading and parsing function summary index bitcode
428 class FunctionIndexBitcodeReader {
429 DiagnosticHandlerFunction DiagnosticHandler;
431 /// Eventually points to the function index built during parsing.
432 FunctionInfoIndex *TheIndex = nullptr;
434 std::unique_ptr<MemoryBuffer> Buffer;
435 std::unique_ptr<BitstreamReader> StreamFile;
436 BitstreamCursor Stream;
438 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
440 /// If false, the summary section is fully parsed into the index during
441 /// the initial parse. Otherwise, if true, the caller is expected to
442 /// invoke \a readFunctionSummary for each summary needed, and the summary
443 /// section is thus parsed lazily.
446 /// Used to indicate whether caller only wants to check for the presence
447 /// of the function summary bitcode section. All blocks are skipped,
448 /// but the SeenFuncSummary boolean is set.
449 bool CheckFuncSummaryPresenceOnly = false;
451 /// Indicates whether we have encountered a function summary section
452 /// yet during parsing, used when checking if file contains function
454 bool SeenFuncSummary = false;
456 /// \brief Map populated during function summary section parsing, and
457 /// consumed during ValueSymbolTable parsing.
459 /// Used to correlate summary records with VST entries. For the per-module
460 /// index this maps the ValueID to the parsed function summary, and
461 /// for the combined index this maps the summary record's bitcode
462 /// offset to the function summary (since in the combined index the
463 /// VST records do not hold value IDs but rather hold the function
464 /// summary record offset).
465 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
467 /// Map populated during module path string table parsing, from the
468 /// module ID to a string reference owned by the index's module
469 /// path string table, used to correlate with combined index function
471 DenseMap<uint64_t, StringRef> ModuleIdMap;
474 std::error_code error(BitcodeError E, const Twine &Message);
475 std::error_code error(BitcodeError E);
476 std::error_code error(const Twine &Message);
478 FunctionIndexBitcodeReader(MemoryBuffer *Buffer,
479 DiagnosticHandlerFunction DiagnosticHandler,
481 bool CheckFuncSummaryPresenceOnly = false);
482 FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler,
484 bool CheckFuncSummaryPresenceOnly = false);
485 ~FunctionIndexBitcodeReader() { freeState(); }
489 void releaseBuffer();
491 /// Check if the parser has encountered a function summary section.
492 bool foundFuncSummary() { return SeenFuncSummary; }
494 /// \brief Main interface to parsing a bitcode buffer.
495 /// \returns true if an error occurred.
496 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
497 FunctionInfoIndex *I);
499 /// \brief Interface for parsing a function summary lazily.
500 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
501 FunctionInfoIndex *I,
502 size_t FunctionSummaryOffset);
505 std::error_code parseModule();
506 std::error_code parseValueSymbolTable();
507 std::error_code parseEntireSummary();
508 std::error_code parseModuleStringTable();
509 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
510 std::error_code initStreamFromBuffer();
511 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
515 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
516 DiagnosticSeverity Severity,
518 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
520 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
522 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
523 std::error_code EC, const Twine &Message) {
524 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
525 DiagnosticHandler(DI);
529 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
530 std::error_code EC) {
531 return error(DiagnosticHandler, EC, EC.message());
534 static std::error_code error(LLVMContext &Context, std::error_code EC,
535 const Twine &Message) {
536 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
540 static std::error_code error(LLVMContext &Context, std::error_code EC) {
541 return error(Context, EC, EC.message());
544 static std::error_code error(LLVMContext &Context, const Twine &Message) {
545 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
549 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
550 if (!ProducerIdentification.empty()) {
551 return ::error(Context, make_error_code(E),
552 Message + " (Producer: '" + ProducerIdentification +
553 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
555 return ::error(Context, make_error_code(E), Message);
558 std::error_code BitcodeReader::error(const Twine &Message) {
559 if (!ProducerIdentification.empty()) {
560 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
561 Message + " (Producer: '" + ProducerIdentification +
562 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
564 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
568 std::error_code BitcodeReader::error(BitcodeError E) {
569 return ::error(Context, make_error_code(E));
572 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
573 : Context(Context), Buffer(Buffer), ValueList(Context),
574 MDValueList(Context) {}
576 BitcodeReader::BitcodeReader(LLVMContext &Context)
577 : Context(Context), Buffer(nullptr), ValueList(Context),
578 MDValueList(Context) {}
580 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
581 if (WillMaterializeAllForwardRefs)
582 return std::error_code();
584 // Prevent recursion.
585 WillMaterializeAllForwardRefs = true;
587 while (!BasicBlockFwdRefQueue.empty()) {
588 Function *F = BasicBlockFwdRefQueue.front();
589 BasicBlockFwdRefQueue.pop_front();
590 assert(F && "Expected valid function");
591 if (!BasicBlockFwdRefs.count(F))
592 // Already materialized.
595 // Check for a function that isn't materializable to prevent an infinite
596 // loop. When parsing a blockaddress stored in a global variable, there
597 // isn't a trivial way to check if a function will have a body without a
598 // linear search through FunctionsWithBodies, so just check it here.
599 if (!F->isMaterializable())
600 return error("Never resolved function from blockaddress");
602 // Try to materialize F.
603 if (std::error_code EC = materialize(F))
606 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
609 WillMaterializeAllForwardRefs = false;
610 return std::error_code();
613 void BitcodeReader::freeState() {
615 std::vector<Type*>().swap(TypeList);
618 std::vector<Comdat *>().swap(ComdatList);
620 std::vector<AttributeSet>().swap(MAttributes);
621 std::vector<BasicBlock*>().swap(FunctionBBs);
622 std::vector<Function*>().swap(FunctionsWithBodies);
623 DeferredFunctionInfo.clear();
624 DeferredMetadataInfo.clear();
627 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
628 BasicBlockFwdRefQueue.clear();
631 //===----------------------------------------------------------------------===//
632 // Helper functions to implement forward reference resolution, etc.
633 //===----------------------------------------------------------------------===//
635 /// Convert a string from a record into an std::string, return true on failure.
636 template <typename StrTy>
637 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
639 if (Idx > Record.size())
642 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
643 Result += (char)Record[i];
647 static bool hasImplicitComdat(size_t Val) {
651 case 1: // Old WeakAnyLinkage
652 case 4: // Old LinkOnceAnyLinkage
653 case 10: // Old WeakODRLinkage
654 case 11: // Old LinkOnceODRLinkage
659 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
661 default: // Map unknown/new linkages to external
663 return GlobalValue::ExternalLinkage;
665 return GlobalValue::AppendingLinkage;
667 return GlobalValue::InternalLinkage;
669 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
671 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
673 return GlobalValue::ExternalWeakLinkage;
675 return GlobalValue::CommonLinkage;
677 return GlobalValue::PrivateLinkage;
679 return GlobalValue::AvailableExternallyLinkage;
681 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
683 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
685 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
686 case 1: // Old value with implicit comdat.
688 return GlobalValue::WeakAnyLinkage;
689 case 10: // Old value with implicit comdat.
691 return GlobalValue::WeakODRLinkage;
692 case 4: // Old value with implicit comdat.
694 return GlobalValue::LinkOnceAnyLinkage;
695 case 11: // Old value with implicit comdat.
697 return GlobalValue::LinkOnceODRLinkage;
701 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
703 default: // Map unknown visibilities to default.
704 case 0: return GlobalValue::DefaultVisibility;
705 case 1: return GlobalValue::HiddenVisibility;
706 case 2: return GlobalValue::ProtectedVisibility;
710 static GlobalValue::DLLStorageClassTypes
711 getDecodedDLLStorageClass(unsigned Val) {
713 default: // Map unknown values to default.
714 case 0: return GlobalValue::DefaultStorageClass;
715 case 1: return GlobalValue::DLLImportStorageClass;
716 case 2: return GlobalValue::DLLExportStorageClass;
720 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
722 case 0: return GlobalVariable::NotThreadLocal;
723 default: // Map unknown non-zero value to general dynamic.
724 case 1: return GlobalVariable::GeneralDynamicTLSModel;
725 case 2: return GlobalVariable::LocalDynamicTLSModel;
726 case 3: return GlobalVariable::InitialExecTLSModel;
727 case 4: return GlobalVariable::LocalExecTLSModel;
731 static int getDecodedCastOpcode(unsigned Val) {
734 case bitc::CAST_TRUNC : return Instruction::Trunc;
735 case bitc::CAST_ZEXT : return Instruction::ZExt;
736 case bitc::CAST_SEXT : return Instruction::SExt;
737 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
738 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
739 case bitc::CAST_UITOFP : return Instruction::UIToFP;
740 case bitc::CAST_SITOFP : return Instruction::SIToFP;
741 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
742 case bitc::CAST_FPEXT : return Instruction::FPExt;
743 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
744 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
745 case bitc::CAST_BITCAST : return Instruction::BitCast;
746 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
750 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
751 bool IsFP = Ty->isFPOrFPVectorTy();
752 // BinOps are only valid for int/fp or vector of int/fp types
753 if (!IsFP && !Ty->isIntOrIntVectorTy())
759 case bitc::BINOP_ADD:
760 return IsFP ? Instruction::FAdd : Instruction::Add;
761 case bitc::BINOP_SUB:
762 return IsFP ? Instruction::FSub : Instruction::Sub;
763 case bitc::BINOP_MUL:
764 return IsFP ? Instruction::FMul : Instruction::Mul;
765 case bitc::BINOP_UDIV:
766 return IsFP ? -1 : Instruction::UDiv;
767 case bitc::BINOP_SDIV:
768 return IsFP ? Instruction::FDiv : Instruction::SDiv;
769 case bitc::BINOP_UREM:
770 return IsFP ? -1 : Instruction::URem;
771 case bitc::BINOP_SREM:
772 return IsFP ? Instruction::FRem : Instruction::SRem;
773 case bitc::BINOP_SHL:
774 return IsFP ? -1 : Instruction::Shl;
775 case bitc::BINOP_LSHR:
776 return IsFP ? -1 : Instruction::LShr;
777 case bitc::BINOP_ASHR:
778 return IsFP ? -1 : Instruction::AShr;
779 case bitc::BINOP_AND:
780 return IsFP ? -1 : Instruction::And;
782 return IsFP ? -1 : Instruction::Or;
783 case bitc::BINOP_XOR:
784 return IsFP ? -1 : Instruction::Xor;
788 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
790 default: return AtomicRMWInst::BAD_BINOP;
791 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
792 case bitc::RMW_ADD: return AtomicRMWInst::Add;
793 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
794 case bitc::RMW_AND: return AtomicRMWInst::And;
795 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
796 case bitc::RMW_OR: return AtomicRMWInst::Or;
797 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
798 case bitc::RMW_MAX: return AtomicRMWInst::Max;
799 case bitc::RMW_MIN: return AtomicRMWInst::Min;
800 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
801 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
805 static AtomicOrdering getDecodedOrdering(unsigned Val) {
807 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
808 case bitc::ORDERING_UNORDERED: return Unordered;
809 case bitc::ORDERING_MONOTONIC: return Monotonic;
810 case bitc::ORDERING_ACQUIRE: return Acquire;
811 case bitc::ORDERING_RELEASE: return Release;
812 case bitc::ORDERING_ACQREL: return AcquireRelease;
813 default: // Map unknown orderings to sequentially-consistent.
814 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
818 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
820 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
821 default: // Map unknown scopes to cross-thread.
822 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
826 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
828 default: // Map unknown selection kinds to any.
829 case bitc::COMDAT_SELECTION_KIND_ANY:
831 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
832 return Comdat::ExactMatch;
833 case bitc::COMDAT_SELECTION_KIND_LARGEST:
834 return Comdat::Largest;
835 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
836 return Comdat::NoDuplicates;
837 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
838 return Comdat::SameSize;
842 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
844 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
845 FMF.setUnsafeAlgebra();
846 if (0 != (Val & FastMathFlags::NoNaNs))
848 if (0 != (Val & FastMathFlags::NoInfs))
850 if (0 != (Val & FastMathFlags::NoSignedZeros))
851 FMF.setNoSignedZeros();
852 if (0 != (Val & FastMathFlags::AllowReciprocal))
853 FMF.setAllowReciprocal();
857 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
859 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
860 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
866 /// \brief A class for maintaining the slot number definition
867 /// as a placeholder for the actual definition for forward constants defs.
868 class ConstantPlaceHolder : public ConstantExpr {
869 void operator=(const ConstantPlaceHolder &) = delete;
872 // allocate space for exactly one operand
873 void *operator new(size_t s) { return User::operator new(s, 1); }
874 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
875 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
876 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
879 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
880 static bool classof(const Value *V) {
881 return isa<ConstantExpr>(V) &&
882 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
885 /// Provide fast operand accessors
886 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
890 // FIXME: can we inherit this from ConstantExpr?
892 struct OperandTraits<ConstantPlaceHolder> :
893 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
895 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
898 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
907 WeakVH &OldV = ValuePtrs[Idx];
913 // Handle constants and non-constants (e.g. instrs) differently for
915 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
916 ResolveConstants.push_back(std::make_pair(PHC, Idx));
919 // If there was a forward reference to this value, replace it.
920 Value *PrevVal = OldV;
921 OldV->replaceAllUsesWith(V);
929 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
934 if (Value *V = ValuePtrs[Idx]) {
935 if (Ty != V->getType())
936 report_fatal_error("Type mismatch in constant table!");
937 return cast<Constant>(V);
940 // Create and return a placeholder, which will later be RAUW'd.
941 Constant *C = new ConstantPlaceHolder(Ty, Context);
946 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
947 // Bail out for a clearly invalid value. This would make us call resize(0)
954 if (Value *V = ValuePtrs[Idx]) {
955 // If the types don't match, it's invalid.
956 if (Ty && Ty != V->getType())
961 // No type specified, must be invalid reference.
962 if (!Ty) return nullptr;
964 // Create and return a placeholder, which will later be RAUW'd.
965 Value *V = new Argument(Ty);
970 /// Once all constants are read, this method bulk resolves any forward
971 /// references. The idea behind this is that we sometimes get constants (such
972 /// as large arrays) which reference *many* forward ref constants. Replacing
973 /// each of these causes a lot of thrashing when building/reuniquing the
974 /// constant. Instead of doing this, we look at all the uses and rewrite all
975 /// the place holders at once for any constant that uses a placeholder.
976 void BitcodeReaderValueList::resolveConstantForwardRefs() {
977 // Sort the values by-pointer so that they are efficient to look up with a
979 std::sort(ResolveConstants.begin(), ResolveConstants.end());
981 SmallVector<Constant*, 64> NewOps;
983 while (!ResolveConstants.empty()) {
984 Value *RealVal = operator[](ResolveConstants.back().second);
985 Constant *Placeholder = ResolveConstants.back().first;
986 ResolveConstants.pop_back();
988 // Loop over all users of the placeholder, updating them to reference the
989 // new value. If they reference more than one placeholder, update them all
991 while (!Placeholder->use_empty()) {
992 auto UI = Placeholder->user_begin();
995 // If the using object isn't uniqued, just update the operands. This
996 // handles instructions and initializers for global variables.
997 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
998 UI.getUse().set(RealVal);
1002 // Otherwise, we have a constant that uses the placeholder. Replace that
1003 // constant with a new constant that has *all* placeholder uses updated.
1004 Constant *UserC = cast<Constant>(U);
1005 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1008 if (!isa<ConstantPlaceHolder>(*I)) {
1009 // Not a placeholder reference.
1011 } else if (*I == Placeholder) {
1012 // Common case is that it just references this one placeholder.
1015 // Otherwise, look up the placeholder in ResolveConstants.
1016 ResolveConstantsTy::iterator It =
1017 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1018 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1020 assert(It != ResolveConstants.end() && It->first == *I);
1021 NewOp = operator[](It->second);
1024 NewOps.push_back(cast<Constant>(NewOp));
1027 // Make the new constant.
1029 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1030 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1031 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1032 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1033 } else if (isa<ConstantVector>(UserC)) {
1034 NewC = ConstantVector::get(NewOps);
1036 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1037 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1040 UserC->replaceAllUsesWith(NewC);
1041 UserC->destroyConstant();
1045 // Update all ValueHandles, they should be the only users at this point.
1046 Placeholder->replaceAllUsesWith(RealVal);
1051 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1052 if (Idx == size()) {
1060 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1066 // If there was a forward reference to this value, replace it.
1067 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1068 PrevMD->replaceAllUsesWith(MD);
1072 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1076 if (Metadata *MD = MDValuePtrs[Idx])
1079 // Track forward refs to be resolved later.
1081 MinFwdRef = std::min(MinFwdRef, Idx);
1082 MaxFwdRef = std::max(MaxFwdRef, Idx);
1085 MinFwdRef = MaxFwdRef = Idx;
1088 // Reset flag to ensure that we save this forward reference if we
1089 // are delaying metadata mapping (e.g. for function importing).
1090 SavedFwdRefs = false;
1092 // Create and return a placeholder, which will later be RAUW'd.
1093 Metadata *MD = MDNode::getTemporary(Context, None).release();
1094 MDValuePtrs[Idx].reset(MD);
1098 void BitcodeReaderMDValueList::tryToResolveCycles() {
1104 // Still forward references... can't resolve cycles.
1107 // Resolve any cycles.
1108 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1109 auto &MD = MDValuePtrs[I];
1110 auto *N = dyn_cast_or_null<MDNode>(MD);
1114 assert(!N->isTemporary() && "Unexpected forward reference");
1118 // Make sure we return early again until there's another forward ref.
1122 Type *BitcodeReader::getTypeByID(unsigned ID) {
1123 // The type table size is always specified correctly.
1124 if (ID >= TypeList.size())
1127 if (Type *Ty = TypeList[ID])
1130 // If we have a forward reference, the only possible case is when it is to a
1131 // named struct. Just create a placeholder for now.
1132 return TypeList[ID] = createIdentifiedStructType(Context);
1135 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1137 auto *Ret = StructType::create(Context, Name);
1138 IdentifiedStructTypes.push_back(Ret);
1142 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1143 auto *Ret = StructType::create(Context);
1144 IdentifiedStructTypes.push_back(Ret);
1149 //===----------------------------------------------------------------------===//
1150 // Functions for parsing blocks from the bitcode file
1151 //===----------------------------------------------------------------------===//
1154 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1155 /// been decoded from the given integer. This function must stay in sync with
1156 /// 'encodeLLVMAttributesForBitcode'.
1157 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1158 uint64_t EncodedAttrs) {
1159 // FIXME: Remove in 4.0.
1161 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1162 // the bits above 31 down by 11 bits.
1163 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1164 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1165 "Alignment must be a power of two.");
1168 B.addAlignmentAttr(Alignment);
1169 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1170 (EncodedAttrs & 0xffff));
1173 std::error_code BitcodeReader::parseAttributeBlock() {
1174 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1175 return error("Invalid record");
1177 if (!MAttributes.empty())
1178 return error("Invalid multiple blocks");
1180 SmallVector<uint64_t, 64> Record;
1182 SmallVector<AttributeSet, 8> Attrs;
1184 // Read all the records.
1186 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1188 switch (Entry.Kind) {
1189 case BitstreamEntry::SubBlock: // Handled for us already.
1190 case BitstreamEntry::Error:
1191 return error("Malformed block");
1192 case BitstreamEntry::EndBlock:
1193 return std::error_code();
1194 case BitstreamEntry::Record:
1195 // The interesting case.
1201 switch (Stream.readRecord(Entry.ID, Record)) {
1202 default: // Default behavior: ignore.
1204 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1205 // FIXME: Remove in 4.0.
1206 if (Record.size() & 1)
1207 return error("Invalid record");
1209 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1211 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1212 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1215 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1219 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1220 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1221 Attrs.push_back(MAttributeGroups[Record[i]]);
1223 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1231 // Returns Attribute::None on unrecognized codes.
1232 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1235 return Attribute::None;
1236 case bitc::ATTR_KIND_ALIGNMENT:
1237 return Attribute::Alignment;
1238 case bitc::ATTR_KIND_ALWAYS_INLINE:
1239 return Attribute::AlwaysInline;
1240 case bitc::ATTR_KIND_ARGMEMONLY:
1241 return Attribute::ArgMemOnly;
1242 case bitc::ATTR_KIND_BUILTIN:
1243 return Attribute::Builtin;
1244 case bitc::ATTR_KIND_BY_VAL:
1245 return Attribute::ByVal;
1246 case bitc::ATTR_KIND_IN_ALLOCA:
1247 return Attribute::InAlloca;
1248 case bitc::ATTR_KIND_COLD:
1249 return Attribute::Cold;
1250 case bitc::ATTR_KIND_CONVERGENT:
1251 return Attribute::Convergent;
1252 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1253 return Attribute::InaccessibleMemOnly;
1254 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1255 return Attribute::InaccessibleMemOrArgMemOnly;
1256 case bitc::ATTR_KIND_INLINE_HINT:
1257 return Attribute::InlineHint;
1258 case bitc::ATTR_KIND_IN_REG:
1259 return Attribute::InReg;
1260 case bitc::ATTR_KIND_JUMP_TABLE:
1261 return Attribute::JumpTable;
1262 case bitc::ATTR_KIND_MIN_SIZE:
1263 return Attribute::MinSize;
1264 case bitc::ATTR_KIND_NAKED:
1265 return Attribute::Naked;
1266 case bitc::ATTR_KIND_NEST:
1267 return Attribute::Nest;
1268 case bitc::ATTR_KIND_NO_ALIAS:
1269 return Attribute::NoAlias;
1270 case bitc::ATTR_KIND_NO_BUILTIN:
1271 return Attribute::NoBuiltin;
1272 case bitc::ATTR_KIND_NO_CAPTURE:
1273 return Attribute::NoCapture;
1274 case bitc::ATTR_KIND_NO_DUPLICATE:
1275 return Attribute::NoDuplicate;
1276 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1277 return Attribute::NoImplicitFloat;
1278 case bitc::ATTR_KIND_NO_INLINE:
1279 return Attribute::NoInline;
1280 case bitc::ATTR_KIND_NO_RECURSE:
1281 return Attribute::NoRecurse;
1282 case bitc::ATTR_KIND_NON_LAZY_BIND:
1283 return Attribute::NonLazyBind;
1284 case bitc::ATTR_KIND_NON_NULL:
1285 return Attribute::NonNull;
1286 case bitc::ATTR_KIND_DEREFERENCEABLE:
1287 return Attribute::Dereferenceable;
1288 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1289 return Attribute::DereferenceableOrNull;
1290 case bitc::ATTR_KIND_NO_RED_ZONE:
1291 return Attribute::NoRedZone;
1292 case bitc::ATTR_KIND_NO_RETURN:
1293 return Attribute::NoReturn;
1294 case bitc::ATTR_KIND_NO_UNWIND:
1295 return Attribute::NoUnwind;
1296 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1297 return Attribute::OptimizeForSize;
1298 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1299 return Attribute::OptimizeNone;
1300 case bitc::ATTR_KIND_READ_NONE:
1301 return Attribute::ReadNone;
1302 case bitc::ATTR_KIND_READ_ONLY:
1303 return Attribute::ReadOnly;
1304 case bitc::ATTR_KIND_RETURNED:
1305 return Attribute::Returned;
1306 case bitc::ATTR_KIND_RETURNS_TWICE:
1307 return Attribute::ReturnsTwice;
1308 case bitc::ATTR_KIND_S_EXT:
1309 return Attribute::SExt;
1310 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1311 return Attribute::StackAlignment;
1312 case bitc::ATTR_KIND_STACK_PROTECT:
1313 return Attribute::StackProtect;
1314 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1315 return Attribute::StackProtectReq;
1316 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1317 return Attribute::StackProtectStrong;
1318 case bitc::ATTR_KIND_SAFESTACK:
1319 return Attribute::SafeStack;
1320 case bitc::ATTR_KIND_STRUCT_RET:
1321 return Attribute::StructRet;
1322 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1323 return Attribute::SanitizeAddress;
1324 case bitc::ATTR_KIND_SANITIZE_THREAD:
1325 return Attribute::SanitizeThread;
1326 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1327 return Attribute::SanitizeMemory;
1328 case bitc::ATTR_KIND_UW_TABLE:
1329 return Attribute::UWTable;
1330 case bitc::ATTR_KIND_Z_EXT:
1331 return Attribute::ZExt;
1335 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1336 unsigned &Alignment) {
1337 // Note: Alignment in bitcode files is incremented by 1, so that zero
1338 // can be used for default alignment.
1339 if (Exponent > Value::MaxAlignmentExponent + 1)
1340 return error("Invalid alignment value");
1341 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1342 return std::error_code();
1345 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1346 Attribute::AttrKind *Kind) {
1347 *Kind = getAttrFromCode(Code);
1348 if (*Kind == Attribute::None)
1349 return error(BitcodeError::CorruptedBitcode,
1350 "Unknown attribute kind (" + Twine(Code) + ")");
1351 return std::error_code();
1354 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1355 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1356 return error("Invalid record");
1358 if (!MAttributeGroups.empty())
1359 return error("Invalid multiple blocks");
1361 SmallVector<uint64_t, 64> Record;
1363 // Read all the records.
1365 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1367 switch (Entry.Kind) {
1368 case BitstreamEntry::SubBlock: // Handled for us already.
1369 case BitstreamEntry::Error:
1370 return error("Malformed block");
1371 case BitstreamEntry::EndBlock:
1372 return std::error_code();
1373 case BitstreamEntry::Record:
1374 // The interesting case.
1380 switch (Stream.readRecord(Entry.ID, Record)) {
1381 default: // Default behavior: ignore.
1383 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1384 if (Record.size() < 3)
1385 return error("Invalid record");
1387 uint64_t GrpID = Record[0];
1388 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1391 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1392 if (Record[i] == 0) { // Enum attribute
1393 Attribute::AttrKind Kind;
1394 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1397 B.addAttribute(Kind);
1398 } else if (Record[i] == 1) { // Integer attribute
1399 Attribute::AttrKind Kind;
1400 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1402 if (Kind == Attribute::Alignment)
1403 B.addAlignmentAttr(Record[++i]);
1404 else if (Kind == Attribute::StackAlignment)
1405 B.addStackAlignmentAttr(Record[++i]);
1406 else if (Kind == Attribute::Dereferenceable)
1407 B.addDereferenceableAttr(Record[++i]);
1408 else if (Kind == Attribute::DereferenceableOrNull)
1409 B.addDereferenceableOrNullAttr(Record[++i]);
1410 } else { // String attribute
1411 assert((Record[i] == 3 || Record[i] == 4) &&
1412 "Invalid attribute group entry");
1413 bool HasValue = (Record[i++] == 4);
1414 SmallString<64> KindStr;
1415 SmallString<64> ValStr;
1417 while (Record[i] != 0 && i != e)
1418 KindStr += Record[i++];
1419 assert(Record[i] == 0 && "Kind string not null terminated");
1422 // Has a value associated with it.
1423 ++i; // Skip the '0' that terminates the "kind" string.
1424 while (Record[i] != 0 && i != e)
1425 ValStr += Record[i++];
1426 assert(Record[i] == 0 && "Value string not null terminated");
1429 B.addAttribute(KindStr.str(), ValStr.str());
1433 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1440 std::error_code BitcodeReader::parseTypeTable() {
1441 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1442 return error("Invalid record");
1444 return parseTypeTableBody();
1447 std::error_code BitcodeReader::parseTypeTableBody() {
1448 if (!TypeList.empty())
1449 return error("Invalid multiple blocks");
1451 SmallVector<uint64_t, 64> Record;
1452 unsigned NumRecords = 0;
1454 SmallString<64> TypeName;
1456 // Read all the records for this type table.
1458 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1460 switch (Entry.Kind) {
1461 case BitstreamEntry::SubBlock: // Handled for us already.
1462 case BitstreamEntry::Error:
1463 return error("Malformed block");
1464 case BitstreamEntry::EndBlock:
1465 if (NumRecords != TypeList.size())
1466 return error("Malformed block");
1467 return std::error_code();
1468 case BitstreamEntry::Record:
1469 // The interesting case.
1475 Type *ResultTy = nullptr;
1476 switch (Stream.readRecord(Entry.ID, Record)) {
1478 return error("Invalid value");
1479 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1480 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1481 // type list. This allows us to reserve space.
1482 if (Record.size() < 1)
1483 return error("Invalid record");
1484 TypeList.resize(Record[0]);
1486 case bitc::TYPE_CODE_VOID: // VOID
1487 ResultTy = Type::getVoidTy(Context);
1489 case bitc::TYPE_CODE_HALF: // HALF
1490 ResultTy = Type::getHalfTy(Context);
1492 case bitc::TYPE_CODE_FLOAT: // FLOAT
1493 ResultTy = Type::getFloatTy(Context);
1495 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1496 ResultTy = Type::getDoubleTy(Context);
1498 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1499 ResultTy = Type::getX86_FP80Ty(Context);
1501 case bitc::TYPE_CODE_FP128: // FP128
1502 ResultTy = Type::getFP128Ty(Context);
1504 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1505 ResultTy = Type::getPPC_FP128Ty(Context);
1507 case bitc::TYPE_CODE_LABEL: // LABEL
1508 ResultTy = Type::getLabelTy(Context);
1510 case bitc::TYPE_CODE_METADATA: // METADATA
1511 ResultTy = Type::getMetadataTy(Context);
1513 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1514 ResultTy = Type::getX86_MMXTy(Context);
1516 case bitc::TYPE_CODE_TOKEN: // TOKEN
1517 ResultTy = Type::getTokenTy(Context);
1519 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1520 if (Record.size() < 1)
1521 return error("Invalid record");
1523 uint64_t NumBits = Record[0];
1524 if (NumBits < IntegerType::MIN_INT_BITS ||
1525 NumBits > IntegerType::MAX_INT_BITS)
1526 return error("Bitwidth for integer type out of range");
1527 ResultTy = IntegerType::get(Context, NumBits);
1530 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1531 // [pointee type, address space]
1532 if (Record.size() < 1)
1533 return error("Invalid record");
1534 unsigned AddressSpace = 0;
1535 if (Record.size() == 2)
1536 AddressSpace = Record[1];
1537 ResultTy = getTypeByID(Record[0]);
1539 !PointerType::isValidElementType(ResultTy))
1540 return error("Invalid type");
1541 ResultTy = PointerType::get(ResultTy, AddressSpace);
1544 case bitc::TYPE_CODE_FUNCTION_OLD: {
1545 // FIXME: attrid is dead, remove it in LLVM 4.0
1546 // FUNCTION: [vararg, attrid, retty, paramty x N]
1547 if (Record.size() < 3)
1548 return error("Invalid record");
1549 SmallVector<Type*, 8> ArgTys;
1550 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1551 if (Type *T = getTypeByID(Record[i]))
1552 ArgTys.push_back(T);
1557 ResultTy = getTypeByID(Record[2]);
1558 if (!ResultTy || ArgTys.size() < Record.size()-3)
1559 return error("Invalid type");
1561 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1564 case bitc::TYPE_CODE_FUNCTION: {
1565 // FUNCTION: [vararg, retty, paramty x N]
1566 if (Record.size() < 2)
1567 return error("Invalid record");
1568 SmallVector<Type*, 8> ArgTys;
1569 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1570 if (Type *T = getTypeByID(Record[i])) {
1571 if (!FunctionType::isValidArgumentType(T))
1572 return error("Invalid function argument type");
1573 ArgTys.push_back(T);
1579 ResultTy = getTypeByID(Record[1]);
1580 if (!ResultTy || ArgTys.size() < Record.size()-2)
1581 return error("Invalid type");
1583 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1586 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1587 if (Record.size() < 1)
1588 return error("Invalid record");
1589 SmallVector<Type*, 8> EltTys;
1590 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1591 if (Type *T = getTypeByID(Record[i]))
1592 EltTys.push_back(T);
1596 if (EltTys.size() != Record.size()-1)
1597 return error("Invalid type");
1598 ResultTy = StructType::get(Context, EltTys, Record[0]);
1601 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1602 if (convertToString(Record, 0, TypeName))
1603 return error("Invalid record");
1606 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1607 if (Record.size() < 1)
1608 return error("Invalid record");
1610 if (NumRecords >= TypeList.size())
1611 return error("Invalid TYPE table");
1613 // Check to see if this was forward referenced, if so fill in the temp.
1614 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1616 Res->setName(TypeName);
1617 TypeList[NumRecords] = nullptr;
1618 } else // Otherwise, create a new struct.
1619 Res = createIdentifiedStructType(Context, TypeName);
1622 SmallVector<Type*, 8> EltTys;
1623 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1624 if (Type *T = getTypeByID(Record[i]))
1625 EltTys.push_back(T);
1629 if (EltTys.size() != Record.size()-1)
1630 return error("Invalid record");
1631 Res->setBody(EltTys, Record[0]);
1635 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1636 if (Record.size() != 1)
1637 return error("Invalid record");
1639 if (NumRecords >= TypeList.size())
1640 return error("Invalid TYPE table");
1642 // Check to see if this was forward referenced, if so fill in the temp.
1643 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1645 Res->setName(TypeName);
1646 TypeList[NumRecords] = nullptr;
1647 } else // Otherwise, create a new struct with no body.
1648 Res = createIdentifiedStructType(Context, TypeName);
1653 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1654 if (Record.size() < 2)
1655 return error("Invalid record");
1656 ResultTy = getTypeByID(Record[1]);
1657 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1658 return error("Invalid type");
1659 ResultTy = ArrayType::get(ResultTy, Record[0]);
1661 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1662 if (Record.size() < 2)
1663 return error("Invalid record");
1665 return error("Invalid vector length");
1666 ResultTy = getTypeByID(Record[1]);
1667 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1668 return error("Invalid type");
1669 ResultTy = VectorType::get(ResultTy, Record[0]);
1673 if (NumRecords >= TypeList.size())
1674 return error("Invalid TYPE table");
1675 if (TypeList[NumRecords])
1677 "Invalid TYPE table: Only named structs can be forward referenced");
1678 assert(ResultTy && "Didn't read a type?");
1679 TypeList[NumRecords++] = ResultTy;
1683 std::error_code BitcodeReader::parseOperandBundleTags() {
1684 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1685 return error("Invalid record");
1687 if (!BundleTags.empty())
1688 return error("Invalid multiple blocks");
1690 SmallVector<uint64_t, 64> Record;
1693 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1695 switch (Entry.Kind) {
1696 case BitstreamEntry::SubBlock: // Handled for us already.
1697 case BitstreamEntry::Error:
1698 return error("Malformed block");
1699 case BitstreamEntry::EndBlock:
1700 return std::error_code();
1701 case BitstreamEntry::Record:
1702 // The interesting case.
1706 // Tags are implicitly mapped to integers by their order.
1708 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1709 return error("Invalid record");
1711 // OPERAND_BUNDLE_TAG: [strchr x N]
1712 BundleTags.emplace_back();
1713 if (convertToString(Record, 0, BundleTags.back()))
1714 return error("Invalid record");
1719 /// Associate a value with its name from the given index in the provided record.
1720 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1721 unsigned NameIndex, Triple &TT) {
1722 SmallString<128> ValueName;
1723 if (convertToString(Record, NameIndex, ValueName))
1724 return error("Invalid record");
1725 unsigned ValueID = Record[0];
1726 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1727 return error("Invalid record");
1728 Value *V = ValueList[ValueID];
1730 StringRef NameStr(ValueName.data(), ValueName.size());
1731 if (NameStr.find_first_of(0) != StringRef::npos)
1732 return error("Invalid value name");
1733 V->setName(NameStr);
1734 auto *GO = dyn_cast<GlobalObject>(V);
1736 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1737 if (TT.isOSBinFormatMachO())
1738 GO->setComdat(nullptr);
1740 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1746 /// Parse the value symbol table at either the current parsing location or
1747 /// at the given bit offset if provided.
1748 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1749 uint64_t CurrentBit;
1750 // Pass in the Offset to distinguish between calling for the module-level
1751 // VST (where we want to jump to the VST offset) and the function-level
1752 // VST (where we don't).
1754 // Save the current parsing location so we can jump back at the end
1756 CurrentBit = Stream.GetCurrentBitNo();
1757 Stream.JumpToBit(Offset * 32);
1759 // Do some checking if we are in debug mode.
1760 BitstreamEntry Entry = Stream.advance();
1761 assert(Entry.Kind == BitstreamEntry::SubBlock);
1762 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1764 // In NDEBUG mode ignore the output so we don't get an unused variable
1770 // Compute the delta between the bitcode indices in the VST (the word offset
1771 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1772 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1773 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1774 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1775 // just before entering the VST subblock because: 1) the EnterSubBlock
1776 // changes the AbbrevID width; 2) the VST block is nested within the same
1777 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1778 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1779 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1780 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1781 unsigned FuncBitcodeOffsetDelta =
1782 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1784 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1785 return error("Invalid record");
1787 SmallVector<uint64_t, 64> Record;
1789 Triple TT(TheModule->getTargetTriple());
1791 // Read all the records for this value table.
1792 SmallString<128> ValueName;
1794 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1796 switch (Entry.Kind) {
1797 case BitstreamEntry::SubBlock: // Handled for us already.
1798 case BitstreamEntry::Error:
1799 return error("Malformed block");
1800 case BitstreamEntry::EndBlock:
1802 Stream.JumpToBit(CurrentBit);
1803 return std::error_code();
1804 case BitstreamEntry::Record:
1805 // The interesting case.
1811 switch (Stream.readRecord(Entry.ID, Record)) {
1812 default: // Default behavior: unknown type.
1814 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1815 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1816 if (std::error_code EC = ValOrErr.getError())
1821 case bitc::VST_CODE_FNENTRY: {
1822 // VST_FNENTRY: [valueid, offset, namechar x N]
1823 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1824 if (std::error_code EC = ValOrErr.getError())
1826 Value *V = ValOrErr.get();
1828 auto *GO = dyn_cast<GlobalObject>(V);
1830 // If this is an alias, need to get the actual Function object
1831 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1832 auto *GA = dyn_cast<GlobalAlias>(V);
1834 GO = GA->getBaseObject();
1838 uint64_t FuncWordOffset = Record[1];
1839 Function *F = dyn_cast<Function>(GO);
1841 uint64_t FuncBitOffset = FuncWordOffset * 32;
1842 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1843 // Set the LastFunctionBlockBit to point to the last function block.
1844 // Later when parsing is resumed after function materialization,
1845 // we can simply skip that last function block.
1846 if (FuncBitOffset > LastFunctionBlockBit)
1847 LastFunctionBlockBit = FuncBitOffset;
1850 case bitc::VST_CODE_BBENTRY: {
1851 if (convertToString(Record, 1, ValueName))
1852 return error("Invalid record");
1853 BasicBlock *BB = getBasicBlock(Record[0]);
1855 return error("Invalid record");
1857 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1865 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1867 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1868 if (Record.size() < 2)
1869 return error("Invalid record");
1871 unsigned Kind = Record[0];
1872 SmallString<8> Name(Record.begin() + 1, Record.end());
1874 unsigned NewKind = TheModule->getMDKindID(Name.str());
1875 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1876 return error("Conflicting METADATA_KIND records");
1877 return std::error_code();
1880 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1882 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1883 /// module level metadata.
1884 std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
1885 IsMetadataMaterialized = true;
1886 unsigned NextMDValueNo = MDValueList.size();
1887 if (ModuleLevel && SeenModuleValuesRecord) {
1888 // Now that we are parsing the module level metadata, we want to restart
1889 // the numbering of the MD values, and replace temp MD created earlier
1890 // with their real values. If we saw a METADATA_VALUE record then we
1891 // would have set the MDValueList size to the number specified in that
1892 // record, to support parsing function-level metadata first, and we need
1893 // to reset back to 0 to fill the MDValueList in with the parsed module
1894 // The function-level metadata parsing should have reset the MDValueList
1895 // size back to the value reported by the METADATA_VALUE record, saved in
1897 assert(NumModuleMDs == MDValueList.size() &&
1898 "Expected MDValueList to only contain module level values");
1902 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1903 return error("Invalid record");
1905 SmallVector<uint64_t, 64> Record;
1908 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1909 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1911 return getMD(ID - 1);
1914 auto getMDString = [&](unsigned ID) -> MDString *{
1915 // This requires that the ID is not really a forward reference. In
1916 // particular, the MDString must already have been resolved.
1917 return cast_or_null<MDString>(getMDOrNull(ID));
1920 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1921 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1923 // Read all the records.
1925 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1927 switch (Entry.Kind) {
1928 case BitstreamEntry::SubBlock: // Handled for us already.
1929 case BitstreamEntry::Error:
1930 return error("Malformed block");
1931 case BitstreamEntry::EndBlock:
1932 MDValueList.tryToResolveCycles();
1933 assert((!(ModuleLevel && SeenModuleValuesRecord) ||
1934 NumModuleMDs == MDValueList.size()) &&
1935 "Inconsistent bitcode: METADATA_VALUES mismatch");
1936 return std::error_code();
1937 case BitstreamEntry::Record:
1938 // The interesting case.
1944 unsigned Code = Stream.readRecord(Entry.ID, Record);
1945 bool IsDistinct = false;
1947 default: // Default behavior: ignore.
1949 case bitc::METADATA_NAME: {
1950 // Read name of the named metadata.
1951 SmallString<8> Name(Record.begin(), Record.end());
1953 Code = Stream.ReadCode();
1955 unsigned NextBitCode = Stream.readRecord(Code, Record);
1956 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1957 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1959 // Read named metadata elements.
1960 unsigned Size = Record.size();
1961 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1962 for (unsigned i = 0; i != Size; ++i) {
1963 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1965 return error("Invalid record");
1966 NMD->addOperand(MD);
1970 case bitc::METADATA_OLD_FN_NODE: {
1971 // FIXME: Remove in 4.0.
1972 // This is a LocalAsMetadata record, the only type of function-local
1974 if (Record.size() % 2 == 1)
1975 return error("Invalid record");
1977 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1978 // to be legal, but there's no upgrade path.
1979 auto dropRecord = [&] {
1980 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1982 if (Record.size() != 2) {
1987 Type *Ty = getTypeByID(Record[0]);
1988 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1993 MDValueList.assignValue(
1994 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1998 case bitc::METADATA_OLD_NODE: {
1999 // FIXME: Remove in 4.0.
2000 if (Record.size() % 2 == 1)
2001 return error("Invalid record");
2003 unsigned Size = Record.size();
2004 SmallVector<Metadata *, 8> Elts;
2005 for (unsigned i = 0; i != Size; i += 2) {
2006 Type *Ty = getTypeByID(Record[i]);
2008 return error("Invalid record");
2009 if (Ty->isMetadataTy())
2010 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
2011 else if (!Ty->isVoidTy()) {
2013 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2014 assert(isa<ConstantAsMetadata>(MD) &&
2015 "Expected non-function-local metadata");
2018 Elts.push_back(nullptr);
2020 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2023 case bitc::METADATA_VALUE: {
2024 if (Record.size() != 2)
2025 return error("Invalid record");
2027 Type *Ty = getTypeByID(Record[0]);
2028 if (Ty->isMetadataTy() || Ty->isVoidTy())
2029 return error("Invalid record");
2031 MDValueList.assignValue(
2032 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2036 case bitc::METADATA_DISTINCT_NODE:
2039 case bitc::METADATA_NODE: {
2040 SmallVector<Metadata *, 8> Elts;
2041 Elts.reserve(Record.size());
2042 for (unsigned ID : Record)
2043 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2044 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2045 : MDNode::get(Context, Elts),
2049 case bitc::METADATA_LOCATION: {
2050 if (Record.size() != 5)
2051 return error("Invalid record");
2053 unsigned Line = Record[1];
2054 unsigned Column = Record[2];
2055 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2056 Metadata *InlinedAt =
2057 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2058 MDValueList.assignValue(
2059 GET_OR_DISTINCT(DILocation, Record[0],
2060 (Context, Line, Column, Scope, InlinedAt)),
2064 case bitc::METADATA_GENERIC_DEBUG: {
2065 if (Record.size() < 4)
2066 return error("Invalid record");
2068 unsigned Tag = Record[1];
2069 unsigned Version = Record[2];
2071 if (Tag >= 1u << 16 || Version != 0)
2072 return error("Invalid record");
2074 auto *Header = getMDString(Record[3]);
2075 SmallVector<Metadata *, 8> DwarfOps;
2076 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2077 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2079 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2080 (Context, Tag, Header, DwarfOps)),
2084 case bitc::METADATA_SUBRANGE: {
2085 if (Record.size() != 3)
2086 return error("Invalid record");
2088 MDValueList.assignValue(
2089 GET_OR_DISTINCT(DISubrange, Record[0],
2090 (Context, Record[1], unrotateSign(Record[2]))),
2094 case bitc::METADATA_ENUMERATOR: {
2095 if (Record.size() != 3)
2096 return error("Invalid record");
2098 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2099 (Context, unrotateSign(Record[1]),
2100 getMDString(Record[2]))),
2104 case bitc::METADATA_BASIC_TYPE: {
2105 if (Record.size() != 6)
2106 return error("Invalid record");
2108 MDValueList.assignValue(
2109 GET_OR_DISTINCT(DIBasicType, Record[0],
2110 (Context, Record[1], getMDString(Record[2]),
2111 Record[3], Record[4], Record[5])),
2115 case bitc::METADATA_DERIVED_TYPE: {
2116 if (Record.size() != 12)
2117 return error("Invalid record");
2119 MDValueList.assignValue(
2120 GET_OR_DISTINCT(DIDerivedType, Record[0],
2121 (Context, Record[1], getMDString(Record[2]),
2122 getMDOrNull(Record[3]), Record[4],
2123 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2124 Record[7], Record[8], Record[9], Record[10],
2125 getMDOrNull(Record[11]))),
2129 case bitc::METADATA_COMPOSITE_TYPE: {
2130 if (Record.size() != 16)
2131 return error("Invalid record");
2133 MDValueList.assignValue(
2134 GET_OR_DISTINCT(DICompositeType, Record[0],
2135 (Context, Record[1], getMDString(Record[2]),
2136 getMDOrNull(Record[3]), Record[4],
2137 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2138 Record[7], Record[8], Record[9], Record[10],
2139 getMDOrNull(Record[11]), Record[12],
2140 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2141 getMDString(Record[15]))),
2145 case bitc::METADATA_SUBROUTINE_TYPE: {
2146 if (Record.size() != 3)
2147 return error("Invalid record");
2149 MDValueList.assignValue(
2150 GET_OR_DISTINCT(DISubroutineType, Record[0],
2151 (Context, Record[1], getMDOrNull(Record[2]))),
2156 case bitc::METADATA_MODULE: {
2157 if (Record.size() != 6)
2158 return error("Invalid record");
2160 MDValueList.assignValue(
2161 GET_OR_DISTINCT(DIModule, Record[0],
2162 (Context, getMDOrNull(Record[1]),
2163 getMDString(Record[2]), getMDString(Record[3]),
2164 getMDString(Record[4]), getMDString(Record[5]))),
2169 case bitc::METADATA_FILE: {
2170 if (Record.size() != 3)
2171 return error("Invalid record");
2173 MDValueList.assignValue(
2174 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2175 getMDString(Record[2]))),
2179 case bitc::METADATA_COMPILE_UNIT: {
2180 if (Record.size() < 14 || Record.size() > 16)
2181 return error("Invalid record");
2183 // Ignore Record[0], which indicates whether this compile unit is
2184 // distinct. It's always distinct.
2185 MDValueList.assignValue(
2186 DICompileUnit::getDistinct(
2187 Context, Record[1], getMDOrNull(Record[2]),
2188 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2189 Record[6], getMDString(Record[7]), Record[8],
2190 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2191 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2192 getMDOrNull(Record[13]),
2193 Record.size() <= 15 ? 0 : getMDOrNull(Record[15]),
2194 Record.size() <= 14 ? 0 : Record[14]),
2198 case bitc::METADATA_SUBPROGRAM: {
2199 if (Record.size() != 18 && Record.size() != 19)
2200 return error("Invalid record");
2202 bool HasFn = Record.size() == 19;
2203 DISubprogram *SP = GET_OR_DISTINCT(
2205 Record[0] || Record[8], // All definitions should be distinct.
2206 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2207 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2208 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2209 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2210 Record[14], getMDOrNull(Record[15 + HasFn]),
2211 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2212 MDValueList.assignValue(SP, NextMDValueNo++);
2214 // Upgrade sp->function mapping to function->sp mapping.
2215 if (HasFn && Record[15]) {
2216 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2217 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2218 if (F->isMaterializable())
2219 // Defer until materialized; unmaterialized functions may not have
2221 FunctionsWithSPs[F] = SP;
2222 else if (!F->empty())
2223 F->setSubprogram(SP);
2228 case bitc::METADATA_LEXICAL_BLOCK: {
2229 if (Record.size() != 5)
2230 return error("Invalid record");
2232 MDValueList.assignValue(
2233 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2234 (Context, getMDOrNull(Record[1]),
2235 getMDOrNull(Record[2]), Record[3], Record[4])),
2239 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2240 if (Record.size() != 4)
2241 return error("Invalid record");
2243 MDValueList.assignValue(
2244 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2245 (Context, getMDOrNull(Record[1]),
2246 getMDOrNull(Record[2]), Record[3])),
2250 case bitc::METADATA_NAMESPACE: {
2251 if (Record.size() != 5)
2252 return error("Invalid record");
2254 MDValueList.assignValue(
2255 GET_OR_DISTINCT(DINamespace, Record[0],
2256 (Context, getMDOrNull(Record[1]),
2257 getMDOrNull(Record[2]), getMDString(Record[3]),
2262 case bitc::METADATA_MACRO: {
2263 if (Record.size() != 5)
2264 return error("Invalid record");
2266 MDValueList.assignValue(
2267 GET_OR_DISTINCT(DIMacro, Record[0],
2268 (Context, Record[1], Record[2],
2269 getMDString(Record[3]), getMDString(Record[4]))),
2273 case bitc::METADATA_MACRO_FILE: {
2274 if (Record.size() != 5)
2275 return error("Invalid record");
2277 MDValueList.assignValue(
2278 GET_OR_DISTINCT(DIMacroFile, Record[0],
2279 (Context, Record[1], Record[2],
2280 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2284 case bitc::METADATA_TEMPLATE_TYPE: {
2285 if (Record.size() != 3)
2286 return error("Invalid record");
2288 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2290 (Context, getMDString(Record[1]),
2291 getMDOrNull(Record[2]))),
2295 case bitc::METADATA_TEMPLATE_VALUE: {
2296 if (Record.size() != 5)
2297 return error("Invalid record");
2299 MDValueList.assignValue(
2300 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2301 (Context, Record[1], getMDString(Record[2]),
2302 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2306 case bitc::METADATA_GLOBAL_VAR: {
2307 if (Record.size() != 11)
2308 return error("Invalid record");
2310 MDValueList.assignValue(
2311 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2312 (Context, getMDOrNull(Record[1]),
2313 getMDString(Record[2]), getMDString(Record[3]),
2314 getMDOrNull(Record[4]), Record[5],
2315 getMDOrNull(Record[6]), Record[7], Record[8],
2316 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2320 case bitc::METADATA_LOCAL_VAR: {
2321 // 10th field is for the obseleted 'inlinedAt:' field.
2322 if (Record.size() < 8 || Record.size() > 10)
2323 return error("Invalid record");
2325 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2326 // DW_TAG_arg_variable.
2327 bool HasTag = Record.size() > 8;
2328 MDValueList.assignValue(
2329 GET_OR_DISTINCT(DILocalVariable, Record[0],
2330 (Context, getMDOrNull(Record[1 + HasTag]),
2331 getMDString(Record[2 + HasTag]),
2332 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2333 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2334 Record[7 + HasTag])),
2338 case bitc::METADATA_EXPRESSION: {
2339 if (Record.size() < 1)
2340 return error("Invalid record");
2342 MDValueList.assignValue(
2343 GET_OR_DISTINCT(DIExpression, Record[0],
2344 (Context, makeArrayRef(Record).slice(1))),
2348 case bitc::METADATA_OBJC_PROPERTY: {
2349 if (Record.size() != 8)
2350 return error("Invalid record");
2352 MDValueList.assignValue(
2353 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2354 (Context, getMDString(Record[1]),
2355 getMDOrNull(Record[2]), Record[3],
2356 getMDString(Record[4]), getMDString(Record[5]),
2357 Record[6], getMDOrNull(Record[7]))),
2361 case bitc::METADATA_IMPORTED_ENTITY: {
2362 if (Record.size() != 6)
2363 return error("Invalid record");
2365 MDValueList.assignValue(
2366 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2367 (Context, Record[1], getMDOrNull(Record[2]),
2368 getMDOrNull(Record[3]), Record[4],
2369 getMDString(Record[5]))),
2373 case bitc::METADATA_STRING: {
2374 std::string String(Record.begin(), Record.end());
2375 llvm::UpgradeMDStringConstant(String);
2376 Metadata *MD = MDString::get(Context, String);
2377 MDValueList.assignValue(MD, NextMDValueNo++);
2380 case bitc::METADATA_KIND: {
2381 // Support older bitcode files that had METADATA_KIND records in a
2382 // block with METADATA_BLOCK_ID.
2383 if (std::error_code EC = parseMetadataKindRecord(Record))
2389 #undef GET_OR_DISTINCT
2392 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2393 std::error_code BitcodeReader::parseMetadataKinds() {
2394 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2395 return error("Invalid record");
2397 SmallVector<uint64_t, 64> Record;
2399 // Read all the records.
2401 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2403 switch (Entry.Kind) {
2404 case BitstreamEntry::SubBlock: // Handled for us already.
2405 case BitstreamEntry::Error:
2406 return error("Malformed block");
2407 case BitstreamEntry::EndBlock:
2408 return std::error_code();
2409 case BitstreamEntry::Record:
2410 // The interesting case.
2416 unsigned Code = Stream.readRecord(Entry.ID, Record);
2418 default: // Default behavior: ignore.
2420 case bitc::METADATA_KIND: {
2421 if (std::error_code EC = parseMetadataKindRecord(Record))
2429 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2431 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2436 // There is no such thing as -0 with integers. "-0" really means MININT.
2440 /// Resolve all of the initializers for global values and aliases that we can.
2441 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2442 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2443 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2444 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2445 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2446 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2448 GlobalInitWorklist.swap(GlobalInits);
2449 AliasInitWorklist.swap(AliasInits);
2450 FunctionPrefixWorklist.swap(FunctionPrefixes);
2451 FunctionPrologueWorklist.swap(FunctionPrologues);
2452 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2454 while (!GlobalInitWorklist.empty()) {
2455 unsigned ValID = GlobalInitWorklist.back().second;
2456 if (ValID >= ValueList.size()) {
2457 // Not ready to resolve this yet, it requires something later in the file.
2458 GlobalInits.push_back(GlobalInitWorklist.back());
2460 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2461 GlobalInitWorklist.back().first->setInitializer(C);
2463 return error("Expected a constant");
2465 GlobalInitWorklist.pop_back();
2468 while (!AliasInitWorklist.empty()) {
2469 unsigned ValID = AliasInitWorklist.back().second;
2470 if (ValID >= ValueList.size()) {
2471 AliasInits.push_back(AliasInitWorklist.back());
2473 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2475 return error("Expected a constant");
2476 GlobalAlias *Alias = AliasInitWorklist.back().first;
2477 if (C->getType() != Alias->getType())
2478 return error("Alias and aliasee types don't match");
2479 Alias->setAliasee(C);
2481 AliasInitWorklist.pop_back();
2484 while (!FunctionPrefixWorklist.empty()) {
2485 unsigned ValID = FunctionPrefixWorklist.back().second;
2486 if (ValID >= ValueList.size()) {
2487 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2489 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2490 FunctionPrefixWorklist.back().first->setPrefixData(C);
2492 return error("Expected a constant");
2494 FunctionPrefixWorklist.pop_back();
2497 while (!FunctionPrologueWorklist.empty()) {
2498 unsigned ValID = FunctionPrologueWorklist.back().second;
2499 if (ValID >= ValueList.size()) {
2500 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2502 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2503 FunctionPrologueWorklist.back().first->setPrologueData(C);
2505 return error("Expected a constant");
2507 FunctionPrologueWorklist.pop_back();
2510 while (!FunctionPersonalityFnWorklist.empty()) {
2511 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2512 if (ValID >= ValueList.size()) {
2513 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2515 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2516 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2518 return error("Expected a constant");
2520 FunctionPersonalityFnWorklist.pop_back();
2523 return std::error_code();
2526 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2527 SmallVector<uint64_t, 8> Words(Vals.size());
2528 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2529 BitcodeReader::decodeSignRotatedValue);
2531 return APInt(TypeBits, Words);
2534 std::error_code BitcodeReader::parseConstants() {
2535 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2536 return error("Invalid record");
2538 SmallVector<uint64_t, 64> Record;
2540 // Read all the records for this value table.
2541 Type *CurTy = Type::getInt32Ty(Context);
2542 unsigned NextCstNo = ValueList.size();
2544 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2546 switch (Entry.Kind) {
2547 case BitstreamEntry::SubBlock: // Handled for us already.
2548 case BitstreamEntry::Error:
2549 return error("Malformed block");
2550 case BitstreamEntry::EndBlock:
2551 if (NextCstNo != ValueList.size())
2552 return error("Invalid ronstant reference");
2554 // Once all the constants have been read, go through and resolve forward
2556 ValueList.resolveConstantForwardRefs();
2557 return std::error_code();
2558 case BitstreamEntry::Record:
2559 // The interesting case.
2566 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2568 default: // Default behavior: unknown constant
2569 case bitc::CST_CODE_UNDEF: // UNDEF
2570 V = UndefValue::get(CurTy);
2572 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2574 return error("Invalid record");
2575 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2576 return error("Invalid record");
2577 CurTy = TypeList[Record[0]];
2578 continue; // Skip the ValueList manipulation.
2579 case bitc::CST_CODE_NULL: // NULL
2580 V = Constant::getNullValue(CurTy);
2582 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2583 if (!CurTy->isIntegerTy() || Record.empty())
2584 return error("Invalid record");
2585 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2587 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2588 if (!CurTy->isIntegerTy() || Record.empty())
2589 return error("Invalid record");
2592 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2593 V = ConstantInt::get(Context, VInt);
2597 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2599 return error("Invalid record");
2600 if (CurTy->isHalfTy())
2601 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2602 APInt(16, (uint16_t)Record[0])));
2603 else if (CurTy->isFloatTy())
2604 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2605 APInt(32, (uint32_t)Record[0])));
2606 else if (CurTy->isDoubleTy())
2607 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2608 APInt(64, Record[0])));
2609 else if (CurTy->isX86_FP80Ty()) {
2610 // Bits are not stored the same way as a normal i80 APInt, compensate.
2611 uint64_t Rearrange[2];
2612 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2613 Rearrange[1] = Record[0] >> 48;
2614 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2615 APInt(80, Rearrange)));
2616 } else if (CurTy->isFP128Ty())
2617 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2618 APInt(128, Record)));
2619 else if (CurTy->isPPC_FP128Ty())
2620 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2621 APInt(128, Record)));
2623 V = UndefValue::get(CurTy);
2627 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2629 return error("Invalid record");
2631 unsigned Size = Record.size();
2632 SmallVector<Constant*, 16> Elts;
2634 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2635 for (unsigned i = 0; i != Size; ++i)
2636 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2637 STy->getElementType(i)));
2638 V = ConstantStruct::get(STy, Elts);
2639 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2640 Type *EltTy = ATy->getElementType();
2641 for (unsigned i = 0; i != Size; ++i)
2642 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2643 V = ConstantArray::get(ATy, Elts);
2644 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2645 Type *EltTy = VTy->getElementType();
2646 for (unsigned i = 0; i != Size; ++i)
2647 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2648 V = ConstantVector::get(Elts);
2650 V = UndefValue::get(CurTy);
2654 case bitc::CST_CODE_STRING: // STRING: [values]
2655 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2657 return error("Invalid record");
2659 SmallString<16> Elts(Record.begin(), Record.end());
2660 V = ConstantDataArray::getString(Context, Elts,
2661 BitCode == bitc::CST_CODE_CSTRING);
2664 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2666 return error("Invalid record");
2668 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2669 unsigned Size = Record.size();
2671 if (EltTy->isIntegerTy(8)) {
2672 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2673 if (isa<VectorType>(CurTy))
2674 V = ConstantDataVector::get(Context, Elts);
2676 V = ConstantDataArray::get(Context, Elts);
2677 } else if (EltTy->isIntegerTy(16)) {
2678 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2679 if (isa<VectorType>(CurTy))
2680 V = ConstantDataVector::get(Context, Elts);
2682 V = ConstantDataArray::get(Context, Elts);
2683 } else if (EltTy->isIntegerTy(32)) {
2684 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2685 if (isa<VectorType>(CurTy))
2686 V = ConstantDataVector::get(Context, Elts);
2688 V = ConstantDataArray::get(Context, Elts);
2689 } else if (EltTy->isIntegerTy(64)) {
2690 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2691 if (isa<VectorType>(CurTy))
2692 V = ConstantDataVector::get(Context, Elts);
2694 V = ConstantDataArray::get(Context, Elts);
2695 } else if (EltTy->isFloatTy()) {
2696 SmallVector<float, 16> Elts(Size);
2697 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2698 if (isa<VectorType>(CurTy))
2699 V = ConstantDataVector::get(Context, Elts);
2701 V = ConstantDataArray::get(Context, Elts);
2702 } else if (EltTy->isDoubleTy()) {
2703 SmallVector<double, 16> Elts(Size);
2704 std::transform(Record.begin(), Record.end(), Elts.begin(),
2706 if (isa<VectorType>(CurTy))
2707 V = ConstantDataVector::get(Context, Elts);
2709 V = ConstantDataArray::get(Context, Elts);
2711 return error("Invalid type for value");
2716 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2717 if (Record.size() < 3)
2718 return error("Invalid record");
2719 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2721 V = UndefValue::get(CurTy); // Unknown binop.
2723 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2724 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2726 if (Record.size() >= 4) {
2727 if (Opc == Instruction::Add ||
2728 Opc == Instruction::Sub ||
2729 Opc == Instruction::Mul ||
2730 Opc == Instruction::Shl) {
2731 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2732 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2733 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2734 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2735 } else if (Opc == Instruction::SDiv ||
2736 Opc == Instruction::UDiv ||
2737 Opc == Instruction::LShr ||
2738 Opc == Instruction::AShr) {
2739 if (Record[3] & (1 << bitc::PEO_EXACT))
2740 Flags |= SDivOperator::IsExact;
2743 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2747 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2748 if (Record.size() < 3)
2749 return error("Invalid record");
2750 int Opc = getDecodedCastOpcode(Record[0]);
2752 V = UndefValue::get(CurTy); // Unknown cast.
2754 Type *OpTy = getTypeByID(Record[1]);
2756 return error("Invalid record");
2757 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2758 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2759 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2763 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2764 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2766 Type *PointeeType = nullptr;
2767 if (Record.size() % 2)
2768 PointeeType = getTypeByID(Record[OpNum++]);
2769 SmallVector<Constant*, 16> Elts;
2770 while (OpNum != Record.size()) {
2771 Type *ElTy = getTypeByID(Record[OpNum++]);
2773 return error("Invalid record");
2774 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2779 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2781 return error("Explicit gep operator type does not match pointee type "
2782 "of pointer operand");
2784 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2785 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2787 bitc::CST_CODE_CE_INBOUNDS_GEP);
2790 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2791 if (Record.size() < 3)
2792 return error("Invalid record");
2794 Type *SelectorTy = Type::getInt1Ty(Context);
2796 // The selector might be an i1 or an <n x i1>
2797 // Get the type from the ValueList before getting a forward ref.
2798 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2799 if (Value *V = ValueList[Record[0]])
2800 if (SelectorTy != V->getType())
2801 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2803 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2805 ValueList.getConstantFwdRef(Record[1],CurTy),
2806 ValueList.getConstantFwdRef(Record[2],CurTy));
2809 case bitc::CST_CODE_CE_EXTRACTELT
2810 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2811 if (Record.size() < 3)
2812 return error("Invalid record");
2814 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2816 return error("Invalid record");
2817 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2818 Constant *Op1 = nullptr;
2819 if (Record.size() == 4) {
2820 Type *IdxTy = getTypeByID(Record[2]);
2822 return error("Invalid record");
2823 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2824 } else // TODO: Remove with llvm 4.0
2825 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2827 return error("Invalid record");
2828 V = ConstantExpr::getExtractElement(Op0, Op1);
2831 case bitc::CST_CODE_CE_INSERTELT
2832 : { // CE_INSERTELT: [opval, opval, opty, opval]
2833 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2834 if (Record.size() < 3 || !OpTy)
2835 return error("Invalid record");
2836 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2837 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2838 OpTy->getElementType());
2839 Constant *Op2 = nullptr;
2840 if (Record.size() == 4) {
2841 Type *IdxTy = getTypeByID(Record[2]);
2843 return error("Invalid record");
2844 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2845 } else // TODO: Remove with llvm 4.0
2846 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2848 return error("Invalid record");
2849 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2852 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2853 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2854 if (Record.size() < 3 || !OpTy)
2855 return error("Invalid record");
2856 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2857 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2858 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2859 OpTy->getNumElements());
2860 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2861 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2864 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2865 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2867 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2868 if (Record.size() < 4 || !RTy || !OpTy)
2869 return error("Invalid record");
2870 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2871 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2872 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2873 RTy->getNumElements());
2874 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2875 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2878 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2879 if (Record.size() < 4)
2880 return error("Invalid record");
2881 Type *OpTy = getTypeByID(Record[0]);
2883 return error("Invalid record");
2884 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2885 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2887 if (OpTy->isFPOrFPVectorTy())
2888 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2890 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2893 // This maintains backward compatibility, pre-asm dialect keywords.
2894 // FIXME: Remove with the 4.0 release.
2895 case bitc::CST_CODE_INLINEASM_OLD: {
2896 if (Record.size() < 2)
2897 return error("Invalid record");
2898 std::string AsmStr, ConstrStr;
2899 bool HasSideEffects = Record[0] & 1;
2900 bool IsAlignStack = Record[0] >> 1;
2901 unsigned AsmStrSize = Record[1];
2902 if (2+AsmStrSize >= Record.size())
2903 return error("Invalid record");
2904 unsigned ConstStrSize = Record[2+AsmStrSize];
2905 if (3+AsmStrSize+ConstStrSize > Record.size())
2906 return error("Invalid record");
2908 for (unsigned i = 0; i != AsmStrSize; ++i)
2909 AsmStr += (char)Record[2+i];
2910 for (unsigned i = 0; i != ConstStrSize; ++i)
2911 ConstrStr += (char)Record[3+AsmStrSize+i];
2912 PointerType *PTy = cast<PointerType>(CurTy);
2913 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2914 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2917 // This version adds support for the asm dialect keywords (e.g.,
2919 case bitc::CST_CODE_INLINEASM: {
2920 if (Record.size() < 2)
2921 return error("Invalid record");
2922 std::string AsmStr, ConstrStr;
2923 bool HasSideEffects = Record[0] & 1;
2924 bool IsAlignStack = (Record[0] >> 1) & 1;
2925 unsigned AsmDialect = Record[0] >> 2;
2926 unsigned AsmStrSize = Record[1];
2927 if (2+AsmStrSize >= Record.size())
2928 return error("Invalid record");
2929 unsigned ConstStrSize = Record[2+AsmStrSize];
2930 if (3+AsmStrSize+ConstStrSize > Record.size())
2931 return error("Invalid record");
2933 for (unsigned i = 0; i != AsmStrSize; ++i)
2934 AsmStr += (char)Record[2+i];
2935 for (unsigned i = 0; i != ConstStrSize; ++i)
2936 ConstrStr += (char)Record[3+AsmStrSize+i];
2937 PointerType *PTy = cast<PointerType>(CurTy);
2938 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2939 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2940 InlineAsm::AsmDialect(AsmDialect));
2943 case bitc::CST_CODE_BLOCKADDRESS:{
2944 if (Record.size() < 3)
2945 return error("Invalid record");
2946 Type *FnTy = getTypeByID(Record[0]);
2948 return error("Invalid record");
2950 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2952 return error("Invalid record");
2954 // Don't let Fn get dematerialized.
2955 BlockAddressesTaken.insert(Fn);
2957 // If the function is already parsed we can insert the block address right
2960 unsigned BBID = Record[2];
2962 // Invalid reference to entry block.
2963 return error("Invalid ID");
2965 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2966 for (size_t I = 0, E = BBID; I != E; ++I) {
2968 return error("Invalid ID");
2973 // Otherwise insert a placeholder and remember it so it can be inserted
2974 // when the function is parsed.
2975 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2977 BasicBlockFwdRefQueue.push_back(Fn);
2978 if (FwdBBs.size() < BBID + 1)
2979 FwdBBs.resize(BBID + 1);
2981 FwdBBs[BBID] = BasicBlock::Create(Context);
2984 V = BlockAddress::get(Fn, BB);
2989 ValueList.assignValue(V, NextCstNo);
2994 std::error_code BitcodeReader::parseUseLists() {
2995 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2996 return error("Invalid record");
2998 // Read all the records.
2999 SmallVector<uint64_t, 64> Record;
3001 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3003 switch (Entry.Kind) {
3004 case BitstreamEntry::SubBlock: // Handled for us already.
3005 case BitstreamEntry::Error:
3006 return error("Malformed block");
3007 case BitstreamEntry::EndBlock:
3008 return std::error_code();
3009 case BitstreamEntry::Record:
3010 // The interesting case.
3014 // Read a use list record.
3017 switch (Stream.readRecord(Entry.ID, Record)) {
3018 default: // Default behavior: unknown type.
3020 case bitc::USELIST_CODE_BB:
3023 case bitc::USELIST_CODE_DEFAULT: {
3024 unsigned RecordLength = Record.size();
3025 if (RecordLength < 3)
3026 // Records should have at least an ID and two indexes.
3027 return error("Invalid record");
3028 unsigned ID = Record.back();
3033 assert(ID < FunctionBBs.size() && "Basic block not found");
3034 V = FunctionBBs[ID];
3037 unsigned NumUses = 0;
3038 SmallDenseMap<const Use *, unsigned, 16> Order;
3039 for (const Use &U : V->uses()) {
3040 if (++NumUses > Record.size())
3042 Order[&U] = Record[NumUses - 1];
3044 if (Order.size() != Record.size() || NumUses > Record.size())
3045 // Mismatches can happen if the functions are being materialized lazily
3046 // (out-of-order), or a value has been upgraded.
3049 V->sortUseList([&](const Use &L, const Use &R) {
3050 return Order.lookup(&L) < Order.lookup(&R);
3058 /// When we see the block for metadata, remember where it is and then skip it.
3059 /// This lets us lazily deserialize the metadata.
3060 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3061 // Save the current stream state.
3062 uint64_t CurBit = Stream.GetCurrentBitNo();
3063 DeferredMetadataInfo.push_back(CurBit);
3065 // Skip over the block for now.
3066 if (Stream.SkipBlock())
3067 return error("Invalid record");
3068 return std::error_code();
3071 std::error_code BitcodeReader::materializeMetadata() {
3072 for (uint64_t BitPos : DeferredMetadataInfo) {
3073 // Move the bit stream to the saved position.
3074 Stream.JumpToBit(BitPos);
3075 if (std::error_code EC = parseMetadata(true))
3078 DeferredMetadataInfo.clear();
3079 return std::error_code();
3082 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3084 void BitcodeReader::saveMDValueList(
3085 DenseMap<const Metadata *, unsigned> &MDValueToValIDMap, bool OnlyTempMD) {
3086 for (unsigned ValID = 0; ValID < MDValueList.size(); ++ValID) {
3087 Metadata *MD = MDValueList[ValID];
3088 auto *N = dyn_cast_or_null<MDNode>(MD);
3089 // Save all values if !OnlyTempMD, otherwise just the temporary metadata.
3090 if (!OnlyTempMD || (N && N->isTemporary())) {
3091 // Will call this after materializing each function, in order to
3092 // handle remapping of the function's instructions/metadata.
3093 // See if we already have an entry in that case.
3094 if (OnlyTempMD && MDValueToValIDMap.count(MD)) {
3095 assert(MDValueToValIDMap[MD] == ValID &&
3096 "Inconsistent metadata value id");
3099 MDValueToValIDMap[MD] = ValID;
3100 // Flag that we saved the forward refs (temporary metadata) for error
3101 // checking during MDValueList destruction.
3103 MDValueList.savedFwdRefs();
3108 /// When we see the block for a function body, remember where it is and then
3109 /// skip it. This lets us lazily deserialize the functions.
3110 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3111 // Get the function we are talking about.
3112 if (FunctionsWithBodies.empty())
3113 return error("Insufficient function protos");
3115 Function *Fn = FunctionsWithBodies.back();
3116 FunctionsWithBodies.pop_back();
3118 // Save the current stream state.
3119 uint64_t CurBit = Stream.GetCurrentBitNo();
3121 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3122 "Mismatch between VST and scanned function offsets");
3123 DeferredFunctionInfo[Fn] = CurBit;
3125 // Skip over the function block for now.
3126 if (Stream.SkipBlock())
3127 return error("Invalid record");
3128 return std::error_code();
3131 std::error_code BitcodeReader::globalCleanup() {
3132 // Patch the initializers for globals and aliases up.
3133 resolveGlobalAndAliasInits();
3134 if (!GlobalInits.empty() || !AliasInits.empty())
3135 return error("Malformed global initializer set");
3137 // Look for intrinsic functions which need to be upgraded at some point
3138 for (Function &F : *TheModule) {
3140 if (UpgradeIntrinsicFunction(&F, NewFn))
3141 UpgradedIntrinsics[&F] = NewFn;
3144 // Look for global variables which need to be renamed.
3145 for (GlobalVariable &GV : TheModule->globals())
3146 UpgradeGlobalVariable(&GV);
3148 // Force deallocation of memory for these vectors to favor the client that
3149 // want lazy deserialization.
3150 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3151 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3152 return std::error_code();
3155 /// Support for lazy parsing of function bodies. This is required if we
3156 /// either have an old bitcode file without a VST forward declaration record,
3157 /// or if we have an anonymous function being materialized, since anonymous
3158 /// functions do not have a name and are therefore not in the VST.
3159 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3160 Stream.JumpToBit(NextUnreadBit);
3162 if (Stream.AtEndOfStream())
3163 return error("Could not find function in stream");
3165 if (!SeenFirstFunctionBody)
3166 return error("Trying to materialize functions before seeing function blocks");
3168 // An old bitcode file with the symbol table at the end would have
3169 // finished the parse greedily.
3170 assert(SeenValueSymbolTable);
3172 SmallVector<uint64_t, 64> Record;
3175 BitstreamEntry Entry = Stream.advance();
3176 switch (Entry.Kind) {
3178 return error("Expect SubBlock");
3179 case BitstreamEntry::SubBlock:
3182 return error("Expect function block");
3183 case bitc::FUNCTION_BLOCK_ID:
3184 if (std::error_code EC = rememberAndSkipFunctionBody())
3186 NextUnreadBit = Stream.GetCurrentBitNo();
3187 return std::error_code();
3193 std::error_code BitcodeReader::parseBitcodeVersion() {
3194 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3195 return error("Invalid record");
3197 // Read all the records.
3198 SmallVector<uint64_t, 64> Record;
3200 BitstreamEntry Entry = Stream.advance();
3202 switch (Entry.Kind) {
3204 case BitstreamEntry::Error:
3205 return error("Malformed block");
3206 case BitstreamEntry::EndBlock:
3207 return std::error_code();
3208 case BitstreamEntry::Record:
3209 // The interesting case.
3215 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3217 default: // Default behavior: reject
3218 return error("Invalid value");
3219 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3221 convertToString(Record, 0, ProducerIdentification);
3224 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3225 unsigned epoch = (unsigned)Record[0];
3226 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3228 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3229 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3236 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3237 bool ShouldLazyLoadMetadata) {
3239 Stream.JumpToBit(ResumeBit);
3240 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3241 return error("Invalid record");
3243 SmallVector<uint64_t, 64> Record;
3244 std::vector<std::string> SectionTable;
3245 std::vector<std::string> GCTable;
3247 // Read all the records for this module.
3249 BitstreamEntry Entry = Stream.advance();
3251 switch (Entry.Kind) {
3252 case BitstreamEntry::Error:
3253 return error("Malformed block");
3254 case BitstreamEntry::EndBlock:
3255 return globalCleanup();
3257 case BitstreamEntry::SubBlock:
3259 default: // Skip unknown content.
3260 if (Stream.SkipBlock())
3261 return error("Invalid record");
3263 case bitc::BLOCKINFO_BLOCK_ID:
3264 if (Stream.ReadBlockInfoBlock())
3265 return error("Malformed block");
3267 case bitc::PARAMATTR_BLOCK_ID:
3268 if (std::error_code EC = parseAttributeBlock())
3271 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3272 if (std::error_code EC = parseAttributeGroupBlock())
3275 case bitc::TYPE_BLOCK_ID_NEW:
3276 if (std::error_code EC = parseTypeTable())
3279 case bitc::VALUE_SYMTAB_BLOCK_ID:
3280 if (!SeenValueSymbolTable) {
3281 // Either this is an old form VST without function index and an
3282 // associated VST forward declaration record (which would have caused
3283 // the VST to be jumped to and parsed before it was encountered
3284 // normally in the stream), or there were no function blocks to
3285 // trigger an earlier parsing of the VST.
3286 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3287 if (std::error_code EC = parseValueSymbolTable())
3289 SeenValueSymbolTable = true;
3291 // We must have had a VST forward declaration record, which caused
3292 // the parser to jump to and parse the VST earlier.
3293 assert(VSTOffset > 0);
3294 if (Stream.SkipBlock())
3295 return error("Invalid record");
3298 case bitc::CONSTANTS_BLOCK_ID:
3299 if (std::error_code EC = parseConstants())
3301 if (std::error_code EC = resolveGlobalAndAliasInits())
3304 case bitc::METADATA_BLOCK_ID:
3305 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3306 if (std::error_code EC = rememberAndSkipMetadata())
3310 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3311 if (std::error_code EC = parseMetadata(true))
3314 case bitc::METADATA_KIND_BLOCK_ID:
3315 if (std::error_code EC = parseMetadataKinds())
3318 case bitc::FUNCTION_BLOCK_ID:
3319 // If this is the first function body we've seen, reverse the
3320 // FunctionsWithBodies list.
3321 if (!SeenFirstFunctionBody) {
3322 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3323 if (std::error_code EC = globalCleanup())
3325 SeenFirstFunctionBody = true;
3328 if (VSTOffset > 0) {
3329 // If we have a VST forward declaration record, make sure we
3330 // parse the VST now if we haven't already. It is needed to
3331 // set up the DeferredFunctionInfo vector for lazy reading.
3332 if (!SeenValueSymbolTable) {
3333 if (std::error_code EC =
3334 BitcodeReader::parseValueSymbolTable(VSTOffset))
3336 SeenValueSymbolTable = true;
3337 // Fall through so that we record the NextUnreadBit below.
3338 // This is necessary in case we have an anonymous function that
3339 // is later materialized. Since it will not have a VST entry we
3340 // need to fall back to the lazy parse to find its offset.
3342 // If we have a VST forward declaration record, but have already
3343 // parsed the VST (just above, when the first function body was
3344 // encountered here), then we are resuming the parse after
3345 // materializing functions. The ResumeBit points to the
3346 // start of the last function block recorded in the
3347 // DeferredFunctionInfo map. Skip it.
3348 if (Stream.SkipBlock())
3349 return error("Invalid record");
3354 // Support older bitcode files that did not have the function
3355 // index in the VST, nor a VST forward declaration record, as
3356 // well as anonymous functions that do not have VST entries.
3357 // Build the DeferredFunctionInfo vector on the fly.
3358 if (std::error_code EC = rememberAndSkipFunctionBody())
3361 // Suspend parsing when we reach the function bodies. Subsequent
3362 // materialization calls will resume it when necessary. If the bitcode
3363 // file is old, the symbol table will be at the end instead and will not
3364 // have been seen yet. In this case, just finish the parse now.
3365 if (SeenValueSymbolTable) {
3366 NextUnreadBit = Stream.GetCurrentBitNo();
3367 return std::error_code();
3370 case bitc::USELIST_BLOCK_ID:
3371 if (std::error_code EC = parseUseLists())
3374 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3375 if (std::error_code EC = parseOperandBundleTags())
3381 case BitstreamEntry::Record:
3382 // The interesting case.
3388 auto BitCode = Stream.readRecord(Entry.ID, Record);
3390 default: break; // Default behavior, ignore unknown content.
3391 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3392 if (Record.size() < 1)
3393 return error("Invalid record");
3394 // Only version #0 and #1 are supported so far.
3395 unsigned module_version = Record[0];
3396 switch (module_version) {
3398 return error("Invalid value");
3400 UseRelativeIDs = false;
3403 UseRelativeIDs = true;
3408 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3410 if (convertToString(Record, 0, S))
3411 return error("Invalid record");
3412 TheModule->setTargetTriple(S);
3415 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3417 if (convertToString(Record, 0, S))
3418 return error("Invalid record");
3419 TheModule->setDataLayout(S);
3422 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3424 if (convertToString(Record, 0, S))
3425 return error("Invalid record");
3426 TheModule->setModuleInlineAsm(S);
3429 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3430 // FIXME: Remove in 4.0.
3432 if (convertToString(Record, 0, S))
3433 return error("Invalid record");
3437 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3439 if (convertToString(Record, 0, S))
3440 return error("Invalid record");
3441 SectionTable.push_back(S);
3444 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3446 if (convertToString(Record, 0, S))
3447 return error("Invalid record");
3448 GCTable.push_back(S);
3451 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3452 if (Record.size() < 2)
3453 return error("Invalid record");
3454 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3455 unsigned ComdatNameSize = Record[1];
3456 std::string ComdatName;
3457 ComdatName.reserve(ComdatNameSize);
3458 for (unsigned i = 0; i != ComdatNameSize; ++i)
3459 ComdatName += (char)Record[2 + i];
3460 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3461 C->setSelectionKind(SK);
3462 ComdatList.push_back(C);
3465 // GLOBALVAR: [pointer type, isconst, initid,
3466 // linkage, alignment, section, visibility, threadlocal,
3467 // unnamed_addr, externally_initialized, dllstorageclass,
3469 case bitc::MODULE_CODE_GLOBALVAR: {
3470 if (Record.size() < 6)
3471 return error("Invalid record");
3472 Type *Ty = getTypeByID(Record[0]);
3474 return error("Invalid record");
3475 bool isConstant = Record[1] & 1;
3476 bool explicitType = Record[1] & 2;
3477 unsigned AddressSpace;
3479 AddressSpace = Record[1] >> 2;
3481 if (!Ty->isPointerTy())
3482 return error("Invalid type for value");
3483 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3484 Ty = cast<PointerType>(Ty)->getElementType();
3487 uint64_t RawLinkage = Record[3];
3488 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3490 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3492 std::string Section;
3494 if (Record[5]-1 >= SectionTable.size())
3495 return error("Invalid ID");
3496 Section = SectionTable[Record[5]-1];
3498 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3499 // Local linkage must have default visibility.
3500 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3501 // FIXME: Change to an error if non-default in 4.0.
3502 Visibility = getDecodedVisibility(Record[6]);
3504 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3505 if (Record.size() > 7)
3506 TLM = getDecodedThreadLocalMode(Record[7]);
3508 bool UnnamedAddr = false;
3509 if (Record.size() > 8)
3510 UnnamedAddr = Record[8];
3512 bool ExternallyInitialized = false;
3513 if (Record.size() > 9)
3514 ExternallyInitialized = Record[9];
3516 GlobalVariable *NewGV =
3517 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3518 TLM, AddressSpace, ExternallyInitialized);
3519 NewGV->setAlignment(Alignment);
3520 if (!Section.empty())
3521 NewGV->setSection(Section);
3522 NewGV->setVisibility(Visibility);
3523 NewGV->setUnnamedAddr(UnnamedAddr);
3525 if (Record.size() > 10)
3526 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3528 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3530 ValueList.push_back(NewGV);
3532 // Remember which value to use for the global initializer.
3533 if (unsigned InitID = Record[2])
3534 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3536 if (Record.size() > 11) {
3537 if (unsigned ComdatID = Record[11]) {
3538 if (ComdatID > ComdatList.size())
3539 return error("Invalid global variable comdat ID");
3540 NewGV->setComdat(ComdatList[ComdatID - 1]);
3542 } else if (hasImplicitComdat(RawLinkage)) {
3543 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3547 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3548 // alignment, section, visibility, gc, unnamed_addr,
3549 // prologuedata, dllstorageclass, comdat, prefixdata]
3550 case bitc::MODULE_CODE_FUNCTION: {
3551 if (Record.size() < 8)
3552 return error("Invalid record");
3553 Type *Ty = getTypeByID(Record[0]);
3555 return error("Invalid record");
3556 if (auto *PTy = dyn_cast<PointerType>(Ty))
3557 Ty = PTy->getElementType();
3558 auto *FTy = dyn_cast<FunctionType>(Ty);
3560 return error("Invalid type for value");
3561 auto CC = static_cast<CallingConv::ID>(Record[1]);
3562 if (CC & ~CallingConv::MaxID)
3563 return error("Invalid calling convention ID");
3565 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3568 Func->setCallingConv(CC);
3569 bool isProto = Record[2];
3570 uint64_t RawLinkage = Record[3];
3571 Func->setLinkage(getDecodedLinkage(RawLinkage));
3572 Func->setAttributes(getAttributes(Record[4]));
3575 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3577 Func->setAlignment(Alignment);
3579 if (Record[6]-1 >= SectionTable.size())
3580 return error("Invalid ID");
3581 Func->setSection(SectionTable[Record[6]-1]);
3583 // Local linkage must have default visibility.
3584 if (!Func->hasLocalLinkage())
3585 // FIXME: Change to an error if non-default in 4.0.
3586 Func->setVisibility(getDecodedVisibility(Record[7]));
3587 if (Record.size() > 8 && Record[8]) {
3588 if (Record[8]-1 >= GCTable.size())
3589 return error("Invalid ID");
3590 Func->setGC(GCTable[Record[8]-1].c_str());
3592 bool UnnamedAddr = false;
3593 if (Record.size() > 9)
3594 UnnamedAddr = Record[9];
3595 Func->setUnnamedAddr(UnnamedAddr);
3596 if (Record.size() > 10 && Record[10] != 0)
3597 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3599 if (Record.size() > 11)
3600 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3602 upgradeDLLImportExportLinkage(Func, RawLinkage);
3604 if (Record.size() > 12) {
3605 if (unsigned ComdatID = Record[12]) {
3606 if (ComdatID > ComdatList.size())
3607 return error("Invalid function comdat ID");
3608 Func->setComdat(ComdatList[ComdatID - 1]);
3610 } else if (hasImplicitComdat(RawLinkage)) {
3611 Func->setComdat(reinterpret_cast<Comdat *>(1));
3614 if (Record.size() > 13 && Record[13] != 0)
3615 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3617 if (Record.size() > 14 && Record[14] != 0)
3618 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3620 ValueList.push_back(Func);
3622 // If this is a function with a body, remember the prototype we are
3623 // creating now, so that we can match up the body with them later.
3625 Func->setIsMaterializable(true);
3626 FunctionsWithBodies.push_back(Func);
3627 DeferredFunctionInfo[Func] = 0;
3631 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3632 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3633 case bitc::MODULE_CODE_ALIAS:
3634 case bitc::MODULE_CODE_ALIAS_OLD: {
3635 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3636 if (Record.size() < (3 + (unsigned)NewRecord))
3637 return error("Invalid record");
3639 Type *Ty = getTypeByID(Record[OpNum++]);
3641 return error("Invalid record");
3645 auto *PTy = dyn_cast<PointerType>(Ty);
3647 return error("Invalid type for value");
3648 Ty = PTy->getElementType();
3649 AddrSpace = PTy->getAddressSpace();
3651 AddrSpace = Record[OpNum++];
3654 auto Val = Record[OpNum++];
3655 auto Linkage = Record[OpNum++];
3656 auto *NewGA = GlobalAlias::create(
3657 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3658 // Old bitcode files didn't have visibility field.
3659 // Local linkage must have default visibility.
3660 if (OpNum != Record.size()) {
3661 auto VisInd = OpNum++;
3662 if (!NewGA->hasLocalLinkage())
3663 // FIXME: Change to an error if non-default in 4.0.
3664 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3666 if (OpNum != Record.size())
3667 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3669 upgradeDLLImportExportLinkage(NewGA, Linkage);
3670 if (OpNum != Record.size())
3671 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3672 if (OpNum != Record.size())
3673 NewGA->setUnnamedAddr(Record[OpNum++]);
3674 ValueList.push_back(NewGA);
3675 AliasInits.push_back(std::make_pair(NewGA, Val));
3678 /// MODULE_CODE_PURGEVALS: [numvals]
3679 case bitc::MODULE_CODE_PURGEVALS:
3680 // Trim down the value list to the specified size.
3681 if (Record.size() < 1 || Record[0] > ValueList.size())
3682 return error("Invalid record");
3683 ValueList.shrinkTo(Record[0]);
3685 /// MODULE_CODE_VSTOFFSET: [offset]
3686 case bitc::MODULE_CODE_VSTOFFSET:
3687 if (Record.size() < 1)
3688 return error("Invalid record");
3689 VSTOffset = Record[0];
3691 /// MODULE_CODE_METADATA_VALUES: [numvals]
3692 case bitc::MODULE_CODE_METADATA_VALUES:
3693 if (Record.size() < 1)
3694 return error("Invalid record");
3695 assert(!IsMetadataMaterialized);
3696 // This record contains the number of metadata values in the module-level
3697 // METADATA_BLOCK. It is used to support lazy parsing of metadata as
3698 // a postpass, where we will parse function-level metadata first.
3699 // This is needed because the ids of metadata are assigned implicitly
3700 // based on their ordering in the bitcode, with the function-level
3701 // metadata ids starting after the module-level metadata ids. Otherwise,
3702 // we would have to parse the module-level metadata block to prime the
3703 // MDValueList when we are lazy loading metadata during function
3704 // importing. Initialize the MDValueList size here based on the
3705 // record value, regardless of whether we are doing lazy metadata
3706 // loading, so that we have consistent handling and assertion
3707 // checking in parseMetadata for module-level metadata.
3708 NumModuleMDs = Record[0];
3709 SeenModuleValuesRecord = true;
3710 assert(MDValueList.size() == 0);
3711 MDValueList.resize(NumModuleMDs);
3718 /// Helper to read the header common to all bitcode files.
3719 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3720 // Sniff for the signature.
3721 if (Stream.Read(8) != 'B' ||
3722 Stream.Read(8) != 'C' ||
3723 Stream.Read(4) != 0x0 ||
3724 Stream.Read(4) != 0xC ||
3725 Stream.Read(4) != 0xE ||
3726 Stream.Read(4) != 0xD)
3732 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3733 Module *M, bool ShouldLazyLoadMetadata) {
3736 if (std::error_code EC = initStream(std::move(Streamer)))
3739 // Sniff for the signature.
3740 if (!hasValidBitcodeHeader(Stream))
3741 return error("Invalid bitcode signature");
3743 // We expect a number of well-defined blocks, though we don't necessarily
3744 // need to understand them all.
3746 if (Stream.AtEndOfStream()) {
3747 // We didn't really read a proper Module.
3748 return error("Malformed IR file");
3751 BitstreamEntry Entry =
3752 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3754 if (Entry.Kind != BitstreamEntry::SubBlock)
3755 return error("Malformed block");
3757 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3758 parseBitcodeVersion();
3762 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3763 return parseModule(0, ShouldLazyLoadMetadata);
3765 if (Stream.SkipBlock())
3766 return error("Invalid record");
3770 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3771 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3772 return error("Invalid record");
3774 SmallVector<uint64_t, 64> Record;
3777 // Read all the records for this module.
3779 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3781 switch (Entry.Kind) {
3782 case BitstreamEntry::SubBlock: // Handled for us already.
3783 case BitstreamEntry::Error:
3784 return error("Malformed block");
3785 case BitstreamEntry::EndBlock:
3787 case BitstreamEntry::Record:
3788 // The interesting case.
3793 switch (Stream.readRecord(Entry.ID, Record)) {
3794 default: break; // Default behavior, ignore unknown content.
3795 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3797 if (convertToString(Record, 0, S))
3798 return error("Invalid record");
3805 llvm_unreachable("Exit infinite loop");
3808 ErrorOr<std::string> BitcodeReader::parseTriple() {
3809 if (std::error_code EC = initStream(nullptr))
3812 // Sniff for the signature.
3813 if (!hasValidBitcodeHeader(Stream))
3814 return error("Invalid bitcode signature");
3816 // We expect a number of well-defined blocks, though we don't necessarily
3817 // need to understand them all.
3819 BitstreamEntry Entry = Stream.advance();
3821 switch (Entry.Kind) {
3822 case BitstreamEntry::Error:
3823 return error("Malformed block");
3824 case BitstreamEntry::EndBlock:
3825 return std::error_code();
3827 case BitstreamEntry::SubBlock:
3828 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3829 return parseModuleTriple();
3831 // Ignore other sub-blocks.
3832 if (Stream.SkipBlock())
3833 return error("Malformed block");
3836 case BitstreamEntry::Record:
3837 Stream.skipRecord(Entry.ID);
3843 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3844 if (std::error_code EC = initStream(nullptr))
3847 // Sniff for the signature.
3848 if (!hasValidBitcodeHeader(Stream))
3849 return error("Invalid bitcode signature");
3851 // We expect a number of well-defined blocks, though we don't necessarily
3852 // need to understand them all.
3854 BitstreamEntry Entry = Stream.advance();
3855 switch (Entry.Kind) {
3856 case BitstreamEntry::Error:
3857 return error("Malformed block");
3858 case BitstreamEntry::EndBlock:
3859 return std::error_code();
3861 case BitstreamEntry::SubBlock:
3862 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3863 if (std::error_code EC = parseBitcodeVersion())
3865 return ProducerIdentification;
3867 // Ignore other sub-blocks.
3868 if (Stream.SkipBlock())
3869 return error("Malformed block");
3871 case BitstreamEntry::Record:
3872 Stream.skipRecord(Entry.ID);
3878 /// Parse metadata attachments.
3879 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3880 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3881 return error("Invalid record");
3883 SmallVector<uint64_t, 64> Record;
3885 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3887 switch (Entry.Kind) {
3888 case BitstreamEntry::SubBlock: // Handled for us already.
3889 case BitstreamEntry::Error:
3890 return error("Malformed block");
3891 case BitstreamEntry::EndBlock:
3892 return std::error_code();
3893 case BitstreamEntry::Record:
3894 // The interesting case.
3898 // Read a metadata attachment record.
3900 switch (Stream.readRecord(Entry.ID, Record)) {
3901 default: // Default behavior: ignore.
3903 case bitc::METADATA_ATTACHMENT: {
3904 unsigned RecordLength = Record.size();
3906 return error("Invalid record");
3907 if (RecordLength % 2 == 0) {
3908 // A function attachment.
3909 for (unsigned I = 0; I != RecordLength; I += 2) {
3910 auto K = MDKindMap.find(Record[I]);
3911 if (K == MDKindMap.end())
3912 return error("Invalid ID");
3913 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3914 F.setMetadata(K->second, cast<MDNode>(MD));
3919 // An instruction attachment.
3920 Instruction *Inst = InstructionList[Record[0]];
3921 for (unsigned i = 1; i != RecordLength; i = i+2) {
3922 unsigned Kind = Record[i];
3923 DenseMap<unsigned, unsigned>::iterator I =
3924 MDKindMap.find(Kind);
3925 if (I == MDKindMap.end())
3926 return error("Invalid ID");
3927 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3928 if (isa<LocalAsMetadata>(Node))
3929 // Drop the attachment. This used to be legal, but there's no
3932 Inst->setMetadata(I->second, cast<MDNode>(Node));
3933 if (I->second == LLVMContext::MD_tbaa)
3934 InstsWithTBAATag.push_back(Inst);
3942 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3943 LLVMContext &Context = PtrType->getContext();
3944 if (!isa<PointerType>(PtrType))
3945 return error(Context, "Load/Store operand is not a pointer type");
3946 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3948 if (ValType && ValType != ElemType)
3949 return error(Context, "Explicit load/store type does not match pointee "
3950 "type of pointer operand");
3951 if (!PointerType::isLoadableOrStorableType(ElemType))
3952 return error(Context, "Cannot load/store from pointer");
3953 return std::error_code();
3956 /// Lazily parse the specified function body block.
3957 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3958 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3959 return error("Invalid record");
3961 InstructionList.clear();
3962 unsigned ModuleValueListSize = ValueList.size();
3963 unsigned ModuleMDValueListSize = MDValueList.size();
3965 // Add all the function arguments to the value table.
3966 for (Argument &I : F->args())
3967 ValueList.push_back(&I);
3969 unsigned NextValueNo = ValueList.size();
3970 BasicBlock *CurBB = nullptr;
3971 unsigned CurBBNo = 0;
3974 auto getLastInstruction = [&]() -> Instruction * {
3975 if (CurBB && !CurBB->empty())
3976 return &CurBB->back();
3977 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3978 !FunctionBBs[CurBBNo - 1]->empty())
3979 return &FunctionBBs[CurBBNo - 1]->back();
3983 std::vector<OperandBundleDef> OperandBundles;
3985 // Read all the records.
3986 SmallVector<uint64_t, 64> Record;
3988 BitstreamEntry Entry = Stream.advance();
3990 switch (Entry.Kind) {
3991 case BitstreamEntry::Error:
3992 return error("Malformed block");
3993 case BitstreamEntry::EndBlock:
3994 goto OutOfRecordLoop;
3996 case BitstreamEntry::SubBlock:
3998 default: // Skip unknown content.
3999 if (Stream.SkipBlock())
4000 return error("Invalid record");
4002 case bitc::CONSTANTS_BLOCK_ID:
4003 if (std::error_code EC = parseConstants())
4005 NextValueNo = ValueList.size();
4007 case bitc::VALUE_SYMTAB_BLOCK_ID:
4008 if (std::error_code EC = parseValueSymbolTable())
4011 case bitc::METADATA_ATTACHMENT_ID:
4012 if (std::error_code EC = parseMetadataAttachment(*F))
4015 case bitc::METADATA_BLOCK_ID:
4016 if (std::error_code EC = parseMetadata())