1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/FunctionInfo.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/DataStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
42 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
45 class BitcodeReaderValueList {
46 std::vector<WeakVH> ValuePtrs;
48 /// As we resolve forward-referenced constants, we add information about them
49 /// to this vector. This allows us to resolve them in bulk instead of
50 /// resolving each reference at a time. See the code in
51 /// ResolveConstantForwardRefs for more information about this.
53 /// The key of this vector is the placeholder constant, the value is the slot
54 /// number that holds the resolved value.
55 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
56 ResolveConstantsTy ResolveConstants;
59 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
60 ~BitcodeReaderValueList() {
61 assert(ResolveConstants.empty() && "Constants not resolved?");
64 // vector compatibility methods
65 unsigned size() const { return ValuePtrs.size(); }
66 void resize(unsigned N) { ValuePtrs.resize(N); }
67 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
70 assert(ResolveConstants.empty() && "Constants not resolved?");
74 Value *operator[](unsigned i) const {
75 assert(i < ValuePtrs.size());
79 Value *back() const { return ValuePtrs.back(); }
80 void pop_back() { ValuePtrs.pop_back(); }
81 bool empty() const { return ValuePtrs.empty(); }
82 void shrinkTo(unsigned N) {
83 assert(N <= size() && "Invalid shrinkTo request!");
87 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
88 Value *getValueFwdRef(unsigned Idx, Type *Ty);
90 void assignValue(Value *V, unsigned Idx);
92 /// Once all constants are read, this method bulk resolves any forward
94 void resolveConstantForwardRefs();
97 class BitcodeReaderMDValueList {
102 std::vector<TrackingMDRef> MDValuePtrs;
104 LLVMContext &Context;
106 BitcodeReaderMDValueList(LLVMContext &C)
107 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
109 // vector compatibility methods
110 unsigned size() const { return MDValuePtrs.size(); }
111 void resize(unsigned N) { MDValuePtrs.resize(N); }
112 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
113 void clear() { MDValuePtrs.clear(); }
114 Metadata *back() const { return MDValuePtrs.back(); }
115 void pop_back() { MDValuePtrs.pop_back(); }
116 bool empty() const { return MDValuePtrs.empty(); }
118 Metadata *operator[](unsigned i) const {
119 assert(i < MDValuePtrs.size());
120 return MDValuePtrs[i];
123 void shrinkTo(unsigned N) {
124 assert(N <= size() && "Invalid shrinkTo request!");
125 MDValuePtrs.resize(N);
128 Metadata *getValueFwdRef(unsigned Idx);
129 void assignValue(Metadata *MD, unsigned Idx);
130 void tryToResolveCycles();
133 class BitcodeReader : public GVMaterializer {
134 LLVMContext &Context;
135 DiagnosticHandlerFunction DiagnosticHandler;
136 Module *TheModule = nullptr;
137 std::unique_ptr<MemoryBuffer> Buffer;
138 std::unique_ptr<BitstreamReader> StreamFile;
139 BitstreamCursor Stream;
140 // Next offset to start scanning for lazy parsing of function bodies.
141 uint64_t NextUnreadBit = 0;
142 // Last function offset found in the VST.
143 uint64_t LastFunctionBlockBit = 0;
144 bool SeenValueSymbolTable = false;
145 uint64_t VSTOffset = 0;
146 // Contains an arbitrary and optional string identifying the bitcode producer
147 std::string ProducerIdentification;
148 // Number of module level metadata records specified by the
149 // MODULE_CODE_METADATA_VALUES record.
150 unsigned NumModuleMDs = 0;
151 // Support older bitcode without the MODULE_CODE_METADATA_VALUES record.
152 bool SeenModuleValuesRecord = false;
154 std::vector<Type*> TypeList;
155 BitcodeReaderValueList ValueList;
156 BitcodeReaderMDValueList MDValueList;
157 std::vector<Comdat *> ComdatList;
158 SmallVector<Instruction *, 64> InstructionList;
160 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
161 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
162 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
163 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
164 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
166 SmallVector<Instruction*, 64> InstsWithTBAATag;
168 /// The set of attributes by index. Index zero in the file is for null, and
169 /// is thus not represented here. As such all indices are off by one.
170 std::vector<AttributeSet> MAttributes;
172 /// The set of attribute groups.
173 std::map<unsigned, AttributeSet> MAttributeGroups;
175 /// While parsing a function body, this is a list of the basic blocks for the
177 std::vector<BasicBlock*> FunctionBBs;
179 // When reading the module header, this list is populated with functions that
180 // have bodies later in the file.
181 std::vector<Function*> FunctionsWithBodies;
183 // When intrinsic functions are encountered which require upgrading they are
184 // stored here with their replacement function.
185 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
186 UpgradedIntrinsicMap UpgradedIntrinsics;
188 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
189 DenseMap<unsigned, unsigned> MDKindMap;
191 // Several operations happen after the module header has been read, but
192 // before function bodies are processed. This keeps track of whether
193 // we've done this yet.
194 bool SeenFirstFunctionBody = false;
196 /// When function bodies are initially scanned, this map contains info about
197 /// where to find deferred function body in the stream.
198 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
200 /// When Metadata block is initially scanned when parsing the module, we may
201 /// choose to defer parsing of the metadata. This vector contains info about
202 /// which Metadata blocks are deferred.
203 std::vector<uint64_t> DeferredMetadataInfo;
205 /// These are basic blocks forward-referenced by block addresses. They are
206 /// inserted lazily into functions when they're loaded. The basic block ID is
207 /// its index into the vector.
208 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
209 std::deque<Function *> BasicBlockFwdRefQueue;
211 /// Indicates that we are using a new encoding for instruction operands where
212 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
213 /// instruction number, for a more compact encoding. Some instruction
214 /// operands are not relative to the instruction ID: basic block numbers, and
215 /// types. Once the old style function blocks have been phased out, we would
216 /// not need this flag.
217 bool UseRelativeIDs = false;
219 /// True if all functions will be materialized, negating the need to process
220 /// (e.g.) blockaddress forward references.
221 bool WillMaterializeAllForwardRefs = false;
223 /// Functions that have block addresses taken. This is usually empty.
224 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
226 /// True if any Metadata block has been materialized.
227 bool IsMetadataMaterialized = false;
229 bool StripDebugInfo = false;
231 /// Functions that need to be matched with subprograms when upgrading old
233 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
235 std::vector<std::string> BundleTags;
238 std::error_code error(BitcodeError E, const Twine &Message);
239 std::error_code error(BitcodeError E);
240 std::error_code error(const Twine &Message);
242 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
243 DiagnosticHandlerFunction DiagnosticHandler);
244 BitcodeReader(LLVMContext &Context,
245 DiagnosticHandlerFunction DiagnosticHandler);
246 ~BitcodeReader() override { freeState(); }
248 std::error_code materializeForwardReferencedFunctions();
252 void releaseBuffer();
254 bool isDematerializable(const GlobalValue *GV) const override;
255 std::error_code materialize(GlobalValue *GV) override;
256 std::error_code materializeModule(Module *M) override;
257 std::vector<StructType *> getIdentifiedStructTypes() const override;
258 void dematerialize(GlobalValue *GV) override;
260 /// \brief Main interface to parsing a bitcode buffer.
261 /// \returns true if an error occurred.
262 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
264 bool ShouldLazyLoadMetadata = false);
266 /// \brief Cheap mechanism to just extract module triple
267 /// \returns true if an error occurred.
268 ErrorOr<std::string> parseTriple();
270 /// Cheap mechanism to just extract the identification block out of bitcode.
271 ErrorOr<std::string> parseIdentificationBlock();
273 static uint64_t decodeSignRotatedValue(uint64_t V);
275 /// Materialize any deferred Metadata block.
276 std::error_code materializeMetadata() override;
278 void setStripDebugInfo() override;
281 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
282 // ProducerIdentification data member, and do some basic enforcement on the
283 // "epoch" encoded in the bitcode.
284 std::error_code parseBitcodeVersion();
286 std::vector<StructType *> IdentifiedStructTypes;
287 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
288 StructType *createIdentifiedStructType(LLVMContext &Context);
290 Type *getTypeByID(unsigned ID);
291 Value *getFnValueByID(unsigned ID, Type *Ty) {
292 if (Ty && Ty->isMetadataTy())
293 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
294 return ValueList.getValueFwdRef(ID, Ty);
296 Metadata *getFnMetadataByID(unsigned ID) {
297 return MDValueList.getValueFwdRef(ID);
299 BasicBlock *getBasicBlock(unsigned ID) const {
300 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
301 return FunctionBBs[ID];
303 AttributeSet getAttributes(unsigned i) const {
304 if (i-1 < MAttributes.size())
305 return MAttributes[i-1];
306 return AttributeSet();
309 /// Read a value/type pair out of the specified record from slot 'Slot'.
310 /// Increment Slot past the number of slots used in the record. Return true on
312 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
313 unsigned InstNum, Value *&ResVal) {
314 if (Slot == Record.size()) return true;
315 unsigned ValNo = (unsigned)Record[Slot++];
316 // Adjust the ValNo, if it was encoded relative to the InstNum.
318 ValNo = InstNum - ValNo;
319 if (ValNo < InstNum) {
320 // If this is not a forward reference, just return the value we already
322 ResVal = getFnValueByID(ValNo, nullptr);
323 return ResVal == nullptr;
325 if (Slot == Record.size())
328 unsigned TypeNo = (unsigned)Record[Slot++];
329 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
330 return ResVal == nullptr;
333 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
334 /// past the number of slots used by the value in the record. Return true if
335 /// there is an error.
336 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
337 unsigned InstNum, Type *Ty, Value *&ResVal) {
338 if (getValue(Record, Slot, InstNum, Ty, ResVal))
340 // All values currently take a single record slot.
345 /// Like popValue, but does not increment the Slot number.
346 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
347 unsigned InstNum, Type *Ty, Value *&ResVal) {
348 ResVal = getValue(Record, Slot, InstNum, Ty);
349 return ResVal == nullptr;
352 /// Version of getValue that returns ResVal directly, or 0 if there is an
354 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
355 unsigned InstNum, Type *Ty) {
356 if (Slot == Record.size()) return nullptr;
357 unsigned ValNo = (unsigned)Record[Slot];
358 // Adjust the ValNo, if it was encoded relative to the InstNum.
360 ValNo = InstNum - ValNo;
361 return getFnValueByID(ValNo, Ty);
364 /// Like getValue, but decodes signed VBRs.
365 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
366 unsigned InstNum, Type *Ty) {
367 if (Slot == Record.size()) return nullptr;
368 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
369 // Adjust the ValNo, if it was encoded relative to the InstNum.
371 ValNo = InstNum - ValNo;
372 return getFnValueByID(ValNo, Ty);
375 /// Converts alignment exponent (i.e. power of two (or zero)) to the
376 /// corresponding alignment to use. If alignment is too large, returns
377 /// a corresponding error code.
378 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
379 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
380 std::error_code parseModule(uint64_t ResumeBit,
381 bool ShouldLazyLoadMetadata = false);
382 std::error_code parseAttributeBlock();
383 std::error_code parseAttributeGroupBlock();
384 std::error_code parseTypeTable();
385 std::error_code parseTypeTableBody();
386 std::error_code parseOperandBundleTags();
388 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
389 unsigned NameIndex, Triple &TT);
390 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
391 std::error_code parseConstants();
392 std::error_code rememberAndSkipFunctionBodies();
393 std::error_code rememberAndSkipFunctionBody();
394 /// Save the positions of the Metadata blocks and skip parsing the blocks.
395 std::error_code rememberAndSkipMetadata();
396 std::error_code parseFunctionBody(Function *F);
397 std::error_code globalCleanup();
398 std::error_code resolveGlobalAndAliasInits();
399 std::error_code parseMetadata(bool ModuleLevel = false);
400 std::error_code parseMetadataKinds();
401 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
402 std::error_code parseMetadataAttachment(Function &F);
403 ErrorOr<std::string> parseModuleTriple();
404 std::error_code parseUseLists();
405 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
406 std::error_code initStreamFromBuffer();
407 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
408 std::error_code findFunctionInStream(
410 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
413 /// Class to manage reading and parsing function summary index bitcode
415 class FunctionIndexBitcodeReader {
416 DiagnosticHandlerFunction DiagnosticHandler;
418 /// Eventually points to the function index built during parsing.
419 FunctionInfoIndex *TheIndex = nullptr;
421 std::unique_ptr<MemoryBuffer> Buffer;
422 std::unique_ptr<BitstreamReader> StreamFile;
423 BitstreamCursor Stream;
425 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
427 /// If false, the summary section is fully parsed into the index during
428 /// the initial parse. Otherwise, if true, the caller is expected to
429 /// invoke \a readFunctionSummary for each summary needed, and the summary
430 /// section is thus parsed lazily.
433 /// Used to indicate whether caller only wants to check for the presence
434 /// of the function summary bitcode section. All blocks are skipped,
435 /// but the SeenFuncSummary boolean is set.
436 bool CheckFuncSummaryPresenceOnly = false;
438 /// Indicates whether we have encountered a function summary section
439 /// yet during parsing, used when checking if file contains function
441 bool SeenFuncSummary = false;
443 /// \brief Map populated during function summary section parsing, and
444 /// consumed during ValueSymbolTable parsing.
446 /// Used to correlate summary records with VST entries. For the per-module
447 /// index this maps the ValueID to the parsed function summary, and
448 /// for the combined index this maps the summary record's bitcode
449 /// offset to the function summary (since in the combined index the
450 /// VST records do not hold value IDs but rather hold the function
451 /// summary record offset).
452 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
454 /// Map populated during module path string table parsing, from the
455 /// module ID to a string reference owned by the index's module
456 /// path string table, used to correlate with combined index function
458 DenseMap<uint64_t, StringRef> ModuleIdMap;
461 std::error_code error(BitcodeError E, const Twine &Message);
462 std::error_code error(BitcodeError E);
463 std::error_code error(const Twine &Message);
465 FunctionIndexBitcodeReader(MemoryBuffer *Buffer,
466 DiagnosticHandlerFunction DiagnosticHandler,
468 bool CheckFuncSummaryPresenceOnly = false);
469 FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler,
471 bool CheckFuncSummaryPresenceOnly = false);
472 ~FunctionIndexBitcodeReader() { freeState(); }
476 void releaseBuffer();
478 /// Check if the parser has encountered a function summary section.
479 bool foundFuncSummary() { return SeenFuncSummary; }
481 /// \brief Main interface to parsing a bitcode buffer.
482 /// \returns true if an error occurred.
483 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
484 FunctionInfoIndex *I);
486 /// \brief Interface for parsing a function summary lazily.
487 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
488 FunctionInfoIndex *I,
489 size_t FunctionSummaryOffset);
492 std::error_code parseModule();
493 std::error_code parseValueSymbolTable();
494 std::error_code parseEntireSummary();
495 std::error_code parseModuleStringTable();
496 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
497 std::error_code initStreamFromBuffer();
498 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
502 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
503 DiagnosticSeverity Severity,
505 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
507 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
509 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
510 std::error_code EC, const Twine &Message) {
511 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
512 DiagnosticHandler(DI);
516 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
517 std::error_code EC) {
518 return error(DiagnosticHandler, EC, EC.message());
521 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
522 const Twine &Message) {
523 return error(DiagnosticHandler,
524 make_error_code(BitcodeError::CorruptedBitcode), Message);
527 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
528 if (!ProducerIdentification.empty()) {
529 return ::error(DiagnosticHandler, make_error_code(E),
530 Message + " (Producer: '" + ProducerIdentification +
531 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
533 return ::error(DiagnosticHandler, make_error_code(E), Message);
536 std::error_code BitcodeReader::error(const Twine &Message) {
537 if (!ProducerIdentification.empty()) {
538 return ::error(DiagnosticHandler,
539 make_error_code(BitcodeError::CorruptedBitcode),
540 Message + " (Producer: '" + ProducerIdentification +
541 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
543 return ::error(DiagnosticHandler,
544 make_error_code(BitcodeError::CorruptedBitcode), Message);
547 std::error_code BitcodeReader::error(BitcodeError E) {
548 return ::error(DiagnosticHandler, make_error_code(E));
551 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
555 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
558 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
559 DiagnosticHandlerFunction DiagnosticHandler)
561 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
562 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
564 BitcodeReader::BitcodeReader(LLVMContext &Context,
565 DiagnosticHandlerFunction DiagnosticHandler)
567 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
568 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
570 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
571 if (WillMaterializeAllForwardRefs)
572 return std::error_code();
574 // Prevent recursion.
575 WillMaterializeAllForwardRefs = true;
577 while (!BasicBlockFwdRefQueue.empty()) {
578 Function *F = BasicBlockFwdRefQueue.front();
579 BasicBlockFwdRefQueue.pop_front();
580 assert(F && "Expected valid function");
581 if (!BasicBlockFwdRefs.count(F))
582 // Already materialized.
585 // Check for a function that isn't materializable to prevent an infinite
586 // loop. When parsing a blockaddress stored in a global variable, there
587 // isn't a trivial way to check if a function will have a body without a
588 // linear search through FunctionsWithBodies, so just check it here.
589 if (!F->isMaterializable())
590 return error("Never resolved function from blockaddress");
592 // Try to materialize F.
593 if (std::error_code EC = materialize(F))
596 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
599 WillMaterializeAllForwardRefs = false;
600 return std::error_code();
603 void BitcodeReader::freeState() {
605 std::vector<Type*>().swap(TypeList);
608 std::vector<Comdat *>().swap(ComdatList);
610 std::vector<AttributeSet>().swap(MAttributes);
611 std::vector<BasicBlock*>().swap(FunctionBBs);
612 std::vector<Function*>().swap(FunctionsWithBodies);
613 DeferredFunctionInfo.clear();
614 DeferredMetadataInfo.clear();
617 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
618 BasicBlockFwdRefQueue.clear();
621 //===----------------------------------------------------------------------===//
622 // Helper functions to implement forward reference resolution, etc.
623 //===----------------------------------------------------------------------===//
625 /// Convert a string from a record into an std::string, return true on failure.
626 template <typename StrTy>
627 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
629 if (Idx > Record.size())
632 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
633 Result += (char)Record[i];
637 static bool hasImplicitComdat(size_t Val) {
641 case 1: // Old WeakAnyLinkage
642 case 4: // Old LinkOnceAnyLinkage
643 case 10: // Old WeakODRLinkage
644 case 11: // Old LinkOnceODRLinkage
649 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
651 default: // Map unknown/new linkages to external
653 return GlobalValue::ExternalLinkage;
655 return GlobalValue::AppendingLinkage;
657 return GlobalValue::InternalLinkage;
659 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
661 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
663 return GlobalValue::ExternalWeakLinkage;
665 return GlobalValue::CommonLinkage;
667 return GlobalValue::PrivateLinkage;
669 return GlobalValue::AvailableExternallyLinkage;
671 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
673 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
675 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
676 case 1: // Old value with implicit comdat.
678 return GlobalValue::WeakAnyLinkage;
679 case 10: // Old value with implicit comdat.
681 return GlobalValue::WeakODRLinkage;
682 case 4: // Old value with implicit comdat.
684 return GlobalValue::LinkOnceAnyLinkage;
685 case 11: // Old value with implicit comdat.
687 return GlobalValue::LinkOnceODRLinkage;
691 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
693 default: // Map unknown visibilities to default.
694 case 0: return GlobalValue::DefaultVisibility;
695 case 1: return GlobalValue::HiddenVisibility;
696 case 2: return GlobalValue::ProtectedVisibility;
700 static GlobalValue::DLLStorageClassTypes
701 getDecodedDLLStorageClass(unsigned Val) {
703 default: // Map unknown values to default.
704 case 0: return GlobalValue::DefaultStorageClass;
705 case 1: return GlobalValue::DLLImportStorageClass;
706 case 2: return GlobalValue::DLLExportStorageClass;
710 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
712 case 0: return GlobalVariable::NotThreadLocal;
713 default: // Map unknown non-zero value to general dynamic.
714 case 1: return GlobalVariable::GeneralDynamicTLSModel;
715 case 2: return GlobalVariable::LocalDynamicTLSModel;
716 case 3: return GlobalVariable::InitialExecTLSModel;
717 case 4: return GlobalVariable::LocalExecTLSModel;
721 static int getDecodedCastOpcode(unsigned Val) {
724 case bitc::CAST_TRUNC : return Instruction::Trunc;
725 case bitc::CAST_ZEXT : return Instruction::ZExt;
726 case bitc::CAST_SEXT : return Instruction::SExt;
727 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
728 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
729 case bitc::CAST_UITOFP : return Instruction::UIToFP;
730 case bitc::CAST_SITOFP : return Instruction::SIToFP;
731 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
732 case bitc::CAST_FPEXT : return Instruction::FPExt;
733 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
734 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
735 case bitc::CAST_BITCAST : return Instruction::BitCast;
736 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
740 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
741 bool IsFP = Ty->isFPOrFPVectorTy();
742 // BinOps are only valid for int/fp or vector of int/fp types
743 if (!IsFP && !Ty->isIntOrIntVectorTy())
749 case bitc::BINOP_ADD:
750 return IsFP ? Instruction::FAdd : Instruction::Add;
751 case bitc::BINOP_SUB:
752 return IsFP ? Instruction::FSub : Instruction::Sub;
753 case bitc::BINOP_MUL:
754 return IsFP ? Instruction::FMul : Instruction::Mul;
755 case bitc::BINOP_UDIV:
756 return IsFP ? -1 : Instruction::UDiv;
757 case bitc::BINOP_SDIV:
758 return IsFP ? Instruction::FDiv : Instruction::SDiv;
759 case bitc::BINOP_UREM:
760 return IsFP ? -1 : Instruction::URem;
761 case bitc::BINOP_SREM:
762 return IsFP ? Instruction::FRem : Instruction::SRem;
763 case bitc::BINOP_SHL:
764 return IsFP ? -1 : Instruction::Shl;
765 case bitc::BINOP_LSHR:
766 return IsFP ? -1 : Instruction::LShr;
767 case bitc::BINOP_ASHR:
768 return IsFP ? -1 : Instruction::AShr;
769 case bitc::BINOP_AND:
770 return IsFP ? -1 : Instruction::And;
772 return IsFP ? -1 : Instruction::Or;
773 case bitc::BINOP_XOR:
774 return IsFP ? -1 : Instruction::Xor;
778 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
780 default: return AtomicRMWInst::BAD_BINOP;
781 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
782 case bitc::RMW_ADD: return AtomicRMWInst::Add;
783 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
784 case bitc::RMW_AND: return AtomicRMWInst::And;
785 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
786 case bitc::RMW_OR: return AtomicRMWInst::Or;
787 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
788 case bitc::RMW_MAX: return AtomicRMWInst::Max;
789 case bitc::RMW_MIN: return AtomicRMWInst::Min;
790 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
791 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
795 static AtomicOrdering getDecodedOrdering(unsigned Val) {
797 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
798 case bitc::ORDERING_UNORDERED: return Unordered;
799 case bitc::ORDERING_MONOTONIC: return Monotonic;
800 case bitc::ORDERING_ACQUIRE: return Acquire;
801 case bitc::ORDERING_RELEASE: return Release;
802 case bitc::ORDERING_ACQREL: return AcquireRelease;
803 default: // Map unknown orderings to sequentially-consistent.
804 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
808 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
810 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
811 default: // Map unknown scopes to cross-thread.
812 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
816 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
818 default: // Map unknown selection kinds to any.
819 case bitc::COMDAT_SELECTION_KIND_ANY:
821 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
822 return Comdat::ExactMatch;
823 case bitc::COMDAT_SELECTION_KIND_LARGEST:
824 return Comdat::Largest;
825 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
826 return Comdat::NoDuplicates;
827 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
828 return Comdat::SameSize;
832 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
834 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
835 FMF.setUnsafeAlgebra();
836 if (0 != (Val & FastMathFlags::NoNaNs))
838 if (0 != (Val & FastMathFlags::NoInfs))
840 if (0 != (Val & FastMathFlags::NoSignedZeros))
841 FMF.setNoSignedZeros();
842 if (0 != (Val & FastMathFlags::AllowReciprocal))
843 FMF.setAllowReciprocal();
847 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
849 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
850 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
856 /// \brief A class for maintaining the slot number definition
857 /// as a placeholder for the actual definition for forward constants defs.
858 class ConstantPlaceHolder : public ConstantExpr {
859 void operator=(const ConstantPlaceHolder &) = delete;
862 // allocate space for exactly one operand
863 void *operator new(size_t s) { return User::operator new(s, 1); }
864 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
865 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
866 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
869 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
870 static bool classof(const Value *V) {
871 return isa<ConstantExpr>(V) &&
872 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
875 /// Provide fast operand accessors
876 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
880 // FIXME: can we inherit this from ConstantExpr?
882 struct OperandTraits<ConstantPlaceHolder> :
883 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
885 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
888 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
897 WeakVH &OldV = ValuePtrs[Idx];
903 // Handle constants and non-constants (e.g. instrs) differently for
905 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
906 ResolveConstants.push_back(std::make_pair(PHC, Idx));
909 // If there was a forward reference to this value, replace it.
910 Value *PrevVal = OldV;
911 OldV->replaceAllUsesWith(V);
919 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
924 if (Value *V = ValuePtrs[Idx]) {
925 if (Ty != V->getType())
926 report_fatal_error("Type mismatch in constant table!");
927 return cast<Constant>(V);
930 // Create and return a placeholder, which will later be RAUW'd.
931 Constant *C = new ConstantPlaceHolder(Ty, Context);
936 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
937 // Bail out for a clearly invalid value. This would make us call resize(0)
944 if (Value *V = ValuePtrs[Idx]) {
945 // If the types don't match, it's invalid.
946 if (Ty && Ty != V->getType())
951 // No type specified, must be invalid reference.
952 if (!Ty) return nullptr;
954 // Create and return a placeholder, which will later be RAUW'd.
955 Value *V = new Argument(Ty);
960 /// Once all constants are read, this method bulk resolves any forward
961 /// references. The idea behind this is that we sometimes get constants (such
962 /// as large arrays) which reference *many* forward ref constants. Replacing
963 /// each of these causes a lot of thrashing when building/reuniquing the
964 /// constant. Instead of doing this, we look at all the uses and rewrite all
965 /// the place holders at once for any constant that uses a placeholder.
966 void BitcodeReaderValueList::resolveConstantForwardRefs() {
967 // Sort the values by-pointer so that they are efficient to look up with a
969 std::sort(ResolveConstants.begin(), ResolveConstants.end());
971 SmallVector<Constant*, 64> NewOps;
973 while (!ResolveConstants.empty()) {
974 Value *RealVal = operator[](ResolveConstants.back().second);
975 Constant *Placeholder = ResolveConstants.back().first;
976 ResolveConstants.pop_back();
978 // Loop over all users of the placeholder, updating them to reference the
979 // new value. If they reference more than one placeholder, update them all
981 while (!Placeholder->use_empty()) {
982 auto UI = Placeholder->user_begin();
985 // If the using object isn't uniqued, just update the operands. This
986 // handles instructions and initializers for global variables.
987 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
988 UI.getUse().set(RealVal);
992 // Otherwise, we have a constant that uses the placeholder. Replace that
993 // constant with a new constant that has *all* placeholder uses updated.
994 Constant *UserC = cast<Constant>(U);
995 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
998 if (!isa<ConstantPlaceHolder>(*I)) {
999 // Not a placeholder reference.
1001 } else if (*I == Placeholder) {
1002 // Common case is that it just references this one placeholder.
1005 // Otherwise, look up the placeholder in ResolveConstants.
1006 ResolveConstantsTy::iterator It =
1007 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1008 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1010 assert(It != ResolveConstants.end() && It->first == *I);
1011 NewOp = operator[](It->second);
1014 NewOps.push_back(cast<Constant>(NewOp));
1017 // Make the new constant.
1019 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1020 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1021 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1022 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1023 } else if (isa<ConstantVector>(UserC)) {
1024 NewC = ConstantVector::get(NewOps);
1026 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1027 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1030 UserC->replaceAllUsesWith(NewC);
1031 UserC->destroyConstant();
1035 // Update all ValueHandles, they should be the only users at this point.
1036 Placeholder->replaceAllUsesWith(RealVal);
1041 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1042 if (Idx == size()) {
1050 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1056 // If there was a forward reference to this value, replace it.
1057 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1058 PrevMD->replaceAllUsesWith(MD);
1062 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1066 if (Metadata *MD = MDValuePtrs[Idx])
1069 // Track forward refs to be resolved later.
1071 MinFwdRef = std::min(MinFwdRef, Idx);
1072 MaxFwdRef = std::max(MaxFwdRef, Idx);
1075 MinFwdRef = MaxFwdRef = Idx;
1079 // Create and return a placeholder, which will later be RAUW'd.
1080 Metadata *MD = MDNode::getTemporary(Context, None).release();
1081 MDValuePtrs[Idx].reset(MD);
1085 void BitcodeReaderMDValueList::tryToResolveCycles() {
1091 // Still forward references... can't resolve cycles.
1094 // Resolve any cycles.
1095 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1096 auto &MD = MDValuePtrs[I];
1097 auto *N = dyn_cast_or_null<MDNode>(MD);
1101 assert(!N->isTemporary() && "Unexpected forward reference");
1105 // Make sure we return early again until there's another forward ref.
1109 Type *BitcodeReader::getTypeByID(unsigned ID) {
1110 // The type table size is always specified correctly.
1111 if (ID >= TypeList.size())
1114 if (Type *Ty = TypeList[ID])
1117 // If we have a forward reference, the only possible case is when it is to a
1118 // named struct. Just create a placeholder for now.
1119 return TypeList[ID] = createIdentifiedStructType(Context);
1122 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1124 auto *Ret = StructType::create(Context, Name);
1125 IdentifiedStructTypes.push_back(Ret);
1129 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1130 auto *Ret = StructType::create(Context);
1131 IdentifiedStructTypes.push_back(Ret);
1136 //===----------------------------------------------------------------------===//
1137 // Functions for parsing blocks from the bitcode file
1138 //===----------------------------------------------------------------------===//
1141 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1142 /// been decoded from the given integer. This function must stay in sync with
1143 /// 'encodeLLVMAttributesForBitcode'.
1144 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1145 uint64_t EncodedAttrs) {
1146 // FIXME: Remove in 4.0.
1148 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1149 // the bits above 31 down by 11 bits.
1150 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1151 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1152 "Alignment must be a power of two.");
1155 B.addAlignmentAttr(Alignment);
1156 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1157 (EncodedAttrs & 0xffff));
1160 std::error_code BitcodeReader::parseAttributeBlock() {
1161 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1162 return error("Invalid record");
1164 if (!MAttributes.empty())
1165 return error("Invalid multiple blocks");
1167 SmallVector<uint64_t, 64> Record;
1169 SmallVector<AttributeSet, 8> Attrs;
1171 // Read all the records.
1173 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1175 switch (Entry.Kind) {
1176 case BitstreamEntry::SubBlock: // Handled for us already.
1177 case BitstreamEntry::Error:
1178 return error("Malformed block");
1179 case BitstreamEntry::EndBlock:
1180 return std::error_code();
1181 case BitstreamEntry::Record:
1182 // The interesting case.
1188 switch (Stream.readRecord(Entry.ID, Record)) {
1189 default: // Default behavior: ignore.
1191 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1192 // FIXME: Remove in 4.0.
1193 if (Record.size() & 1)
1194 return error("Invalid record");
1196 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1198 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1199 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1202 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1206 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1207 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1208 Attrs.push_back(MAttributeGroups[Record[i]]);
1210 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1218 // Returns Attribute::None on unrecognized codes.
1219 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1222 return Attribute::None;
1223 case bitc::ATTR_KIND_ALIGNMENT:
1224 return Attribute::Alignment;
1225 case bitc::ATTR_KIND_ALWAYS_INLINE:
1226 return Attribute::AlwaysInline;
1227 case bitc::ATTR_KIND_ARGMEMONLY:
1228 return Attribute::ArgMemOnly;
1229 case bitc::ATTR_KIND_BUILTIN:
1230 return Attribute::Builtin;
1231 case bitc::ATTR_KIND_BY_VAL:
1232 return Attribute::ByVal;
1233 case bitc::ATTR_KIND_IN_ALLOCA:
1234 return Attribute::InAlloca;
1235 case bitc::ATTR_KIND_COLD:
1236 return Attribute::Cold;
1237 case bitc::ATTR_KIND_CONVERGENT:
1238 return Attribute::Convergent;
1239 case bitc::ATTR_KIND_INLINE_HINT:
1240 return Attribute::InlineHint;
1241 case bitc::ATTR_KIND_IN_REG:
1242 return Attribute::InReg;
1243 case bitc::ATTR_KIND_JUMP_TABLE:
1244 return Attribute::JumpTable;
1245 case bitc::ATTR_KIND_MIN_SIZE:
1246 return Attribute::MinSize;
1247 case bitc::ATTR_KIND_NAKED:
1248 return Attribute::Naked;
1249 case bitc::ATTR_KIND_NEST:
1250 return Attribute::Nest;
1251 case bitc::ATTR_KIND_NO_ALIAS:
1252 return Attribute::NoAlias;
1253 case bitc::ATTR_KIND_NO_BUILTIN:
1254 return Attribute::NoBuiltin;
1255 case bitc::ATTR_KIND_NO_CAPTURE:
1256 return Attribute::NoCapture;
1257 case bitc::ATTR_KIND_NO_DUPLICATE:
1258 return Attribute::NoDuplicate;
1259 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1260 return Attribute::NoImplicitFloat;
1261 case bitc::ATTR_KIND_NO_INLINE:
1262 return Attribute::NoInline;
1263 case bitc::ATTR_KIND_NO_RECURSE:
1264 return Attribute::NoRecurse;
1265 case bitc::ATTR_KIND_NON_LAZY_BIND:
1266 return Attribute::NonLazyBind;
1267 case bitc::ATTR_KIND_NON_NULL:
1268 return Attribute::NonNull;
1269 case bitc::ATTR_KIND_DEREFERENCEABLE:
1270 return Attribute::Dereferenceable;
1271 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1272 return Attribute::DereferenceableOrNull;
1273 case bitc::ATTR_KIND_NO_RED_ZONE:
1274 return Attribute::NoRedZone;
1275 case bitc::ATTR_KIND_NO_RETURN:
1276 return Attribute::NoReturn;
1277 case bitc::ATTR_KIND_NO_UNWIND:
1278 return Attribute::NoUnwind;
1279 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1280 return Attribute::OptimizeForSize;
1281 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1282 return Attribute::OptimizeNone;
1283 case bitc::ATTR_KIND_READ_NONE:
1284 return Attribute::ReadNone;
1285 case bitc::ATTR_KIND_READ_ONLY:
1286 return Attribute::ReadOnly;
1287 case bitc::ATTR_KIND_RETURNED:
1288 return Attribute::Returned;
1289 case bitc::ATTR_KIND_RETURNS_TWICE:
1290 return Attribute::ReturnsTwice;
1291 case bitc::ATTR_KIND_S_EXT:
1292 return Attribute::SExt;
1293 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1294 return Attribute::StackAlignment;
1295 case bitc::ATTR_KIND_STACK_PROTECT:
1296 return Attribute::StackProtect;
1297 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1298 return Attribute::StackProtectReq;
1299 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1300 return Attribute::StackProtectStrong;
1301 case bitc::ATTR_KIND_SAFESTACK:
1302 return Attribute::SafeStack;
1303 case bitc::ATTR_KIND_STRUCT_RET:
1304 return Attribute::StructRet;
1305 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1306 return Attribute::SanitizeAddress;
1307 case bitc::ATTR_KIND_SANITIZE_THREAD:
1308 return Attribute::SanitizeThread;
1309 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1310 return Attribute::SanitizeMemory;
1311 case bitc::ATTR_KIND_UW_TABLE:
1312 return Attribute::UWTable;
1313 case bitc::ATTR_KIND_Z_EXT:
1314 return Attribute::ZExt;
1318 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1319 unsigned &Alignment) {
1320 // Note: Alignment in bitcode files is incremented by 1, so that zero
1321 // can be used for default alignment.
1322 if (Exponent > Value::MaxAlignmentExponent + 1)
1323 return error("Invalid alignment value");
1324 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1325 return std::error_code();
1328 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1329 Attribute::AttrKind *Kind) {
1330 *Kind = getAttrFromCode(Code);
1331 if (*Kind == Attribute::None)
1332 return error(BitcodeError::CorruptedBitcode,
1333 "Unknown attribute kind (" + Twine(Code) + ")");
1334 return std::error_code();
1337 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1338 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1339 return error("Invalid record");
1341 if (!MAttributeGroups.empty())
1342 return error("Invalid multiple blocks");
1344 SmallVector<uint64_t, 64> Record;
1346 // Read all the records.
1348 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1350 switch (Entry.Kind) {
1351 case BitstreamEntry::SubBlock: // Handled for us already.
1352 case BitstreamEntry::Error:
1353 return error("Malformed block");
1354 case BitstreamEntry::EndBlock:
1355 return std::error_code();
1356 case BitstreamEntry::Record:
1357 // The interesting case.
1363 switch (Stream.readRecord(Entry.ID, Record)) {
1364 default: // Default behavior: ignore.
1366 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1367 if (Record.size() < 3)
1368 return error("Invalid record");
1370 uint64_t GrpID = Record[0];
1371 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1374 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1375 if (Record[i] == 0) { // Enum attribute
1376 Attribute::AttrKind Kind;
1377 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1380 B.addAttribute(Kind);
1381 } else if (Record[i] == 1) { // Integer attribute
1382 Attribute::AttrKind Kind;
1383 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1385 if (Kind == Attribute::Alignment)
1386 B.addAlignmentAttr(Record[++i]);
1387 else if (Kind == Attribute::StackAlignment)
1388 B.addStackAlignmentAttr(Record[++i]);
1389 else if (Kind == Attribute::Dereferenceable)
1390 B.addDereferenceableAttr(Record[++i]);
1391 else if (Kind == Attribute::DereferenceableOrNull)
1392 B.addDereferenceableOrNullAttr(Record[++i]);
1393 } else { // String attribute
1394 assert((Record[i] == 3 || Record[i] == 4) &&
1395 "Invalid attribute group entry");
1396 bool HasValue = (Record[i++] == 4);
1397 SmallString<64> KindStr;
1398 SmallString<64> ValStr;
1400 while (Record[i] != 0 && i != e)
1401 KindStr += Record[i++];
1402 assert(Record[i] == 0 && "Kind string not null terminated");
1405 // Has a value associated with it.
1406 ++i; // Skip the '0' that terminates the "kind" string.
1407 while (Record[i] != 0 && i != e)
1408 ValStr += Record[i++];
1409 assert(Record[i] == 0 && "Value string not null terminated");
1412 B.addAttribute(KindStr.str(), ValStr.str());
1416 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1423 std::error_code BitcodeReader::parseTypeTable() {
1424 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1425 return error("Invalid record");
1427 return parseTypeTableBody();
1430 std::error_code BitcodeReader::parseTypeTableBody() {
1431 if (!TypeList.empty())
1432 return error("Invalid multiple blocks");
1434 SmallVector<uint64_t, 64> Record;
1435 unsigned NumRecords = 0;
1437 SmallString<64> TypeName;
1439 // Read all the records for this type table.
1441 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1443 switch (Entry.Kind) {
1444 case BitstreamEntry::SubBlock: // Handled for us already.
1445 case BitstreamEntry::Error:
1446 return error("Malformed block");
1447 case BitstreamEntry::EndBlock:
1448 if (NumRecords != TypeList.size())
1449 return error("Malformed block");
1450 return std::error_code();
1451 case BitstreamEntry::Record:
1452 // The interesting case.
1458 Type *ResultTy = nullptr;
1459 switch (Stream.readRecord(Entry.ID, Record)) {
1461 return error("Invalid value");
1462 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1463 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1464 // type list. This allows us to reserve space.
1465 if (Record.size() < 1)
1466 return error("Invalid record");
1467 TypeList.resize(Record[0]);
1469 case bitc::TYPE_CODE_VOID: // VOID
1470 ResultTy = Type::getVoidTy(Context);
1472 case bitc::TYPE_CODE_HALF: // HALF
1473 ResultTy = Type::getHalfTy(Context);
1475 case bitc::TYPE_CODE_FLOAT: // FLOAT
1476 ResultTy = Type::getFloatTy(Context);
1478 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1479 ResultTy = Type::getDoubleTy(Context);
1481 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1482 ResultTy = Type::getX86_FP80Ty(Context);
1484 case bitc::TYPE_CODE_FP128: // FP128
1485 ResultTy = Type::getFP128Ty(Context);
1487 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1488 ResultTy = Type::getPPC_FP128Ty(Context);
1490 case bitc::TYPE_CODE_LABEL: // LABEL
1491 ResultTy = Type::getLabelTy(Context);
1493 case bitc::TYPE_CODE_METADATA: // METADATA
1494 ResultTy = Type::getMetadataTy(Context);
1496 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1497 ResultTy = Type::getX86_MMXTy(Context);
1499 case bitc::TYPE_CODE_TOKEN: // TOKEN
1500 ResultTy = Type::getTokenTy(Context);
1502 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1503 if (Record.size() < 1)
1504 return error("Invalid record");
1506 uint64_t NumBits = Record[0];
1507 if (NumBits < IntegerType::MIN_INT_BITS ||
1508 NumBits > IntegerType::MAX_INT_BITS)
1509 return error("Bitwidth for integer type out of range");
1510 ResultTy = IntegerType::get(Context, NumBits);
1513 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1514 // [pointee type, address space]
1515 if (Record.size() < 1)
1516 return error("Invalid record");
1517 unsigned AddressSpace = 0;
1518 if (Record.size() == 2)
1519 AddressSpace = Record[1];
1520 ResultTy = getTypeByID(Record[0]);
1522 !PointerType::isValidElementType(ResultTy))
1523 return error("Invalid type");
1524 ResultTy = PointerType::get(ResultTy, AddressSpace);
1527 case bitc::TYPE_CODE_FUNCTION_OLD: {
1528 // FIXME: attrid is dead, remove it in LLVM 4.0
1529 // FUNCTION: [vararg, attrid, retty, paramty x N]
1530 if (Record.size() < 3)
1531 return error("Invalid record");
1532 SmallVector<Type*, 8> ArgTys;
1533 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1534 if (Type *T = getTypeByID(Record[i]))
1535 ArgTys.push_back(T);
1540 ResultTy = getTypeByID(Record[2]);
1541 if (!ResultTy || ArgTys.size() < Record.size()-3)
1542 return error("Invalid type");
1544 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1547 case bitc::TYPE_CODE_FUNCTION: {
1548 // FUNCTION: [vararg, retty, paramty x N]
1549 if (Record.size() < 2)
1550 return error("Invalid record");
1551 SmallVector<Type*, 8> ArgTys;
1552 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1553 if (Type *T = getTypeByID(Record[i])) {
1554 if (!FunctionType::isValidArgumentType(T))
1555 return error("Invalid function argument type");
1556 ArgTys.push_back(T);
1562 ResultTy = getTypeByID(Record[1]);
1563 if (!ResultTy || ArgTys.size() < Record.size()-2)
1564 return error("Invalid type");
1566 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1569 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1570 if (Record.size() < 1)
1571 return error("Invalid record");
1572 SmallVector<Type*, 8> EltTys;
1573 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1574 if (Type *T = getTypeByID(Record[i]))
1575 EltTys.push_back(T);
1579 if (EltTys.size() != Record.size()-1)
1580 return error("Invalid type");
1581 ResultTy = StructType::get(Context, EltTys, Record[0]);
1584 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1585 if (convertToString(Record, 0, TypeName))
1586 return error("Invalid record");
1589 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1590 if (Record.size() < 1)
1591 return error("Invalid record");
1593 if (NumRecords >= TypeList.size())
1594 return error("Invalid TYPE table");
1596 // Check to see if this was forward referenced, if so fill in the temp.
1597 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1599 Res->setName(TypeName);
1600 TypeList[NumRecords] = nullptr;
1601 } else // Otherwise, create a new struct.
1602 Res = createIdentifiedStructType(Context, TypeName);
1605 SmallVector<Type*, 8> EltTys;
1606 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1607 if (Type *T = getTypeByID(Record[i]))
1608 EltTys.push_back(T);
1612 if (EltTys.size() != Record.size()-1)
1613 return error("Invalid record");
1614 Res->setBody(EltTys, Record[0]);
1618 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1619 if (Record.size() != 1)
1620 return error("Invalid record");
1622 if (NumRecords >= TypeList.size())
1623 return error("Invalid TYPE table");
1625 // Check to see if this was forward referenced, if so fill in the temp.
1626 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1628 Res->setName(TypeName);
1629 TypeList[NumRecords] = nullptr;
1630 } else // Otherwise, create a new struct with no body.
1631 Res = createIdentifiedStructType(Context, TypeName);
1636 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1637 if (Record.size() < 2)
1638 return error("Invalid record");
1639 ResultTy = getTypeByID(Record[1]);
1640 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1641 return error("Invalid type");
1642 ResultTy = ArrayType::get(ResultTy, Record[0]);
1644 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1645 if (Record.size() < 2)
1646 return error("Invalid record");
1648 return error("Invalid vector length");
1649 ResultTy = getTypeByID(Record[1]);
1650 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1651 return error("Invalid type");
1652 ResultTy = VectorType::get(ResultTy, Record[0]);
1656 if (NumRecords >= TypeList.size())
1657 return error("Invalid TYPE table");
1658 if (TypeList[NumRecords])
1660 "Invalid TYPE table: Only named structs can be forward referenced");
1661 assert(ResultTy && "Didn't read a type?");
1662 TypeList[NumRecords++] = ResultTy;
1666 std::error_code BitcodeReader::parseOperandBundleTags() {
1667 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1668 return error("Invalid record");
1670 if (!BundleTags.empty())
1671 return error("Invalid multiple blocks");
1673 SmallVector<uint64_t, 64> Record;
1676 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1678 switch (Entry.Kind) {
1679 case BitstreamEntry::SubBlock: // Handled for us already.
1680 case BitstreamEntry::Error:
1681 return error("Malformed block");
1682 case BitstreamEntry::EndBlock:
1683 return std::error_code();
1684 case BitstreamEntry::Record:
1685 // The interesting case.
1689 // Tags are implicitly mapped to integers by their order.
1691 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1692 return error("Invalid record");
1694 // OPERAND_BUNDLE_TAG: [strchr x N]
1695 BundleTags.emplace_back();
1696 if (convertToString(Record, 0, BundleTags.back()))
1697 return error("Invalid record");
1702 /// Associate a value with its name from the given index in the provided record.
1703 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1704 unsigned NameIndex, Triple &TT) {
1705 SmallString<128> ValueName;
1706 if (convertToString(Record, NameIndex, ValueName))
1707 return error("Invalid record");
1708 unsigned ValueID = Record[0];
1709 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1710 return error("Invalid record");
1711 Value *V = ValueList[ValueID];
1713 StringRef NameStr(ValueName.data(), ValueName.size());
1714 if (NameStr.find_first_of(0) != StringRef::npos)
1715 return error("Invalid value name");
1716 V->setName(NameStr);
1717 auto *GO = dyn_cast<GlobalObject>(V);
1719 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1720 if (TT.isOSBinFormatMachO())
1721 GO->setComdat(nullptr);
1723 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1729 /// Parse the value symbol table at either the current parsing location or
1730 /// at the given bit offset if provided.
1731 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1732 uint64_t CurrentBit;
1733 // Pass in the Offset to distinguish between calling for the module-level
1734 // VST (where we want to jump to the VST offset) and the function-level
1735 // VST (where we don't).
1737 // Save the current parsing location so we can jump back at the end
1739 CurrentBit = Stream.GetCurrentBitNo();
1740 Stream.JumpToBit(Offset * 32);
1742 // Do some checking if we are in debug mode.
1743 BitstreamEntry Entry = Stream.advance();
1744 assert(Entry.Kind == BitstreamEntry::SubBlock);
1745 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1747 // In NDEBUG mode ignore the output so we don't get an unused variable
1753 // Compute the delta between the bitcode indices in the VST (the word offset
1754 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1755 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1756 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1757 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1758 // just before entering the VST subblock because: 1) the EnterSubBlock
1759 // changes the AbbrevID width; 2) the VST block is nested within the same
1760 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1761 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1762 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1763 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1764 unsigned FuncBitcodeOffsetDelta =
1765 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1767 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1768 return error("Invalid record");
1770 SmallVector<uint64_t, 64> Record;
1772 Triple TT(TheModule->getTargetTriple());
1774 // Read all the records for this value table.
1775 SmallString<128> ValueName;
1777 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1779 switch (Entry.Kind) {
1780 case BitstreamEntry::SubBlock: // Handled for us already.
1781 case BitstreamEntry::Error:
1782 return error("Malformed block");
1783 case BitstreamEntry::EndBlock:
1785 Stream.JumpToBit(CurrentBit);
1786 return std::error_code();
1787 case BitstreamEntry::Record:
1788 // The interesting case.
1794 switch (Stream.readRecord(Entry.ID, Record)) {
1795 default: // Default behavior: unknown type.
1797 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1798 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1799 if (std::error_code EC = ValOrErr.getError())
1804 case bitc::VST_CODE_FNENTRY: {
1805 // VST_FNENTRY: [valueid, offset, namechar x N]
1806 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1807 if (std::error_code EC = ValOrErr.getError())
1809 Value *V = ValOrErr.get();
1811 auto *GO = dyn_cast<GlobalObject>(V);
1813 // If this is an alias, need to get the actual Function object
1814 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1815 auto *GA = dyn_cast<GlobalAlias>(V);
1817 GO = GA->getBaseObject();
1821 uint64_t FuncWordOffset = Record[1];
1822 Function *F = dyn_cast<Function>(GO);
1824 uint64_t FuncBitOffset = FuncWordOffset * 32;
1825 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1826 // Set the LastFunctionBlockBit to point to the last function block.
1827 // Later when parsing is resumed after function materialization,
1828 // we can simply skip that last function block.
1829 if (FuncBitOffset > LastFunctionBlockBit)
1830 LastFunctionBlockBit = FuncBitOffset;
1833 case bitc::VST_CODE_BBENTRY: {
1834 if (convertToString(Record, 1, ValueName))
1835 return error("Invalid record");
1836 BasicBlock *BB = getBasicBlock(Record[0]);
1838 return error("Invalid record");
1840 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1848 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1850 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1851 if (Record.size() < 2)
1852 return error("Invalid record");
1854 unsigned Kind = Record[0];
1855 SmallString<8> Name(Record.begin() + 1, Record.end());
1857 unsigned NewKind = TheModule->getMDKindID(Name.str());
1858 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1859 return error("Conflicting METADATA_KIND records");
1860 return std::error_code();
1863 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1865 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1866 /// module level metadata.
1867 std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
1868 IsMetadataMaterialized = true;
1869 unsigned NextMDValueNo = MDValueList.size();
1870 if (ModuleLevel && SeenModuleValuesRecord) {
1871 // Now that we are parsing the module level metadata, we want to restart
1872 // the numbering of the MD values, and replace temp MD created earlier
1873 // with their real values. If we saw a METADATA_VALUE record then we
1874 // would have set the MDValueList size to the number specified in that
1875 // record, to support parsing function-level metadata first, and we need
1876 // to reset back to 0 to fill the MDValueList in with the parsed module
1877 // The function-level metadata parsing should have reset the MDValueList
1878 // size back to the value reported by the METADATA_VALUE record, saved in
1880 assert(NumModuleMDs == MDValueList.size() &&
1881 "Expected MDValueList to only contain module level values");
1885 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1886 return error("Invalid record");
1888 SmallVector<uint64_t, 64> Record;
1891 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1892 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1894 return getMD(ID - 1);
1897 auto getMDString = [&](unsigned ID) -> MDString *{
1898 // This requires that the ID is not really a forward reference. In
1899 // particular, the MDString must already have been resolved.
1900 return cast_or_null<MDString>(getMDOrNull(ID));
1903 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1904 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1906 // Read all the records.
1908 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1910 switch (Entry.Kind) {
1911 case BitstreamEntry::SubBlock: // Handled for us already.
1912 case BitstreamEntry::Error:
1913 return error("Malformed block");
1914 case BitstreamEntry::EndBlock:
1915 MDValueList.tryToResolveCycles();
1916 assert((!(ModuleLevel && SeenModuleValuesRecord) ||
1917 NumModuleMDs == MDValueList.size()) &&
1918 "Inconsistent bitcode: METADATA_VALUES mismatch");
1919 return std::error_code();
1920 case BitstreamEntry::Record:
1921 // The interesting case.
1927 unsigned Code = Stream.readRecord(Entry.ID, Record);
1928 bool IsDistinct = false;
1930 default: // Default behavior: ignore.
1932 case bitc::METADATA_NAME: {
1933 // Read name of the named metadata.
1934 SmallString<8> Name(Record.begin(), Record.end());
1936 Code = Stream.ReadCode();
1938 unsigned NextBitCode = Stream.readRecord(Code, Record);
1939 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1940 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1942 // Read named metadata elements.
1943 unsigned Size = Record.size();
1944 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1945 for (unsigned i = 0; i != Size; ++i) {
1946 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1948 return error("Invalid record");
1949 NMD->addOperand(MD);
1953 case bitc::METADATA_OLD_FN_NODE: {
1954 // FIXME: Remove in 4.0.
1955 // This is a LocalAsMetadata record, the only type of function-local
1957 if (Record.size() % 2 == 1)
1958 return error("Invalid record");
1960 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1961 // to be legal, but there's no upgrade path.
1962 auto dropRecord = [&] {
1963 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1965 if (Record.size() != 2) {
1970 Type *Ty = getTypeByID(Record[0]);
1971 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1976 MDValueList.assignValue(
1977 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1981 case bitc::METADATA_OLD_NODE: {
1982 // FIXME: Remove in 4.0.
1983 if (Record.size() % 2 == 1)
1984 return error("Invalid record");
1986 unsigned Size = Record.size();
1987 SmallVector<Metadata *, 8> Elts;
1988 for (unsigned i = 0; i != Size; i += 2) {
1989 Type *Ty = getTypeByID(Record[i]);
1991 return error("Invalid record");
1992 if (Ty->isMetadataTy())
1993 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1994 else if (!Ty->isVoidTy()) {
1996 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1997 assert(isa<ConstantAsMetadata>(MD) &&
1998 "Expected non-function-local metadata");
2001 Elts.push_back(nullptr);
2003 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2006 case bitc::METADATA_VALUE: {
2007 if (Record.size() != 2)
2008 return error("Invalid record");
2010 Type *Ty = getTypeByID(Record[0]);
2011 if (Ty->isMetadataTy() || Ty->isVoidTy())
2012 return error("Invalid record");
2014 MDValueList.assignValue(
2015 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2019 case bitc::METADATA_DISTINCT_NODE:
2022 case bitc::METADATA_NODE: {
2023 SmallVector<Metadata *, 8> Elts;
2024 Elts.reserve(Record.size());
2025 for (unsigned ID : Record)
2026 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2027 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2028 : MDNode::get(Context, Elts),
2032 case bitc::METADATA_LOCATION: {
2033 if (Record.size() != 5)
2034 return error("Invalid record");
2036 unsigned Line = Record[1];
2037 unsigned Column = Record[2];
2038 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2039 Metadata *InlinedAt =
2040 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2041 MDValueList.assignValue(
2042 GET_OR_DISTINCT(DILocation, Record[0],
2043 (Context, Line, Column, Scope, InlinedAt)),
2047 case bitc::METADATA_GENERIC_DEBUG: {
2048 if (Record.size() < 4)
2049 return error("Invalid record");
2051 unsigned Tag = Record[1];
2052 unsigned Version = Record[2];
2054 if (Tag >= 1u << 16 || Version != 0)
2055 return error("Invalid record");
2057 auto *Header = getMDString(Record[3]);
2058 SmallVector<Metadata *, 8> DwarfOps;
2059 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2060 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2062 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2063 (Context, Tag, Header, DwarfOps)),
2067 case bitc::METADATA_SUBRANGE: {
2068 if (Record.size() != 3)
2069 return error("Invalid record");
2071 MDValueList.assignValue(
2072 GET_OR_DISTINCT(DISubrange, Record[0],
2073 (Context, Record[1], unrotateSign(Record[2]))),
2077 case bitc::METADATA_ENUMERATOR: {
2078 if (Record.size() != 3)
2079 return error("Invalid record");
2081 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2082 (Context, unrotateSign(Record[1]),
2083 getMDString(Record[2]))),
2087 case bitc::METADATA_BASIC_TYPE: {
2088 if (Record.size() != 6)
2089 return error("Invalid record");
2091 MDValueList.assignValue(
2092 GET_OR_DISTINCT(DIBasicType, Record[0],
2093 (Context, Record[1], getMDString(Record[2]),
2094 Record[3], Record[4], Record[5])),
2098 case bitc::METADATA_DERIVED_TYPE: {
2099 if (Record.size() != 12)
2100 return error("Invalid record");
2102 MDValueList.assignValue(
2103 GET_OR_DISTINCT(DIDerivedType, Record[0],
2104 (Context, Record[1], getMDString(Record[2]),
2105 getMDOrNull(Record[3]), Record[4],
2106 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2107 Record[7], Record[8], Record[9], Record[10],
2108 getMDOrNull(Record[11]))),
2112 case bitc::METADATA_COMPOSITE_TYPE: {
2113 if (Record.size() != 16)
2114 return error("Invalid record");
2116 MDValueList.assignValue(
2117 GET_OR_DISTINCT(DICompositeType, Record[0],
2118 (Context, Record[1], getMDString(Record[2]),
2119 getMDOrNull(Record[3]), Record[4],
2120 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2121 Record[7], Record[8], Record[9], Record[10],
2122 getMDOrNull(Record[11]), Record[12],
2123 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2124 getMDString(Record[15]))),
2128 case bitc::METADATA_SUBROUTINE_TYPE: {
2129 if (Record.size() != 3)
2130 return error("Invalid record");
2132 MDValueList.assignValue(
2133 GET_OR_DISTINCT(DISubroutineType, Record[0],
2134 (Context, Record[1], getMDOrNull(Record[2]))),
2139 case bitc::METADATA_MODULE: {
2140 if (Record.size() != 6)
2141 return error("Invalid record");
2143 MDValueList.assignValue(
2144 GET_OR_DISTINCT(DIModule, Record[0],
2145 (Context, getMDOrNull(Record[1]),
2146 getMDString(Record[2]), getMDString(Record[3]),
2147 getMDString(Record[4]), getMDString(Record[5]))),
2152 case bitc::METADATA_FILE: {
2153 if (Record.size() != 3)
2154 return error("Invalid record");
2156 MDValueList.assignValue(
2157 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2158 getMDString(Record[2]))),
2162 case bitc::METADATA_COMPILE_UNIT: {
2163 if (Record.size() < 14 || Record.size() > 16)
2164 return error("Invalid record");
2166 // Ignore Record[0], which indicates whether this compile unit is
2167 // distinct. It's always distinct.
2168 MDValueList.assignValue(
2169 DICompileUnit::getDistinct(
2170 Context, Record[1], getMDOrNull(Record[2]),
2171 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2172 Record[6], getMDString(Record[7]), Record[8],
2173 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2174 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2175 getMDOrNull(Record[13]),
2176 Record.size() <= 15 ? 0 : getMDOrNull(Record[15]),
2177 Record.size() <= 14 ? 0 : Record[14]),
2181 case bitc::METADATA_SUBPROGRAM: {
2182 if (Record.size() != 18 && Record.size() != 19)
2183 return error("Invalid record");
2185 bool HasFn = Record.size() == 19;
2186 DISubprogram *SP = GET_OR_DISTINCT(
2188 Record[0] || Record[8], // All definitions should be distinct.
2189 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2190 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2191 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2192 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2193 Record[14], getMDOrNull(Record[15 + HasFn]),
2194 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2195 MDValueList.assignValue(SP, NextMDValueNo++);
2197 // Upgrade sp->function mapping to function->sp mapping.
2198 if (HasFn && Record[15]) {
2199 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2200 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2201 if (F->isMaterializable())
2202 // Defer until materialized; unmaterialized functions may not have
2204 FunctionsWithSPs[F] = SP;
2205 else if (!F->empty())
2206 F->setSubprogram(SP);
2211 case bitc::METADATA_LEXICAL_BLOCK: {
2212 if (Record.size() != 5)
2213 return error("Invalid record");
2215 MDValueList.assignValue(
2216 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2217 (Context, getMDOrNull(Record[1]),
2218 getMDOrNull(Record[2]), Record[3], Record[4])),
2222 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2223 if (Record.size() != 4)
2224 return error("Invalid record");
2226 MDValueList.assignValue(
2227 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2228 (Context, getMDOrNull(Record[1]),
2229 getMDOrNull(Record[2]), Record[3])),
2233 case bitc::METADATA_NAMESPACE: {
2234 if (Record.size() != 5)
2235 return error("Invalid record");
2237 MDValueList.assignValue(
2238 GET_OR_DISTINCT(DINamespace, Record[0],
2239 (Context, getMDOrNull(Record[1]),
2240 getMDOrNull(Record[2]), getMDString(Record[3]),
2245 case bitc::METADATA_MACRO: {
2246 if (Record.size() != 5)
2247 return error("Invalid record");
2249 MDValueList.assignValue(
2250 GET_OR_DISTINCT(DIMacro, Record[0],
2251 (Context, Record[1], Record[2],
2252 getMDString(Record[3]), getMDString(Record[4]))),
2256 case bitc::METADATA_MACRO_FILE: {
2257 if (Record.size() != 5)
2258 return error("Invalid record");
2260 MDValueList.assignValue(
2261 GET_OR_DISTINCT(DIMacroFile, Record[0],
2262 (Context, Record[1], Record[2],
2263 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2267 case bitc::METADATA_TEMPLATE_TYPE: {
2268 if (Record.size() != 3)
2269 return error("Invalid record");
2271 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2273 (Context, getMDString(Record[1]),
2274 getMDOrNull(Record[2]))),
2278 case bitc::METADATA_TEMPLATE_VALUE: {
2279 if (Record.size() != 5)
2280 return error("Invalid record");
2282 MDValueList.assignValue(
2283 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2284 (Context, Record[1], getMDString(Record[2]),
2285 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2289 case bitc::METADATA_GLOBAL_VAR: {
2290 if (Record.size() != 11)
2291 return error("Invalid record");
2293 MDValueList.assignValue(
2294 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2295 (Context, getMDOrNull(Record[1]),
2296 getMDString(Record[2]), getMDString(Record[3]),
2297 getMDOrNull(Record[4]), Record[5],
2298 getMDOrNull(Record[6]), Record[7], Record[8],
2299 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2303 case bitc::METADATA_LOCAL_VAR: {
2304 // 10th field is for the obseleted 'inlinedAt:' field.
2305 if (Record.size() < 8 || Record.size() > 10)
2306 return error("Invalid record");
2308 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2309 // DW_TAG_arg_variable.
2310 bool HasTag = Record.size() > 8;
2311 MDValueList.assignValue(
2312 GET_OR_DISTINCT(DILocalVariable, Record[0],
2313 (Context, getMDOrNull(Record[1 + HasTag]),
2314 getMDString(Record[2 + HasTag]),
2315 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2316 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2317 Record[7 + HasTag])),
2321 case bitc::METADATA_EXPRESSION: {
2322 if (Record.size() < 1)
2323 return error("Invalid record");
2325 MDValueList.assignValue(
2326 GET_OR_DISTINCT(DIExpression, Record[0],
2327 (Context, makeArrayRef(Record).slice(1))),
2331 case bitc::METADATA_OBJC_PROPERTY: {
2332 if (Record.size() != 8)
2333 return error("Invalid record");
2335 MDValueList.assignValue(
2336 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2337 (Context, getMDString(Record[1]),
2338 getMDOrNull(Record[2]), Record[3],
2339 getMDString(Record[4]), getMDString(Record[5]),
2340 Record[6], getMDOrNull(Record[7]))),
2344 case bitc::METADATA_IMPORTED_ENTITY: {
2345 if (Record.size() != 6)
2346 return error("Invalid record");
2348 MDValueList.assignValue(
2349 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2350 (Context, Record[1], getMDOrNull(Record[2]),
2351 getMDOrNull(Record[3]), Record[4],
2352 getMDString(Record[5]))),
2356 case bitc::METADATA_STRING: {
2357 std::string String(Record.begin(), Record.end());
2358 llvm::UpgradeMDStringConstant(String);
2359 Metadata *MD = MDString::get(Context, String);
2360 MDValueList.assignValue(MD, NextMDValueNo++);
2363 case bitc::METADATA_KIND: {
2364 // Support older bitcode files that had METADATA_KIND records in a
2365 // block with METADATA_BLOCK_ID.
2366 if (std::error_code EC = parseMetadataKindRecord(Record))
2372 #undef GET_OR_DISTINCT
2375 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2376 std::error_code BitcodeReader::parseMetadataKinds() {
2377 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2378 return error("Invalid record");
2380 SmallVector<uint64_t, 64> Record;
2382 // Read all the records.
2384 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2386 switch (Entry.Kind) {
2387 case BitstreamEntry::SubBlock: // Handled for us already.
2388 case BitstreamEntry::Error:
2389 return error("Malformed block");
2390 case BitstreamEntry::EndBlock:
2391 return std::error_code();
2392 case BitstreamEntry::Record:
2393 // The interesting case.
2399 unsigned Code = Stream.readRecord(Entry.ID, Record);
2401 default: // Default behavior: ignore.
2403 case bitc::METADATA_KIND: {
2404 if (std::error_code EC = parseMetadataKindRecord(Record))
2412 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2414 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2419 // There is no such thing as -0 with integers. "-0" really means MININT.
2423 /// Resolve all of the initializers for global values and aliases that we can.
2424 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2425 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2426 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2427 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2428 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2429 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2431 GlobalInitWorklist.swap(GlobalInits);
2432 AliasInitWorklist.swap(AliasInits);
2433 FunctionPrefixWorklist.swap(FunctionPrefixes);
2434 FunctionPrologueWorklist.swap(FunctionPrologues);
2435 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2437 while (!GlobalInitWorklist.empty()) {
2438 unsigned ValID = GlobalInitWorklist.back().second;
2439 if (ValID >= ValueList.size()) {
2440 // Not ready to resolve this yet, it requires something later in the file.
2441 GlobalInits.push_back(GlobalInitWorklist.back());
2443 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2444 GlobalInitWorklist.back().first->setInitializer(C);
2446 return error("Expected a constant");
2448 GlobalInitWorklist.pop_back();
2451 while (!AliasInitWorklist.empty()) {
2452 unsigned ValID = AliasInitWorklist.back().second;
2453 if (ValID >= ValueList.size()) {
2454 AliasInits.push_back(AliasInitWorklist.back());
2456 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2458 return error("Expected a constant");
2459 GlobalAlias *Alias = AliasInitWorklist.back().first;
2460 if (C->getType() != Alias->getType())
2461 return error("Alias and aliasee types don't match");
2462 Alias->setAliasee(C);
2464 AliasInitWorklist.pop_back();
2467 while (!FunctionPrefixWorklist.empty()) {
2468 unsigned ValID = FunctionPrefixWorklist.back().second;
2469 if (ValID >= ValueList.size()) {
2470 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2472 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2473 FunctionPrefixWorklist.back().first->setPrefixData(C);
2475 return error("Expected a constant");
2477 FunctionPrefixWorklist.pop_back();
2480 while (!FunctionPrologueWorklist.empty()) {
2481 unsigned ValID = FunctionPrologueWorklist.back().second;
2482 if (ValID >= ValueList.size()) {
2483 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2485 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2486 FunctionPrologueWorklist.back().first->setPrologueData(C);
2488 return error("Expected a constant");
2490 FunctionPrologueWorklist.pop_back();
2493 while (!FunctionPersonalityFnWorklist.empty()) {
2494 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2495 if (ValID >= ValueList.size()) {
2496 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2498 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2499 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2501 return error("Expected a constant");
2503 FunctionPersonalityFnWorklist.pop_back();
2506 return std::error_code();
2509 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2510 SmallVector<uint64_t, 8> Words(Vals.size());
2511 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2512 BitcodeReader::decodeSignRotatedValue);
2514 return APInt(TypeBits, Words);
2517 std::error_code BitcodeReader::parseConstants() {
2518 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2519 return error("Invalid record");
2521 SmallVector<uint64_t, 64> Record;
2523 // Read all the records for this value table.
2524 Type *CurTy = Type::getInt32Ty(Context);
2525 unsigned NextCstNo = ValueList.size();
2527 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2529 switch (Entry.Kind) {
2530 case BitstreamEntry::SubBlock: // Handled for us already.
2531 case BitstreamEntry::Error:
2532 return error("Malformed block");
2533 case BitstreamEntry::EndBlock:
2534 if (NextCstNo != ValueList.size())
2535 return error("Invalid ronstant reference");
2537 // Once all the constants have been read, go through and resolve forward
2539 ValueList.resolveConstantForwardRefs();
2540 return std::error_code();
2541 case BitstreamEntry::Record:
2542 // The interesting case.
2549 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2551 default: // Default behavior: unknown constant
2552 case bitc::CST_CODE_UNDEF: // UNDEF
2553 V = UndefValue::get(CurTy);
2555 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2557 return error("Invalid record");
2558 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2559 return error("Invalid record");
2560 CurTy = TypeList[Record[0]];
2561 continue; // Skip the ValueList manipulation.
2562 case bitc::CST_CODE_NULL: // NULL
2563 V = Constant::getNullValue(CurTy);
2565 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2566 if (!CurTy->isIntegerTy() || Record.empty())
2567 return error("Invalid record");
2568 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2570 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2571 if (!CurTy->isIntegerTy() || Record.empty())
2572 return error("Invalid record");
2575 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2576 V = ConstantInt::get(Context, VInt);
2580 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2582 return error("Invalid record");
2583 if (CurTy->isHalfTy())
2584 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2585 APInt(16, (uint16_t)Record[0])));
2586 else if (CurTy->isFloatTy())
2587 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2588 APInt(32, (uint32_t)Record[0])));
2589 else if (CurTy->isDoubleTy())
2590 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2591 APInt(64, Record[0])));
2592 else if (CurTy->isX86_FP80Ty()) {
2593 // Bits are not stored the same way as a normal i80 APInt, compensate.
2594 uint64_t Rearrange[2];
2595 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2596 Rearrange[1] = Record[0] >> 48;
2597 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2598 APInt(80, Rearrange)));
2599 } else if (CurTy->isFP128Ty())
2600 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2601 APInt(128, Record)));
2602 else if (CurTy->isPPC_FP128Ty())
2603 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2604 APInt(128, Record)));
2606 V = UndefValue::get(CurTy);
2610 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2612 return error("Invalid record");
2614 unsigned Size = Record.size();
2615 SmallVector<Constant*, 16> Elts;
2617 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2618 for (unsigned i = 0; i != Size; ++i)
2619 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2620 STy->getElementType(i)));
2621 V = ConstantStruct::get(STy, Elts);
2622 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2623 Type *EltTy = ATy->getElementType();
2624 for (unsigned i = 0; i != Size; ++i)
2625 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2626 V = ConstantArray::get(ATy, Elts);
2627 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2628 Type *EltTy = VTy->getElementType();
2629 for (unsigned i = 0; i != Size; ++i)
2630 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2631 V = ConstantVector::get(Elts);
2633 V = UndefValue::get(CurTy);
2637 case bitc::CST_CODE_STRING: // STRING: [values]
2638 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2640 return error("Invalid record");
2642 SmallString<16> Elts(Record.begin(), Record.end());
2643 V = ConstantDataArray::getString(Context, Elts,
2644 BitCode == bitc::CST_CODE_CSTRING);
2647 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2649 return error("Invalid record");
2651 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2652 unsigned Size = Record.size();
2654 if (EltTy->isIntegerTy(8)) {
2655 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2656 if (isa<VectorType>(CurTy))
2657 V = ConstantDataVector::get(Context, Elts);
2659 V = ConstantDataArray::get(Context, Elts);
2660 } else if (EltTy->isIntegerTy(16)) {
2661 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2662 if (isa<VectorType>(CurTy))
2663 V = ConstantDataVector::get(Context, Elts);
2665 V = ConstantDataArray::get(Context, Elts);
2666 } else if (EltTy->isIntegerTy(32)) {
2667 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2668 if (isa<VectorType>(CurTy))
2669 V = ConstantDataVector::get(Context, Elts);
2671 V = ConstantDataArray::get(Context, Elts);
2672 } else if (EltTy->isIntegerTy(64)) {
2673 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2674 if (isa<VectorType>(CurTy))
2675 V = ConstantDataVector::get(Context, Elts);
2677 V = ConstantDataArray::get(Context, Elts);
2678 } else if (EltTy->isFloatTy()) {
2679 SmallVector<float, 16> Elts(Size);
2680 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2681 if (isa<VectorType>(CurTy))
2682 V = ConstantDataVector::get(Context, Elts);
2684 V = ConstantDataArray::get(Context, Elts);
2685 } else if (EltTy->isDoubleTy()) {
2686 SmallVector<double, 16> Elts(Size);
2687 std::transform(Record.begin(), Record.end(), Elts.begin(),
2689 if (isa<VectorType>(CurTy))
2690 V = ConstantDataVector::get(Context, Elts);
2692 V = ConstantDataArray::get(Context, Elts);
2694 return error("Invalid type for value");
2699 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2700 if (Record.size() < 3)
2701 return error("Invalid record");
2702 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2704 V = UndefValue::get(CurTy); // Unknown binop.
2706 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2707 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2709 if (Record.size() >= 4) {
2710 if (Opc == Instruction::Add ||
2711 Opc == Instruction::Sub ||
2712 Opc == Instruction::Mul ||
2713 Opc == Instruction::Shl) {
2714 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2715 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2716 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2717 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2718 } else if (Opc == Instruction::SDiv ||
2719 Opc == Instruction::UDiv ||
2720 Opc == Instruction::LShr ||
2721 Opc == Instruction::AShr) {
2722 if (Record[3] & (1 << bitc::PEO_EXACT))
2723 Flags |= SDivOperator::IsExact;
2726 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2730 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2731 if (Record.size() < 3)
2732 return error("Invalid record");
2733 int Opc = getDecodedCastOpcode(Record[0]);
2735 V = UndefValue::get(CurTy); // Unknown cast.
2737 Type *OpTy = getTypeByID(Record[1]);
2739 return error("Invalid record");
2740 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2741 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2742 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2746 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2747 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2749 Type *PointeeType = nullptr;
2750 if (Record.size() % 2)
2751 PointeeType = getTypeByID(Record[OpNum++]);
2752 SmallVector<Constant*, 16> Elts;
2753 while (OpNum != Record.size()) {
2754 Type *ElTy = getTypeByID(Record[OpNum++]);
2756 return error("Invalid record");
2757 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2762 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2764 return error("Explicit gep operator type does not match pointee type "
2765 "of pointer operand");
2767 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2768 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2770 bitc::CST_CODE_CE_INBOUNDS_GEP);
2773 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2774 if (Record.size() < 3)
2775 return error("Invalid record");
2777 Type *SelectorTy = Type::getInt1Ty(Context);
2779 // The selector might be an i1 or an <n x i1>
2780 // Get the type from the ValueList before getting a forward ref.
2781 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2782 if (Value *V = ValueList[Record[0]])
2783 if (SelectorTy != V->getType())
2784 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2786 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2788 ValueList.getConstantFwdRef(Record[1],CurTy),
2789 ValueList.getConstantFwdRef(Record[2],CurTy));
2792 case bitc::CST_CODE_CE_EXTRACTELT
2793 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2794 if (Record.size() < 3)
2795 return error("Invalid record");
2797 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2799 return error("Invalid record");
2800 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2801 Constant *Op1 = nullptr;
2802 if (Record.size() == 4) {
2803 Type *IdxTy = getTypeByID(Record[2]);
2805 return error("Invalid record");
2806 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2807 } else // TODO: Remove with llvm 4.0
2808 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2810 return error("Invalid record");
2811 V = ConstantExpr::getExtractElement(Op0, Op1);
2814 case bitc::CST_CODE_CE_INSERTELT
2815 : { // CE_INSERTELT: [opval, opval, opty, opval]
2816 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2817 if (Record.size() < 3 || !OpTy)
2818 return error("Invalid record");
2819 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2820 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2821 OpTy->getElementType());
2822 Constant *Op2 = nullptr;
2823 if (Record.size() == 4) {
2824 Type *IdxTy = getTypeByID(Record[2]);
2826 return error("Invalid record");
2827 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2828 } else // TODO: Remove with llvm 4.0
2829 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2831 return error("Invalid record");
2832 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2835 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2836 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2837 if (Record.size() < 3 || !OpTy)
2838 return error("Invalid record");
2839 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2840 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2841 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2842 OpTy->getNumElements());
2843 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2844 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2847 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2848 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2850 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2851 if (Record.size() < 4 || !RTy || !OpTy)
2852 return error("Invalid record");
2853 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2854 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2855 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2856 RTy->getNumElements());
2857 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2858 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2861 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2862 if (Record.size() < 4)
2863 return error("Invalid record");
2864 Type *OpTy = getTypeByID(Record[0]);
2866 return error("Invalid record");
2867 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2868 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2870 if (OpTy->isFPOrFPVectorTy())
2871 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2873 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2876 // This maintains backward compatibility, pre-asm dialect keywords.
2877 // FIXME: Remove with the 4.0 release.
2878 case bitc::CST_CODE_INLINEASM_OLD: {
2879 if (Record.size() < 2)
2880 return error("Invalid record");
2881 std::string AsmStr, ConstrStr;
2882 bool HasSideEffects = Record[0] & 1;
2883 bool IsAlignStack = Record[0] >> 1;
2884 unsigned AsmStrSize = Record[1];
2885 if (2+AsmStrSize >= Record.size())
2886 return error("Invalid record");
2887 unsigned ConstStrSize = Record[2+AsmStrSize];
2888 if (3+AsmStrSize+ConstStrSize > Record.size())
2889 return error("Invalid record");
2891 for (unsigned i = 0; i != AsmStrSize; ++i)
2892 AsmStr += (char)Record[2+i];
2893 for (unsigned i = 0; i != ConstStrSize; ++i)
2894 ConstrStr += (char)Record[3+AsmStrSize+i];
2895 PointerType *PTy = cast<PointerType>(CurTy);
2896 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2897 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2900 // This version adds support for the asm dialect keywords (e.g.,
2902 case bitc::CST_CODE_INLINEASM: {
2903 if (Record.size() < 2)
2904 return error("Invalid record");
2905 std::string AsmStr, ConstrStr;
2906 bool HasSideEffects = Record[0] & 1;
2907 bool IsAlignStack = (Record[0] >> 1) & 1;
2908 unsigned AsmDialect = Record[0] >> 2;
2909 unsigned AsmStrSize = Record[1];
2910 if (2+AsmStrSize >= Record.size())
2911 return error("Invalid record");
2912 unsigned ConstStrSize = Record[2+AsmStrSize];
2913 if (3+AsmStrSize+ConstStrSize > Record.size())
2914 return error("Invalid record");
2916 for (unsigned i = 0; i != AsmStrSize; ++i)
2917 AsmStr += (char)Record[2+i];
2918 for (unsigned i = 0; i != ConstStrSize; ++i)
2919 ConstrStr += (char)Record[3+AsmStrSize+i];
2920 PointerType *PTy = cast<PointerType>(CurTy);
2921 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2922 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2923 InlineAsm::AsmDialect(AsmDialect));
2926 case bitc::CST_CODE_BLOCKADDRESS:{
2927 if (Record.size() < 3)
2928 return error("Invalid record");
2929 Type *FnTy = getTypeByID(Record[0]);
2931 return error("Invalid record");
2933 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2935 return error("Invalid record");
2937 // Don't let Fn get dematerialized.
2938 BlockAddressesTaken.insert(Fn);
2940 // If the function is already parsed we can insert the block address right
2943 unsigned BBID = Record[2];
2945 // Invalid reference to entry block.
2946 return error("Invalid ID");
2948 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2949 for (size_t I = 0, E = BBID; I != E; ++I) {
2951 return error("Invalid ID");
2956 // Otherwise insert a placeholder and remember it so it can be inserted
2957 // when the function is parsed.
2958 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2960 BasicBlockFwdRefQueue.push_back(Fn);
2961 if (FwdBBs.size() < BBID + 1)
2962 FwdBBs.resize(BBID + 1);
2964 FwdBBs[BBID] = BasicBlock::Create(Context);
2967 V = BlockAddress::get(Fn, BB);
2972 ValueList.assignValue(V, NextCstNo);
2977 std::error_code BitcodeReader::parseUseLists() {
2978 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2979 return error("Invalid record");
2981 // Read all the records.
2982 SmallVector<uint64_t, 64> Record;
2984 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2986 switch (Entry.Kind) {
2987 case BitstreamEntry::SubBlock: // Handled for us already.
2988 case BitstreamEntry::Error:
2989 return error("Malformed block");
2990 case BitstreamEntry::EndBlock:
2991 return std::error_code();
2992 case BitstreamEntry::Record:
2993 // The interesting case.
2997 // Read a use list record.
3000 switch (Stream.readRecord(Entry.ID, Record)) {
3001 default: // Default behavior: unknown type.
3003 case bitc::USELIST_CODE_BB:
3006 case bitc::USELIST_CODE_DEFAULT: {
3007 unsigned RecordLength = Record.size();
3008 if (RecordLength < 3)
3009 // Records should have at least an ID and two indexes.
3010 return error("Invalid record");
3011 unsigned ID = Record.back();
3016 assert(ID < FunctionBBs.size() && "Basic block not found");
3017 V = FunctionBBs[ID];
3020 unsigned NumUses = 0;
3021 SmallDenseMap<const Use *, unsigned, 16> Order;
3022 for (const Use &U : V->uses()) {
3023 if (++NumUses > Record.size())
3025 Order[&U] = Record[NumUses - 1];
3027 if (Order.size() != Record.size() || NumUses > Record.size())
3028 // Mismatches can happen if the functions are being materialized lazily
3029 // (out-of-order), or a value has been upgraded.
3032 V->sortUseList([&](const Use &L, const Use &R) {
3033 return Order.lookup(&L) < Order.lookup(&R);
3041 /// When we see the block for metadata, remember where it is and then skip it.
3042 /// This lets us lazily deserialize the metadata.
3043 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3044 // Save the current stream state.
3045 uint64_t CurBit = Stream.GetCurrentBitNo();
3046 DeferredMetadataInfo.push_back(CurBit);
3048 // Skip over the block for now.
3049 if (Stream.SkipBlock())
3050 return error("Invalid record");
3051 return std::error_code();
3054 std::error_code BitcodeReader::materializeMetadata() {
3055 for (uint64_t BitPos : DeferredMetadataInfo) {
3056 // Move the bit stream to the saved position.
3057 Stream.JumpToBit(BitPos);
3058 if (std::error_code EC = parseMetadata(true))
3061 DeferredMetadataInfo.clear();
3062 return std::error_code();
3065 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3067 /// When we see the block for a function body, remember where it is and then
3068 /// skip it. This lets us lazily deserialize the functions.
3069 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3070 // Get the function we are talking about.
3071 if (FunctionsWithBodies.empty())
3072 return error("Insufficient function protos");
3074 Function *Fn = FunctionsWithBodies.back();
3075 FunctionsWithBodies.pop_back();
3077 // Save the current stream state.
3078 uint64_t CurBit = Stream.GetCurrentBitNo();
3080 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3081 "Mismatch between VST and scanned function offsets");
3082 DeferredFunctionInfo[Fn] = CurBit;
3084 // Skip over the function block for now.
3085 if (Stream.SkipBlock())
3086 return error("Invalid record");
3087 return std::error_code();
3090 std::error_code BitcodeReader::globalCleanup() {
3091 // Patch the initializers for globals and aliases up.
3092 resolveGlobalAndAliasInits();
3093 if (!GlobalInits.empty() || !AliasInits.empty())
3094 return error("Malformed global initializer set");
3096 // Look for intrinsic functions which need to be upgraded at some point
3097 for (Function &F : *TheModule) {
3099 if (UpgradeIntrinsicFunction(&F, NewFn))
3100 UpgradedIntrinsics[&F] = NewFn;
3103 // Look for global variables which need to be renamed.
3104 for (GlobalVariable &GV : TheModule->globals())
3105 UpgradeGlobalVariable(&GV);
3107 // Force deallocation of memory for these vectors to favor the client that
3108 // want lazy deserialization.
3109 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3110 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3111 return std::error_code();
3114 /// Support for lazy parsing of function bodies. This is required if we
3115 /// either have an old bitcode file without a VST forward declaration record,
3116 /// or if we have an anonymous function being materialized, since anonymous
3117 /// functions do not have a name and are therefore not in the VST.
3118 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3119 Stream.JumpToBit(NextUnreadBit);
3121 if (Stream.AtEndOfStream())
3122 return error("Could not find function in stream");
3124 if (!SeenFirstFunctionBody)
3125 return error("Trying to materialize functions before seeing function blocks");
3127 // An old bitcode file with the symbol table at the end would have
3128 // finished the parse greedily.
3129 assert(SeenValueSymbolTable);
3131 SmallVector<uint64_t, 64> Record;
3134 BitstreamEntry Entry = Stream.advance();
3135 switch (Entry.Kind) {
3137 return error("Expect SubBlock");
3138 case BitstreamEntry::SubBlock:
3141 return error("Expect function block");
3142 case bitc::FUNCTION_BLOCK_ID:
3143 if (std::error_code EC = rememberAndSkipFunctionBody())
3145 NextUnreadBit = Stream.GetCurrentBitNo();
3146 return std::error_code();
3152 std::error_code BitcodeReader::parseBitcodeVersion() {
3153 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3154 return error("Invalid record");
3156 // Read all the records.
3157 SmallVector<uint64_t, 64> Record;
3159 BitstreamEntry Entry = Stream.advance();
3161 switch (Entry.Kind) {
3163 case BitstreamEntry::Error:
3164 return error("Malformed block");
3165 case BitstreamEntry::EndBlock:
3166 return std::error_code();
3167 case BitstreamEntry::Record:
3168 // The interesting case.
3174 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3176 default: // Default behavior: reject
3177 return error("Invalid value");
3178 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3180 convertToString(Record, 0, ProducerIdentification);
3183 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3184 unsigned epoch = (unsigned)Record[0];
3185 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3187 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3188 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3195 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3196 bool ShouldLazyLoadMetadata) {
3198 Stream.JumpToBit(ResumeBit);
3199 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3200 return error("Invalid record");
3202 SmallVector<uint64_t, 64> Record;
3203 std::vector<std::string> SectionTable;
3204 std::vector<std::string> GCTable;
3206 // Read all the records for this module.
3208 BitstreamEntry Entry = Stream.advance();
3210 switch (Entry.Kind) {
3211 case BitstreamEntry::Error:
3212 return error("Malformed block");
3213 case BitstreamEntry::EndBlock:
3214 return globalCleanup();
3216 case BitstreamEntry::SubBlock:
3218 default: // Skip unknown content.
3219 if (Stream.SkipBlock())
3220 return error("Invalid record");
3222 case bitc::BLOCKINFO_BLOCK_ID:
3223 if (Stream.ReadBlockInfoBlock())
3224 return error("Malformed block");
3226 case bitc::PARAMATTR_BLOCK_ID:
3227 if (std::error_code EC = parseAttributeBlock())
3230 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3231 if (std::error_code EC = parseAttributeGroupBlock())
3234 case bitc::TYPE_BLOCK_ID_NEW:
3235 if (std::error_code EC = parseTypeTable())
3238 case bitc::VALUE_SYMTAB_BLOCK_ID:
3239 if (!SeenValueSymbolTable) {
3240 // Either this is an old form VST without function index and an
3241 // associated VST forward declaration record (which would have caused
3242 // the VST to be jumped to and parsed before it was encountered
3243 // normally in the stream), or there were no function blocks to
3244 // trigger an earlier parsing of the VST.
3245 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3246 if (std::error_code EC = parseValueSymbolTable())
3248 SeenValueSymbolTable = true;
3250 // We must have had a VST forward declaration record, which caused
3251 // the parser to jump to and parse the VST earlier.
3252 assert(VSTOffset > 0);
3253 if (Stream.SkipBlock())
3254 return error("Invalid record");
3257 case bitc::CONSTANTS_BLOCK_ID:
3258 if (std::error_code EC = parseConstants())
3260 if (std::error_code EC = resolveGlobalAndAliasInits())
3263 case bitc::METADATA_BLOCK_ID:
3264 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3265 if (std::error_code EC = rememberAndSkipMetadata())
3269 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3270 if (std::error_code EC = parseMetadata(true))
3273 case bitc::METADATA_KIND_BLOCK_ID:
3274 if (std::error_code EC = parseMetadataKinds())
3277 case bitc::FUNCTION_BLOCK_ID:
3278 // If this is the first function body we've seen, reverse the
3279 // FunctionsWithBodies list.
3280 if (!SeenFirstFunctionBody) {
3281 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3282 if (std::error_code EC = globalCleanup())
3284 SeenFirstFunctionBody = true;
3287 if (VSTOffset > 0) {
3288 // If we have a VST forward declaration record, make sure we
3289 // parse the VST now if we haven't already. It is needed to
3290 // set up the DeferredFunctionInfo vector for lazy reading.
3291 if (!SeenValueSymbolTable) {
3292 if (std::error_code EC =
3293 BitcodeReader::parseValueSymbolTable(VSTOffset))
3295 SeenValueSymbolTable = true;
3296 // Fall through so that we record the NextUnreadBit below.
3297 // This is necessary in case we have an anonymous function that
3298 // is later materialized. Since it will not have a VST entry we
3299 // need to fall back to the lazy parse to find its offset.
3301 // If we have a VST forward declaration record, but have already
3302 // parsed the VST (just above, when the first function body was
3303 // encountered here), then we are resuming the parse after
3304 // materializing functions. The ResumeBit points to the
3305 // start of the last function block recorded in the
3306 // DeferredFunctionInfo map. Skip it.
3307 if (Stream.SkipBlock())
3308 return error("Invalid record");
3313 // Support older bitcode files that did not have the function
3314 // index in the VST, nor a VST forward declaration record, as
3315 // well as anonymous functions that do not have VST entries.
3316 // Build the DeferredFunctionInfo vector on the fly.
3317 if (std::error_code EC = rememberAndSkipFunctionBody())
3320 // Suspend parsing when we reach the function bodies. Subsequent
3321 // materialization calls will resume it when necessary. If the bitcode
3322 // file is old, the symbol table will be at the end instead and will not
3323 // have been seen yet. In this case, just finish the parse now.
3324 if (SeenValueSymbolTable) {
3325 NextUnreadBit = Stream.GetCurrentBitNo();
3326 return std::error_code();
3329 case bitc::USELIST_BLOCK_ID:
3330 if (std::error_code EC = parseUseLists())
3333 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3334 if (std::error_code EC = parseOperandBundleTags())
3340 case BitstreamEntry::Record:
3341 // The interesting case.
3347 auto BitCode = Stream.readRecord(Entry.ID, Record);
3349 default: break; // Default behavior, ignore unknown content.
3350 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3351 if (Record.size() < 1)
3352 return error("Invalid record");
3353 // Only version #0 and #1 are supported so far.
3354 unsigned module_version = Record[0];
3355 switch (module_version) {
3357 return error("Invalid value");
3359 UseRelativeIDs = false;
3362 UseRelativeIDs = true;
3367 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3369 if (convertToString(Record, 0, S))
3370 return error("Invalid record");
3371 TheModule->setTargetTriple(S);
3374 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3376 if (convertToString(Record, 0, S))
3377 return error("Invalid record");
3378 TheModule->setDataLayout(S);
3381 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3383 if (convertToString(Record, 0, S))
3384 return error("Invalid record");
3385 TheModule->setModuleInlineAsm(S);
3388 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3389 // FIXME: Remove in 4.0.
3391 if (convertToString(Record, 0, S))
3392 return error("Invalid record");
3396 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3398 if (convertToString(Record, 0, S))
3399 return error("Invalid record");
3400 SectionTable.push_back(S);
3403 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3405 if (convertToString(Record, 0, S))
3406 return error("Invalid record");
3407 GCTable.push_back(S);
3410 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3411 if (Record.size() < 2)
3412 return error("Invalid record");
3413 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3414 unsigned ComdatNameSize = Record[1];
3415 std::string ComdatName;
3416 ComdatName.reserve(ComdatNameSize);
3417 for (unsigned i = 0; i != ComdatNameSize; ++i)
3418 ComdatName += (char)Record[2 + i];
3419 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3420 C->setSelectionKind(SK);
3421 ComdatList.push_back(C);
3424 // GLOBALVAR: [pointer type, isconst, initid,
3425 // linkage, alignment, section, visibility, threadlocal,
3426 // unnamed_addr, externally_initialized, dllstorageclass,
3428 case bitc::MODULE_CODE_GLOBALVAR: {
3429 if (Record.size() < 6)
3430 return error("Invalid record");
3431 Type *Ty = getTypeByID(Record[0]);
3433 return error("Invalid record");
3434 bool isConstant = Record[1] & 1;
3435 bool explicitType = Record[1] & 2;
3436 unsigned AddressSpace;
3438 AddressSpace = Record[1] >> 2;
3440 if (!Ty->isPointerTy())
3441 return error("Invalid type for value");
3442 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3443 Ty = cast<PointerType>(Ty)->getElementType();
3446 uint64_t RawLinkage = Record[3];
3447 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3449 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3451 std::string Section;
3453 if (Record[5]-1 >= SectionTable.size())
3454 return error("Invalid ID");
3455 Section = SectionTable[Record[5]-1];
3457 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3458 // Local linkage must have default visibility.
3459 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3460 // FIXME: Change to an error if non-default in 4.0.
3461 Visibility = getDecodedVisibility(Record[6]);
3463 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3464 if (Record.size() > 7)
3465 TLM = getDecodedThreadLocalMode(Record[7]);
3467 bool UnnamedAddr = false;
3468 if (Record.size() > 8)
3469 UnnamedAddr = Record[8];
3471 bool ExternallyInitialized = false;
3472 if (Record.size() > 9)
3473 ExternallyInitialized = Record[9];
3475 GlobalVariable *NewGV =
3476 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3477 TLM, AddressSpace, ExternallyInitialized);
3478 NewGV->setAlignment(Alignment);
3479 if (!Section.empty())
3480 NewGV->setSection(Section);
3481 NewGV->setVisibility(Visibility);
3482 NewGV->setUnnamedAddr(UnnamedAddr);
3484 if (Record.size() > 10)
3485 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3487 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3489 ValueList.push_back(NewGV);
3491 // Remember which value to use for the global initializer.
3492 if (unsigned InitID = Record[2])
3493 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3495 if (Record.size() > 11) {
3496 if (unsigned ComdatID = Record[11]) {
3497 if (ComdatID > ComdatList.size())
3498 return error("Invalid global variable comdat ID");
3499 NewGV->setComdat(ComdatList[ComdatID - 1]);
3501 } else if (hasImplicitComdat(RawLinkage)) {
3502 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3506 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3507 // alignment, section, visibility, gc, unnamed_addr,
3508 // prologuedata, dllstorageclass, comdat, prefixdata]
3509 case bitc::MODULE_CODE_FUNCTION: {
3510 if (Record.size() < 8)
3511 return error("Invalid record");
3512 Type *Ty = getTypeByID(Record[0]);
3514 return error("Invalid record");
3515 if (auto *PTy = dyn_cast<PointerType>(Ty))
3516 Ty = PTy->getElementType();
3517 auto *FTy = dyn_cast<FunctionType>(Ty);
3519 return error("Invalid type for value");
3520 auto CC = static_cast<CallingConv::ID>(Record[1]);
3521 if (CC & ~CallingConv::MaxID)
3522 return error("Invalid calling convention ID");
3524 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3527 Func->setCallingConv(CC);
3528 bool isProto = Record[2];
3529 uint64_t RawLinkage = Record[3];
3530 Func->setLinkage(getDecodedLinkage(RawLinkage));
3531 Func->setAttributes(getAttributes(Record[4]));
3534 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3536 Func->setAlignment(Alignment);
3538 if (Record[6]-1 >= SectionTable.size())
3539 return error("Invalid ID");
3540 Func->setSection(SectionTable[Record[6]-1]);
3542 // Local linkage must have default visibility.
3543 if (!Func->hasLocalLinkage())
3544 // FIXME: Change to an error if non-default in 4.0.
3545 Func->setVisibility(getDecodedVisibility(Record[7]));
3546 if (Record.size() > 8 && Record[8]) {
3547 if (Record[8]-1 >= GCTable.size())
3548 return error("Invalid ID");
3549 Func->setGC(GCTable[Record[8]-1].c_str());
3551 bool UnnamedAddr = false;
3552 if (Record.size() > 9)
3553 UnnamedAddr = Record[9];
3554 Func->setUnnamedAddr(UnnamedAddr);
3555 if (Record.size() > 10 && Record[10] != 0)
3556 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3558 if (Record.size() > 11)
3559 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3561 upgradeDLLImportExportLinkage(Func, RawLinkage);
3563 if (Record.size() > 12) {
3564 if (unsigned ComdatID = Record[12]) {
3565 if (ComdatID > ComdatList.size())
3566 return error("Invalid function comdat ID");
3567 Func->setComdat(ComdatList[ComdatID - 1]);
3569 } else if (hasImplicitComdat(RawLinkage)) {
3570 Func->setComdat(reinterpret_cast<Comdat *>(1));
3573 if (Record.size() > 13 && Record[13] != 0)
3574 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3576 if (Record.size() > 14 && Record[14] != 0)
3577 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3579 ValueList.push_back(Func);
3581 // If this is a function with a body, remember the prototype we are
3582 // creating now, so that we can match up the body with them later.
3584 Func->setIsMaterializable(true);
3585 FunctionsWithBodies.push_back(Func);
3586 DeferredFunctionInfo[Func] = 0;
3590 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3591 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3592 case bitc::MODULE_CODE_ALIAS:
3593 case bitc::MODULE_CODE_ALIAS_OLD: {
3594 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3595 if (Record.size() < (3 + (unsigned)NewRecord))
3596 return error("Invalid record");
3598 Type *Ty = getTypeByID(Record[OpNum++]);
3600 return error("Invalid record");
3604 auto *PTy = dyn_cast<PointerType>(Ty);
3606 return error("Invalid type for value");
3607 Ty = PTy->getElementType();
3608 AddrSpace = PTy->getAddressSpace();
3610 AddrSpace = Record[OpNum++];
3613 auto Val = Record[OpNum++];
3614 auto Linkage = Record[OpNum++];
3615 auto *NewGA = GlobalAlias::create(
3616 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3617 // Old bitcode files didn't have visibility field.
3618 // Local linkage must have default visibility.
3619 if (OpNum != Record.size()) {
3620 auto VisInd = OpNum++;
3621 if (!NewGA->hasLocalLinkage())
3622 // FIXME: Change to an error if non-default in 4.0.
3623 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3625 if (OpNum != Record.size())
3626 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3628 upgradeDLLImportExportLinkage(NewGA, Linkage);
3629 if (OpNum != Record.size())
3630 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3631 if (OpNum != Record.size())
3632 NewGA->setUnnamedAddr(Record[OpNum++]);
3633 ValueList.push_back(NewGA);
3634 AliasInits.push_back(std::make_pair(NewGA, Val));
3637 /// MODULE_CODE_PURGEVALS: [numvals]
3638 case bitc::MODULE_CODE_PURGEVALS:
3639 // Trim down the value list to the specified size.
3640 if (Record.size() < 1 || Record[0] > ValueList.size())
3641 return error("Invalid record");
3642 ValueList.shrinkTo(Record[0]);
3644 /// MODULE_CODE_VSTOFFSET: [offset]
3645 case bitc::MODULE_CODE_VSTOFFSET:
3646 if (Record.size() < 1)
3647 return error("Invalid record");
3648 VSTOffset = Record[0];
3650 /// MODULE_CODE_METADATA_VALUES: [numvals]
3651 case bitc::MODULE_CODE_METADATA_VALUES:
3652 if (Record.size() < 1)
3653 return error("Invalid record");
3654 assert(!IsMetadataMaterialized);
3655 // This record contains the number of metadata values in the module-level
3656 // METADATA_BLOCK. It is used to support lazy parsing of metadata as
3657 // a postpass, where we will parse function-level metadata first.
3658 // This is needed because the ids of metadata are assigned implicitly
3659 // based on their ordering in the bitcode, with the function-level
3660 // metadata ids starting after the module-level metadata ids. Otherwise,
3661 // we would have to parse the module-level metadata block to prime the
3662 // MDValueList when we are lazy loading metadata during function
3663 // importing. Initialize the MDValueList size here based on the
3664 // record value, regardless of whether we are doing lazy metadata
3665 // loading, so that we have consistent handling and assertion
3666 // checking in parseMetadata for module-level metadata.
3667 NumModuleMDs = Record[0];
3668 SeenModuleValuesRecord = true;
3669 assert(MDValueList.size() == 0);
3670 MDValueList.resize(NumModuleMDs);
3677 /// Helper to read the header common to all bitcode files.
3678 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3679 // Sniff for the signature.
3680 if (Stream.Read(8) != 'B' ||
3681 Stream.Read(8) != 'C' ||
3682 Stream.Read(4) != 0x0 ||
3683 Stream.Read(4) != 0xC ||
3684 Stream.Read(4) != 0xE ||
3685 Stream.Read(4) != 0xD)
3691 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3692 Module *M, bool ShouldLazyLoadMetadata) {
3695 if (std::error_code EC = initStream(std::move(Streamer)))
3698 // Sniff for the signature.
3699 if (!hasValidBitcodeHeader(Stream))
3700 return error("Invalid bitcode signature");
3702 // We expect a number of well-defined blocks, though we don't necessarily
3703 // need to understand them all.
3705 if (Stream.AtEndOfStream()) {
3706 // We didn't really read a proper Module.
3707 return error("Malformed IR file");
3710 BitstreamEntry Entry =
3711 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3713 if (Entry.Kind != BitstreamEntry::SubBlock)
3714 return error("Malformed block");
3716 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3717 parseBitcodeVersion();
3721 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3722 return parseModule(0, ShouldLazyLoadMetadata);
3724 if (Stream.SkipBlock())
3725 return error("Invalid record");
3729 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3730 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3731 return error("Invalid record");
3733 SmallVector<uint64_t, 64> Record;
3736 // Read all the records for this module.
3738 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3740 switch (Entry.Kind) {
3741 case BitstreamEntry::SubBlock: // Handled for us already.
3742 case BitstreamEntry::Error:
3743 return error("Malformed block");
3744 case BitstreamEntry::EndBlock:
3746 case BitstreamEntry::Record:
3747 // The interesting case.
3752 switch (Stream.readRecord(Entry.ID, Record)) {
3753 default: break; // Default behavior, ignore unknown content.
3754 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3756 if (convertToString(Record, 0, S))
3757 return error("Invalid record");
3764 llvm_unreachable("Exit infinite loop");
3767 ErrorOr<std::string> BitcodeReader::parseTriple() {
3768 if (std::error_code EC = initStream(nullptr))
3771 // Sniff for the signature.
3772 if (!hasValidBitcodeHeader(Stream))
3773 return error("Invalid bitcode signature");
3775 // We expect a number of well-defined blocks, though we don't necessarily
3776 // need to understand them all.
3778 BitstreamEntry Entry = Stream.advance();
3780 switch (Entry.Kind) {
3781 case BitstreamEntry::Error:
3782 return error("Malformed block");
3783 case BitstreamEntry::EndBlock:
3784 return std::error_code();
3786 case BitstreamEntry::SubBlock:
3787 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3788 return parseModuleTriple();
3790 // Ignore other sub-blocks.
3791 if (Stream.SkipBlock())
3792 return error("Malformed block");
3795 case BitstreamEntry::Record:
3796 Stream.skipRecord(Entry.ID);
3802 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3803 if (std::error_code EC = initStream(nullptr))
3806 // Sniff for the signature.
3807 if (!hasValidBitcodeHeader(Stream))
3808 return error("Invalid bitcode signature");
3810 // We expect a number of well-defined blocks, though we don't necessarily
3811 // need to understand them all.
3813 BitstreamEntry Entry = Stream.advance();
3814 switch (Entry.Kind) {
3815 case BitstreamEntry::Error:
3816 return error("Malformed block");
3817 case BitstreamEntry::EndBlock:
3818 return std::error_code();
3820 case BitstreamEntry::SubBlock:
3821 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3822 if (std::error_code EC = parseBitcodeVersion())
3824 return ProducerIdentification;
3826 // Ignore other sub-blocks.
3827 if (Stream.SkipBlock())
3828 return error("Malformed block");
3830 case BitstreamEntry::Record:
3831 Stream.skipRecord(Entry.ID);
3837 /// Parse metadata attachments.
3838 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3839 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3840 return error("Invalid record");
3842 SmallVector<uint64_t, 64> Record;
3844 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3846 switch (Entry.Kind) {
3847 case BitstreamEntry::SubBlock: // Handled for us already.
3848 case BitstreamEntry::Error:
3849 return error("Malformed block");
3850 case BitstreamEntry::EndBlock:
3851 return std::error_code();
3852 case BitstreamEntry::Record:
3853 // The interesting case.
3857 // Read a metadata attachment record.
3859 switch (Stream.readRecord(Entry.ID, Record)) {
3860 default: // Default behavior: ignore.
3862 case bitc::METADATA_ATTACHMENT: {
3863 unsigned RecordLength = Record.size();
3865 return error("Invalid record");
3866 if (RecordLength % 2 == 0) {
3867 // A function attachment.
3868 for (unsigned I = 0; I != RecordLength; I += 2) {
3869 auto K = MDKindMap.find(Record[I]);
3870 if (K == MDKindMap.end())
3871 return error("Invalid ID");
3872 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3873 F.setMetadata(K->second, cast<MDNode>(MD));
3878 // An instruction attachment.
3879 Instruction *Inst = InstructionList[Record[0]];
3880 for (unsigned i = 1; i != RecordLength; i = i+2) {
3881 unsigned Kind = Record[i];
3882 DenseMap<unsigned, unsigned>::iterator I =
3883 MDKindMap.find(Kind);
3884 if (I == MDKindMap.end())
3885 return error("Invalid ID");
3886 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3887 if (isa<LocalAsMetadata>(Node))
3888 // Drop the attachment. This used to be legal, but there's no
3891 Inst->setMetadata(I->second, cast<MDNode>(Node));
3892 if (I->second == LLVMContext::MD_tbaa)
3893 InstsWithTBAATag.push_back(Inst);
3901 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3902 Type *ValType, Type *PtrType) {
3903 if (!isa<PointerType>(PtrType))
3904 return error(DH, "Load/Store operand is not a pointer type");
3905 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3907 if (ValType && ValType != ElemType)
3908 return error(DH, "Explicit load/store type does not match pointee type of "
3910 if (!PointerType::isLoadableOrStorableType(ElemType))
3911 return error(DH, "Cannot load/store from pointer");
3912 return std::error_code();
3915 /// Lazily parse the specified function body block.
3916 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3917 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3918 return error("Invalid record");
3920 InstructionList.clear();
3921 unsigned ModuleValueListSize = ValueList.size();
3922 unsigned ModuleMDValueListSize = MDValueList.size();
3924 // Add all the function arguments to the value table.
3925 for (Argument &I : F->args())
3926 ValueList.push_back(&I);
3928 unsigned NextValueNo = ValueList.size();
3929 BasicBlock *CurBB = nullptr;
3930 unsigned CurBBNo = 0;
3933 auto getLastInstruction = [&]() -> Instruction * {
3934 if (CurBB && !CurBB->empty())
3935 return &CurBB->back();
3936 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3937 !FunctionBBs[CurBBNo - 1]->empty())
3938 return &FunctionBBs[CurBBNo - 1]->back();
3942 std::vector<OperandBundleDef> OperandBundles;
3944 // Read all the records.
3945 SmallVector<uint64_t, 64> Record;
3947 BitstreamEntry Entry = Stream.advance();
3949 switch (Entry.Kind) {
3950 case BitstreamEntry::Error:
3951 return error("Malformed block");
3952 case BitstreamEntry::EndBlock:
3953 goto OutOfRecordLoop;
3955 case BitstreamEntry::SubBlock:
3957 default: // Skip unknown content.
3958 if (Stream.SkipBlock())
3959 return error("Invalid record");
3961 case bitc::CONSTANTS_BLOCK_ID:
3962 if (std::error_code EC = parseConstants())
3964 NextValueNo = ValueList.size();
3966 case bitc::VALUE_SYMTAB_BLOCK_ID:
3967 if (std::error_code EC = parseValueSymbolTable())
3970 case bitc::METADATA_ATTACHMENT_ID:
3971 if (std::error_code EC = parseMetadataAttachment(*F))
3974 case bitc::METADATA_BLOCK_ID:
3975 if (std::error_code EC = parseMetadata())
3978 case bitc::USELIST_BLOCK_ID:
3979 if (std::error_code EC = parseUseLists())
3985 case BitstreamEntry::Record:
3986 // The interesting case.
3992 Instruction *I = nullptr;
3993 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3995 default: // Default behavior: reject
3996 return error("Invalid value");
3997 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3998 if (Record.size() < 1 || Record[0] == 0)
3999 return error("Invalid record");
4000 // Create all the basic blocks for the function.
4001 FunctionBBs.resize(Record[0]);
4003 // See if anything took the address of blocks in this function.
4004 auto BBFRI = BasicBlockFwdRefs.find(F);
4005 if (BBFRI == BasicBlockFwdRefs.end()) {
4006 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4007 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4009 auto &BBRefs = BBFRI->second;
4010 // Check for invalid basic block references.
4011 if (BBRefs.size() > FunctionBBs.size())
4012 return error("Invalid ID");
4013 assert(!BBRefs.empty() && "Unexpected empty array");
4014 assert(!BBRefs.front() && "Invalid reference to entry block");
4015 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4017 if (I < RE && BBRefs[I]) {
4018 BBRefs[I]->insertInto(F);
4019 FunctionBBs[I] = BBRefs[I];
4021 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4024 // Erase from the table.
4025 BasicBlockFwdRefs.erase(BBFRI);
4028 CurBB = FunctionBBs[0];
4032 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4033 // This record indicates that the last instruction is at the same
4034 // location as the previous instruction with a location.
4035 I = getLastInstruction();
4038 return error("Invalid record");
4039 I->setDebugLoc(LastLoc);
4043 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4044 I = getLastInstruction();
4045 if (!I || Record.size() < 4)
4046 return error("Invalid record");
4048 unsigned Line = Record[0], Col = Record[1];
4049 unsigned ScopeID = Record[2], IAID = Record[3];
4051 MDNode *Scope = nullptr, *IA = nullptr;
4052 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
4053 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
4054 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4055 I->setDebugLoc(LastLoc);
4060 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4063 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4064 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4065 OpNum+1 > Record.size())
4066 return error("Invalid record");
4068 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4070 return error("Invalid record");
4071 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4072 InstructionList.push_back(I);
4073 if (OpNum < Record.size()) {
4074 if (Opc == Instruction::Add ||
4075 Opc == Instruction::Sub ||
4076 Opc == Instruction::Mul ||
4077 Opc == Instruction::Shl) {
4078 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4079 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4080 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4081 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4082 } else if (Opc == Instruction::SDiv ||
4083 Opc == Instruction::UDiv ||
4084 Opc == Instruction::LShr ||
4085 Opc == Instruction::AShr) {
4086 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4087 cast<BinaryOperator>(I)->setIsExact(true);
4088 } else if (isa<FPMathOperator>(I)) {
4089 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4091 I->setFastMathFlags(FMF);
4097 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4100 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4101 OpNum+2 != Record.size())
4102 return error("Invalid record");
4104 Type *ResTy = getTypeByID(Record[OpNum]);
4105 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4106 if (Opc == -1 || !ResTy)
4107 return error("Invalid record");
4108 Instruction *Temp = nullptr;
4109 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4111 InstructionList.push_back(Temp);
4112 CurBB->getInstList().push_back(Temp);
4115 auto CastOp = (Instruction::CastOps)Opc;
4116 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4117 return error("Invalid cast");
4118 I = CastInst::Create(CastOp, Op, ResTy);
4120 InstructionList.push_back(I);
4123 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4124 case bitc::FUNC_CODE_INST_GEP_OLD:
4125 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4131 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4132 InBounds = Record[OpNum++];
4133 Ty = getTypeByID(Record[OpNum++]);
4135 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4140 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4141 return error("Invalid record");
4144 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4147 cast<SequentialType>(BasePtr->getType()->getScalarType())
4150 "Explicit gep type does not match pointee type of pointer operand");
4152 SmallVector<Value*, 16> GEPIdx;
4153 while (OpNum != Record.size()) {
4155 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4156 return error("Invalid record");
4157 GEPIdx.push_back(Op);
4160 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4162 InstructionList.push_back(I);
4164 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4168 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4169 // EXTRACTVAL: [opty, opval, n x indices]
4172 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4173 return error("Invalid record");
4175 unsigned RecSize = Record.size();
4176 if (OpNum == RecSize)
4177 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4179 SmallVector<unsigned, 4> EXTRACTVALIdx;
4180 Type *CurTy = Agg->getType();
4181 for (; OpNum != RecSize; ++OpNum) {
4182 bool IsArray = CurTy->isArrayTy();
4183 bool IsStruct = CurTy->isStructTy();
4184 uint64_t Index = Record[OpNum];
4186 if (!IsStruct && !IsArray)
4187 return error("EXTRACTVAL: Invalid type");
4188 if ((unsigned)Index != Index)
4189 return error("Invalid value");
4190 if (IsStruct && Index >= CurTy->subtypes().size())
4191 return error("EXTRACTVAL: Invalid struct index");
4192 if (IsArray && Index >= CurTy->getArrayNumElements())
4193 return error("EXTRACTVAL: Invalid array index");
4194 EXTRACTVALIdx.push_back((unsigned)Index);
4197 CurTy = CurTy->subtypes()[Index];
4199 CurTy = CurTy->subtypes()[0];
4202 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4203 InstructionList.push_back(I);
4207 case bitc::FUNC_CODE_INST_INSERTVAL: {
4208 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4211 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4212 return error("Invalid record");
4214 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4215 return error("Invalid record");
4217 unsigned RecSize = Record.size();
4218 if (OpNum == RecSize)
4219 return error("INSERTVAL: Invalid instruction with 0 indices");
4221 SmallVector<unsigned, 4> INSERTVALIdx;
4222 Type *CurTy = Agg->getType();
4223 for (; OpNum != RecSize; ++OpNum) {
4224 bool IsArray = CurTy->isArrayTy();
4225 bool IsStruct = CurTy->isStructTy();
4226 uint64_t Index = Record[OpNum];
4228 if (!IsStruct && !IsArray)
4229 return error("INSERTVAL: Invalid type");
4230 if ((unsigned)Index != Index)
4231 return error("Invalid value");
4232 if (IsStruct && Index >= CurTy->subtypes().size())
4233 return error("INSERTVAL: Invalid struct index");
4234 if (IsArray && Index >= CurTy->getArrayNumElements())
4235 return error("INSERTVAL: Invalid array index");
4237 INSERTVALIdx.push_back((unsigned)Index);
4239 CurTy = CurTy->subtypes()[Index];
4241 CurTy = CurTy->subtypes()[0];
4244 if (CurTy != Val->getType())
4245 return error("Inserted value type doesn't match aggregate type");
4247 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4248 InstructionList.push_back(I);
4252 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4253 // obsolete form of select
4254 // handles select i1 ... in old bitcode
4256 Value *TrueVal, *FalseVal, *Cond;
4257 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4258 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4259 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4260 return error("Invalid record");
4262 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4263 InstructionList.push_back(I);
4267 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4268 // new form of select
4269 // handles select i1 or select [N x i1]
4271 Value *TrueVal, *FalseVal, *Cond;
4272 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4273 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4274 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4275 return error("Invalid record");
4277 // select condition can be either i1 or [N x i1]
4278 if (VectorType* vector_type =
4279 dyn_cast<VectorType>(Cond->getType())) {
4281 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4282 return error("Invalid type for value");
4285 if (Cond->getType() != Type::getInt1Ty(Context))
4286 return error("Invalid type for value");
4289 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4290 InstructionList.push_back(I);
4294 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4297 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4298 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4299 return error("Invalid record");
4300 if (!Vec->getType()->isVectorTy())
4301 return error("Invalid type for value");
4302 I = ExtractElementInst::Create(Vec, Idx);
4303 InstructionList.push_back(I);
4307 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4309 Value *Vec, *Elt, *Idx;
4310 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4311 return error("Invalid record");
4312 if (!Vec->getType()->isVectorTy())
4313 return error("Invalid type for value");
4314 if (popValue(Record, OpNum, NextValueNo,
4315 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4316 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4317 return error("Invalid record");
4318 I = InsertElementInst::Create(Vec, Elt, Idx);
4319 InstructionList.push_back(I);
4323 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4325 Value *Vec1, *Vec2, *Mask;
4326 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4327 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4328 return error("Invalid record");
4330 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4331 return error("Invalid record");
4332 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4333 return error("Invalid type for value");
4334 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4335 InstructionList.push_back(I);
4339 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4340 // Old form of ICmp/FCmp returning bool
4341 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4342 // both legal on vectors but had different behaviour.
4343 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4344 // FCmp/ICmp returning bool or vector of bool
4348 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4349 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4350 return error("Invalid record");
4352 unsigned PredVal = Record[OpNum];
4353 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4355 if (IsFP && Record.size() > OpNum+1)
4356 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4358 if (OpNum+1 != Record.size())
4359 return error("Invalid record");
4361 if (LHS->getType()->isFPOrFPVectorTy())
4362 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4364 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4367 I->setFastMathFlags(FMF);
4368 InstructionList.push_back(I);
4372 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4374 unsigned Size = Record.size();
4376 I = ReturnInst::Create(Context);
4377 InstructionList.push_back(I);
4382 Value *Op = nullptr;
4383 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4384 return error("Invalid record");
4385 if (OpNum != Record.size())
4386 return error("Invalid record");
4388 I = ReturnInst::Create(Context, Op);
4389 InstructionList.push_back(I);
4392 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4393 if (Record.size() != 1 && Record.size() != 3)
4394 return error("Invalid record");
4395 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4397 return error("Invalid record");
4399 if (Record.size() == 1) {
4400 I = BranchInst::Create(TrueDest);
4401 InstructionList.push_back(I);
4404 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4405 Value *Cond = getValue(Record, 2, NextValueNo,
4406 Type::getInt1Ty(Context));
4407 if (!FalseDest || !Cond)
4408 return error("Invalid record");
4409 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4410 InstructionList.push_back(I);
4414 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4415 if (Record.size() != 1 && Record.size() != 2)
4416 return error("Invalid record");
4419 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4421 return error("Invalid record");
4422 BasicBlock *UnwindDest = nullptr;
4423 if (Record.size() == 2) {
4424 UnwindDest = getBasicBlock(Record[Idx++]);
4426 return error("Invalid record");
4429 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4430 InstructionList.push_back(I);
4433 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4434 if (Record.size() != 2)
4435 return error("Invalid record");
4438 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4440 return error("Invalid record");
4441 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4443 return error("Invalid record");
4445 I = CatchReturnInst::Create(CatchPad, BB);
4446 InstructionList.push_back(I);
4449 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4450 // We must have, at minimum, the outer scope and the number of arguments.
4451 if (Record.size() < 2)
4452 return error("Invalid record");
4457 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4459 unsigned NumHandlers = Record[Idx++];
4461 SmallVector<BasicBlock *, 2> Handlers;
4462 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4463 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4465 return error("Invalid record");
4466 Handlers.push_back(BB);
4469 BasicBlock *UnwindDest = nullptr;
4470 if (Idx + 1 == Record.size()) {
4471 UnwindDest = getBasicBlock(Record[Idx++]);
4473 return error("Invalid record");
4476 if (Record.size() != Idx)
4477 return error("Invalid record");
4480 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4481 for (BasicBlock *Handler : Handlers)
4482 CatchSwitch->addHandler(Handler);
4484 InstructionList.push_back(I);
4487 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [tok,bb#,num,(ty,val)*]
4488 // We must have, at minimum, the outer scope and the number of arguments.
4489 if (Record.size() < 2)
4490 return error("Invalid record");
4495 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4497 unsigned NumArgOperands = Record[Idx++];
4499 SmallVector<Value *, 2> Args;
4500 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4502 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4503 return error("Invalid record");
4504 Args.push_back(Val);
4507 BasicBlock *UnwindDest = nullptr;
4508 if (Idx + 1 == Record.size()) {
4509 UnwindDest = getBasicBlock(Record[Idx++]);
4511 return error("Invalid record");
4514 if (Record.size() != Idx)
4515 return error("Invalid record");
4517 I = TerminatePadInst::Create(ParentPad, UnwindDest, Args);
4518 InstructionList.push_back(I);
4521 case bitc::FUNC_CODE_INST_CATCHPAD:
4522 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4523 // We must have, at minimum, the outer scope and the number of arguments.
4524 if (Record.size() < 2)
4525 return error("Invalid record");
4530 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4532 unsigned NumArgOperands = Record[Idx++];
4534 SmallVector<Value *, 2> Args;
4535 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4537 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4538 return error("Invalid record");
4539 Args.push_back(Val);
4542 if (Record.size() != Idx)
4543 return error("Invalid record");
4545 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4546 I = CleanupPadInst::Create(ParentPad, Args);
4548 I = CatchPadInst::Create(ParentPad, Args);
4549 InstructionList.push_back(I);
4552 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4554 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4555 // "New" SwitchInst format with case ranges. The changes to write this
4556 // format were reverted but we still recognize bitcode that uses it.
4557 // Hopefully someday we will have support for case ranges and can use
4558 // this format again.
4560 Type *OpTy = getTypeByID(Record[1]);
4561 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4563 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4564 BasicBlock *Default = getBasicBlock(Record[3]);
4565 if (!OpTy || !Cond || !Default)
4566 return error("Invalid record");
4568 unsigned NumCases = Record[4];
4570 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4571 InstructionList.push_back(SI);
4573 unsigned CurIdx = 5;
4574 for (unsigned i = 0; i != NumCases; ++i) {
4575 SmallVector<ConstantInt*, 1> CaseVals;
4576 unsigned NumItems = Record[CurIdx++];
4577 for (unsigned ci = 0; ci != NumItems; ++ci) {
4578 bool isSingleNumber = Record[CurIdx++];
4581 unsigned ActiveWords = 1;
4582 if (ValueBitWidth > 64)
4583 ActiveWords = Record[CurIdx++];
4584 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4586 CurIdx += ActiveWords;
4588 if (!isSingleNumber) {
4590 if (ValueBitWidth > 64)
4591 ActiveWords = Record[CurIdx++];
4592 APInt High = readWideAPInt(
4593 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4594 CurIdx += ActiveWords;
4596 // FIXME: It is not clear whether values in the range should be
4597 // compared as signed or unsigned values. The partially
4598 // implemented changes that used this format in the past used
4599 // unsigned comparisons.
4600 for ( ; Low.ule(High); ++Low)
4601 CaseVals.push_back(ConstantInt::get(Context, Low));
4603 CaseVals.push_back(ConstantInt::get(Context, Low));
4605 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4606 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4607 cve = CaseVals.end(); cvi != cve; ++cvi)
4608 SI->addCase(*cvi, DestBB);
4614 // Old SwitchInst format without case ranges.
4616 if (Record.size() < 3 || (Record.size() & 1) == 0)
4617 return error("Invalid record");
4618 Type *OpTy = getTypeByID(Record[0]);
4619 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4620 BasicBlock *Default = getBasicBlock(Record[2]);
4621 if (!OpTy || !Cond || !Default)
4622 return error("Invalid record");
4623 unsigned NumCases = (Record.size()-3)/2;
4624 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4625 InstructionList.push_back(SI);
4626 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4627 ConstantInt *CaseVal =
4628 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4629 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4630 if (!CaseVal || !DestBB) {
4632 return error("Invalid record");
4634 SI->addCase(CaseVal, DestBB);
4639 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4640 if (Record.size() < 2)
4641 return error("Invalid record");
4642 Type *OpTy = getTypeByID(Record[0]);
4643 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4644 if (!OpTy || !Address)
4645 return error("Invalid record");
4646 unsigned NumDests = Record.size()-2;
4647 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4648 InstructionList.push_back(IBI);
4649 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4650 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4651 IBI->addDestination(DestBB);
4654 return error("Invalid record");
4661 case bitc::FUNC_CODE_INST_INVOKE: {
4662 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4663 if (Record.size() < 4)
4664 return error("Invalid record");
4666 AttributeSet PAL = getAttributes(Record[OpNum++]);
4667 unsigned CCInfo = Record[OpNum++];
4668 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4669 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4671 FunctionType *FTy = nullptr;
4672 if (CCInfo >> 13 & 1 &&
4673 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4674 return error("Explicit invoke type is not a function type");
4677 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4678 return error("Invalid record");
4680 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4682 return error("Callee is not a pointer");
4684 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4686 return error("Callee is not of pointer to function type");
4687 } else if (CalleeTy->getElementType() != FTy)
4688 return error("Explicit invoke type does not match pointee type of "
4690 if (Record.size() < FTy->getNumParams() + OpNum)
4691 return error("Insufficient operands to call");
4693 SmallVector<Value*, 16> Ops;
4694 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4695 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4696 FTy->getParamType(i)));
4698 return error("Invalid record");
4701 if (!FTy->isVarArg()) {
4702 if (Record.size() != OpNum)
4703 return error("Invalid record");
4705 // Read type/value pairs for varargs params.
4706 while (OpNum != Record.size()) {
4708 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4709 return error("Invalid record");
4714 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4715 OperandBundles.clear();
4716 InstructionList.push_back(I);
4717 cast<InvokeInst>(I)->setCallingConv(
4718 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4719 cast<InvokeInst>(I)->setAttributes(PAL);
4722 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4724 Value *Val = nullptr;
4725 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4726 return error("Invalid record");
4727 I = ResumeInst::Create(Val);
4728 InstructionList.push_back(I);
4731 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4732 I = new UnreachableInst(Context);
4733 InstructionList.push_back(I);
4735 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4736 if (Record.size() < 1 || ((Record.size()-1)&1))
4737 return error("Invalid record");
4738 Type *Ty = getTypeByID(Record[0]);
4740 return error("Invalid record");
4742 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4743 InstructionList.push_back(PN);
4745 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4747 // With the new function encoding, it is possible that operands have
4748 // negative IDs (for forward references). Use a signed VBR
4749 // representation to keep the encoding small.
4751 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4753 V = getValue(Record, 1+i, NextValueNo, Ty);
4754 BasicBlock *BB = getBasicBlock(Record[2+i]);
4756 return error("Invalid record");
4757 PN->addIncoming(V, BB);
4763 case bitc::FUNC_CODE_INST_LANDINGPAD:
4764 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4765 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4767 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4768 if (Record.size() < 3)
4769 return error("Invalid record");
4771 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4772 if (Record.size() < 4)
4773 return error("Invalid record");
4775 Type *Ty = getTypeByID(Record[Idx++]);
4777 return error("Invalid record");
4778 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4779 Value *PersFn = nullptr;
4780 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4781 return error("Invalid record");
4783 if (!F->hasPersonalityFn())
4784 F->setPersonalityFn(cast<Constant>(PersFn));
4785 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4786 return error("Personality function mismatch");
4789 bool IsCleanup = !!Record[Idx++];
4790 unsigned NumClauses = Record[Idx++];
4791 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4792 LP->setCleanup(IsCleanup);
4793 for (unsigned J = 0; J != NumClauses; ++J) {
4794 LandingPadInst::ClauseType CT =
4795 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4798 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4800 return error("Invalid record");
4803 assert((CT != LandingPadInst::Catch ||
4804 !isa<ArrayType>(Val->getType())) &&
4805 "Catch clause has a invalid type!");
4806 assert((CT != LandingPadInst::Filter ||
4807 isa<ArrayType>(Val->getType())) &&
4808 "Filter clause has invalid type!");
4809 LP->addClause(cast<Constant>(Val));
4813 InstructionList.push_back(I);
4817 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4818 if (Record.size() != 4)
4819 return error("Invalid record");
4820 uint64_t AlignRecord = Record[3];
4821 const uint64_t InAllocaMask = uint64_t(1) << 5;
4822 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4823 // Reserve bit 7 for SwiftError flag.
4824 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4825 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4826 bool InAlloca = AlignRecord & InAllocaMask;
4827 Type *Ty = getTypeByID(Record[0]);
4828 if ((AlignRecord & ExplicitTypeMask) == 0) {
4829 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4831 return error("Old-style alloca with a non-pointer type");
4832 Ty = PTy->getElementType();
4834 Type *OpTy = getTypeByID(Record[1]);
4835 Value *Size = getFnValueByID(Record[2], OpTy);
4837 if (std::error_code EC =
4838 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4842 return error("Invalid record");
4843 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4844 AI->setUsedWithInAlloca(InAlloca);
4846 InstructionList.push_back(I);
4849 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4852 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4853 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4854 return error("Invalid record");
4857 if (OpNum + 3 == Record.size())
4858 Ty = getTypeByID(Record[OpNum++]);
4859 if (std::error_code EC =
4860 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4863 Ty = cast<PointerType>(Op->getType())->getElementType();
4866 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4868 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4870 InstructionList.push_back(I);
4873 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4874 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4877 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4878 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4879 return error("Invalid record");
4882 if (OpNum + 5 == Record.size())
4883 Ty = getTypeByID(Record[OpNum++]);
4884 if (std::error_code EC =
4885 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4888 Ty = cast<PointerType>(Op->getType())->getElementType();
4890 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4891 if (Ordering == NotAtomic || Ordering == Release ||
4892 Ordering == AcquireRelease)
4893 return error("Invalid record");
4894 if (Ordering != NotAtomic && Record[OpNum] == 0)
4895 return error("Invalid record");
4896 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4899 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4901 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4903 InstructionList.push_back(I);
4906 case bitc::FUNC_CODE_INST_STORE:
4907 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4910 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4911 (BitCode == bitc::FUNC_CODE_INST_STORE
4912 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4913 : popValue(Record, OpNum, NextValueNo,
4914 cast<PointerType>(Ptr->getType())->getElementType(),
4916 OpNum + 2 != Record.size())
4917 return error("Invalid record");
4919 if (std::error_code EC = typeCheckLoadStoreInst(
4920 DiagnosticHandler, Val->getType(), Ptr->getType()))
4923 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4925 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4926 InstructionList.push_back(I);
4929 case bitc::FUNC_CODE_INST_STOREATOMIC:
4930 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4931 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4934 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4935 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4936 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4937 : popValue(Record, OpNum, NextValueNo,
4938 cast<PointerType>(Ptr->getType())->getElementType(),
4940 OpNum + 4 != Record.size())
4941 return error("Invalid record");
4943 if (std::error_code EC = typeCheckLoadStoreInst(
4944 DiagnosticHandler, Val->getType(), Ptr->getType()))
4946 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4947 if (Ordering == NotAtomic || Ordering == Acquire ||
4948 Ordering == AcquireRelease)
4949 return error("Invalid record");
4950 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4951 if (Ordering != NotAtomic && Record[OpNum] == 0)
4952 return error("Invalid record");
4955 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4957 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4958 InstructionList.push_back(I);
4961 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4962 case bitc::FUNC_CODE_INST_CMPXCHG: {
4963 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4964 // failureordering?, isweak?]
4966 Value *Ptr, *Cmp, *New;
4967 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4968 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4969 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4970 : popValue(Record, OpNum, NextValueNo,
4971 cast<PointerType>(Ptr->getType())->getElementType(),
4973 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4974 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4975 return error("Invalid record");
4976 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4977 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4978 return error("Invalid record");
4979 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4981 if (std::error_code EC = typeCheckLoadStoreInst(
4982 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4984 AtomicOrdering FailureOrdering;
4985 if (Record.size() < 7)
4987 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4989 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4991 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4993 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4995 if (Record.size() < 8) {
4996 // Before weak cmpxchgs existed, the instruction simply returned the
4997 // value loaded from memory, so bitcode files from that era will be
4998 // expecting the first component of a modern cmpxchg.
4999 CurBB->getInstList().push_back(I);
5000 I = ExtractValueInst::Create(I, 0);
5002 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5005 InstructionList.push_back(I);
5008 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5009 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5012 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5013 popValue(Record, OpNum, NextValueNo,
5014 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5015 OpNum+4 != Record.size())
5016 return error("Invalid record");
5017 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5018 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5019 Operation > AtomicRMWInst::LAST_BINOP)
5020 return error("Invalid record");
5021 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5022 if (Ordering == NotAtomic || Ordering == Unordered)
5023 return error("Invalid record");
5024 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5025 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5026 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5027 InstructionList.push_back(I);
5030 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5031 if (2 != Record.size())
5032 return error("Invalid record");
5033 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5034 if (Ordering == NotAtomic || Ordering == Unordered ||
5035 Ordering == Monotonic)
5036 return error("Invalid record");
5037 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5038 I = new FenceInst(Context, Ordering, SynchScope);
5039 InstructionList.push_back(I);
5042 case bitc::FUNC_CODE_INST_CALL: {
5043 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
5044 if (Record.size() < 3)
5045 return error("Invalid record");
5048 AttributeSet PAL = getAttributes(Record[OpNum++]);
5049 unsigned CCInfo = Record[OpNum++];
5051 FunctionType *FTy = nullptr;
5052 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5053 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5054 return error("Explicit call type is not a function type");
5057 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5058 return error("Invalid record");
5060 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5062 return error("Callee is not a pointer type");
5064 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5066 return error("Callee is not of pointer to function type");
5067 } else if (OpTy->getElementType() != FTy)
5068 return error("Explicit call type does not match pointee type of "
5070 if (Record.size() < FTy->getNumParams() + OpNum)
5071 return error("Insufficient operands to call");
5073 SmallVector<Value*, 16> Args;
5074 // Read the fixed params.
5075 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5076 if (FTy->getParamType(i)->isLabelTy())
5077 Args.push_back(getBasicBlock(Record[OpNum]));
5079 Args.push_back(getValue(Record, OpNum, NextValueNo,
5080 FTy->getParamType(i)));
5082 return error("Invalid record");
5085 // Read type/value pairs for varargs params.
5086 if (!FTy->isVarArg()) {
5087 if (OpNum != Record.size())
5088 return error("Invalid record");
5090 while (OpNum != Record.size()) {
5092 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5093 return error("Invalid record");
5098 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5099 OperandBundles.clear();
5100 InstructionList.push_back(I);
5101 cast<CallInst>(I)->setCallingConv(
5102 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5103 CallInst::TailCallKind TCK = CallInst::TCK_None;
5104 if (CCInfo & 1 << bitc::CALL_TAIL)
5105 TCK = CallInst::TCK_Tail;
5106 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5107 TCK = CallInst::TCK_MustTail;
5108 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5109 TCK = CallInst::TCK_NoTail;
5110 cast<CallInst>(I)->setTailCallKind(TCK);
5111 cast<CallInst>(I)->setAttributes(PAL);
5114 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5115 if (Record.size() < 3)
5116 return error("Invalid record");
5117 Type *OpTy = getTypeByID(Record[0]);
5118 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5119 Type *ResTy = getTypeByID(Record[2]);
5120 if (!OpTy || !Op || !ResTy)
5121 return error("Invalid record");
5122 I = new VAArgInst(Op, ResTy);
5123 InstructionList.push_back(I);
5127 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5128 // A call or an invoke can be optionally prefixed with some variable
5129 // number of operand bundle blocks. These blocks are read into
5130 // OperandBundles and consumed at the next call or invoke instruction.
5132 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5133 return error("Invalid record");
5135 std::vector<Value *> Inputs;
5138 while (OpNum != Record.size()) {
5140 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5141 return error("Invalid record");
5142 Inputs.push_back(Op);
5145 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5150 // Add instruction to end of current BB. If there is no current BB, reject
5154 return error("Invalid instruction with no BB");
5156 if (!OperandBundles.empty()) {
5158 return error("Operand bundles found with no consumer");
5160 CurBB->getInstList().push_back(I);
5162 // If this was a terminator instruction, move to the next block.
5163 if (isa<TerminatorInst>(I)) {
5165 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5168 // Non-void values get registered in the value table for future use.
5169 if (I && !I->getType()->isVoidTy())
5170 ValueList.assignValue(I, NextValueNo++);
5175 if (!OperandBundles.empty())
5176 return error("Operand bundles found with no consumer");
5178 // Check the function list for unresolved values.
5179 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5180 if (!A->getParent()) {
5181 // We found at least one unresolved value. Nuke them all to avoid leaks.
5182 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5183 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5184 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5188 return error("Never resolved value found in function");
5192 // FIXME: Check for unresolved forward-declared metadata references
5193 // and clean up leaks.
5195 // Trim the value list down to the size it was before we parsed this function.
5196 ValueList.shrinkTo(ModuleValueListSize);
5197 MDValueList.shrinkTo(ModuleMDValueListSize);
5198 std::vector<BasicBlock*>().swap(FunctionBBs);
5199 return std::error_code();
5202 /// Find the function body in the bitcode stream
5203 std::error_code BitcodeReader::findFunctionInStream(
5205 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5206 while (DeferredFunctionInfoIterator->second == 0) {
5207 // This is the fallback handling for the old format bitcode that
5208 // didn't contain the function index in the VST, or when we have
5209 // an anonymous function which would not have a VST entry.
5210 // Assert that we have one of those two cases.
5211 assert(VSTOffset == 0 || !F->hasName());
5212 // Parse the next body in the stream and set its position in the
5213 // DeferredFunctionInfo map.
5214 if (std::error_code EC = rememberAndSkipFunctionBodies())
5217 return std::error_code();
5220 //===----------------------------------------------------------------------===//
5221 // GVMaterializer implementation
5222 //===----------------------------------------------------------------------===//
5224 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5226 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5227 // In older bitcode we must materialize the metadata before parsing
5228 // any functions, in order to set up the MDValueList properly.
5229 if (!SeenModuleValuesRecord) {
5230 if (std::error_code EC = materializeMetadata())
5234 Function *F = dyn_cast<Function>(GV);
5235 // If it's not a function or is already material, ignore the request.
5236 if (!F || !F->isMaterializable())
5237 return std::error_code();
5239 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5240 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5241 // If its position is recorded as 0, its body is somewhere in the stream
5242 // but we haven't seen it yet.
5243 if (DFII->second == 0)
5244 if (std::error_code EC = findFunctionInStream(F, DFII))
5247 // Move the bit stream to the saved position of the deferred function body.
5248 Stream.JumpToBit(DFII->second);
5250 if (std::error_code EC = parseFunctionBody(F))
5252 F->setIsMaterializable(false);
5257 // Upgrade any old intrinsic calls in the function.
5258 for (auto &I : UpgradedIntrinsics) {
5259 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5262 if (CallInst *CI = dyn_cast<CallInst>(U))
5263 UpgradeIntrinsicCall(CI, I.second);
5267 // Finish fn->subprogram upgrade for materialized functions.
5268 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5269 F->setSubprogram(SP);
5271 // Bring in any functions that this function forward-referenced via
5273 return materializeForwardReferencedFunctions();
5276 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5277 const Function *F = dyn_cast<Function>(GV);
5278 if (!F || F->isDeclaration())
5281 // Dematerializing F would leave dangling references that wouldn't be
5282 // reconnected on re-materialization.
5283 if (BlockAddressesTaken.count(F))
5286 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5289 void BitcodeReader::dematerialize(GlobalValue *GV) {
5290 Function *F = dyn_cast<Function>(GV);
5291 // If this function isn't dematerializable, this is a noop.
5292 if (!F || !isDematerializable(F))
5295 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5297 // Just forget the function body, we can remat it later.
5298 F->dropAllReferences();
5299 F->setIsMaterializable(true);
5302 std::error_code BitcodeReader::materializeModule(Module *M) {
5303 assert(M == TheModule &&
5304 "Can only Materialize the Module this BitcodeReader is attached to.");
5306 if (std::error_code EC = materializeMetadata())
5309 // Promise to materialize all forward references.
5310 WillMaterializeAllForwardRefs = true;
5312 // Iterate over the module, deserializing any functions that are still on
5314 for (Function &F : *TheModule) {
5315 if (std::error_code EC = materialize(&F))
5318 // At this point, if there are any function bodies, parse the rest of
5319 // the bits in the module past the last function block we have recorded
5320 // through either lazy scanning or the VST.
5321 if (LastFunctionBlockBit || NextUnreadBit)
5322 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5325 // Check that all block address forward references got resolved (as we
5327 if (!BasicBlockFwdRefs.empty())
5328 return error("Never resolved function from blockaddress");
5330 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5331 // delete the old functions to clean up. We can't do this unless the entire
5332 // module is materialized because there could always be another function body
5333 // with calls to the old function.
5334 for (auto &I : UpgradedIntrinsics) {
5335 for (auto *U : I.first->users()) {
5336 if (CallInst *CI = dyn_cast<CallInst>(U))
5337 UpgradeIntrinsicCall(CI, I.second);
5339 if (!I.first->use_empty())
5340 I.first->replaceAllUsesWith(I.second);
5341 I.first->eraseFromParent();
5343 UpgradedIntrinsics.clear();
5345 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5346 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5348 UpgradeDebugInfo(*M);
5349 return std::error_code();
5352 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5353 return IdentifiedStructTypes;
5357 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5359 return initLazyStream(std::move(Streamer));
5360 return initStreamFromBuffer();
5363 std::error_code BitcodeReader::initStreamFromBuffer() {
5364 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5365 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5367 if (Buffer->getBufferSize() & 3)
5368 return error("Invalid bitcode signature");
5370 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5371 // The magic number is 0x0B17C0DE stored in little endian.
5372 if (isBitcodeWrapper(BufPtr, BufEnd))
5373 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5374 return error("Invalid bitcode wrapper header");
5376 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5377 Stream.init(&*StreamFile);
5379 return std::error_code();
5383 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5384 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5387 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5388 StreamingMemoryObject &Bytes = *OwnedBytes;
5389 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5390 Stream.init(&*StreamFile);
5392 unsigned char buf[16];
5393 if (Bytes.readBytes(buf, 16, 0) != 16)
5394 return error("Invalid bitcode signature");
5396 if (!isBitcode(buf, buf + 16))
5397 return error("Invalid bitcode signature");
5399 if (isBitcodeWrapper(buf, buf + 4)) {
5400 const unsigned char *bitcodeStart = buf;
5401 const unsigned char *bitcodeEnd = buf + 16;
5402 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5403 Bytes.dropLeadingBytes(bitcodeStart - buf);
5404 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5406 return std::error_code();
5409 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5410 const Twine &Message) {
5411 return ::error(DiagnosticHandler, make_error_code(E), Message);
5414 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5415 return ::error(DiagnosticHandler,
5416 make_error_code(BitcodeError::CorruptedBitcode), Message);
5419 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5420 return ::error(DiagnosticHandler, make_error_code(E));
5423 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5424 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5425 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5426 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
5427 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5429 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5430 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5431 bool CheckFuncSummaryPresenceOnly)
5432 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
5433 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5435 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5437 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5439 // Specialized value symbol table parser used when reading function index
5440 // blocks where we don't actually create global values.
5441 // At the end of this routine the function index is populated with a map
5442 // from function name to FunctionInfo. The function info contains
5443 // the function block's bitcode offset as well as the offset into the
5444 // function summary section.
5445 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5446 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5447 return error("Invalid record");
5449 SmallVector<uint64_t, 64> Record;
5451 // Read all the records for this value table.
5452 SmallString<128> ValueName;
5454 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5456 switch (Entry.Kind) {
5457 case BitstreamEntry::SubBlock: // Handled for us already.
5458 case BitstreamEntry::Error:
5459 return error("Malformed block");
5460 case BitstreamEntry::EndBlock:
5461 return std::error_code();
5462 case BitstreamEntry::Record:
5463 // The interesting case.
5469 switch (Stream.readRecord(Entry.ID, Record)) {
5470 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5472 case bitc::VST_CODE_FNENTRY: {
5473 // VST_FNENTRY: [valueid, offset, namechar x N]
5474 if (convertToString(Record, 2, ValueName))
5475 return error("Invalid record");
5476 unsigned ValueID = Record[0];
5477 uint64_t FuncOffset = Record[1];
5478 std::unique_ptr<FunctionInfo> FuncInfo =
5479 llvm::make_unique<FunctionInfo>(FuncOffset);
5480 if (foundFuncSummary() && !IsLazy) {
5481 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5482 SummaryMap.find(ValueID);
5483 assert(SMI != SummaryMap.end() && "Summary info not found");
5484 FuncInfo->setFunctionSummary(std::move(SMI->second));
5486 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5491 case bitc::VST_CODE_COMBINED_FNENTRY: {
5492 // VST_FNENTRY: [offset, namechar x N]
5493 if (convertToString(Record, 1, ValueName))
5494 return error("Invalid record");
5495 uint64_t FuncSummaryOffset = Record[0];
5496 std::unique_ptr<FunctionInfo> FuncInfo =
5497 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5498 if (foundFuncSummary() && !IsLazy) {
5499 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5500 SummaryMap.find(FuncSummaryOffset);
5501 assert(SMI != SummaryMap.end() && "Summary info not found");
5502 FuncInfo->setFunctionSummary(std::move(SMI->second));
5504 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5513 // Parse just the blocks needed for function index building out of the module.
5514 // At the end of this routine the function Index is populated with a map
5515 // from function name to FunctionInfo. The function info contains
5516 // either the parsed function summary information (when parsing summaries
5517 // eagerly), or just to the function summary record's offset
5518 // if parsing lazily (IsLazy).
5519 std::error_code FunctionIndexBitcodeReader::parseModule() {
5520 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5521 return error("Invalid record");
5523 // Read the function index for this module.
5525 BitstreamEntry Entry = Stream.advance();
5527 switch (Entry.Kind) {
5528 case BitstreamEntry::Error:
5529 return error("Malformed block");
5530 case BitstreamEntry::EndBlock:
5531 return std::error_code();
5533 case BitstreamEntry::SubBlock:
5534 if (CheckFuncSummaryPresenceOnly) {
5535 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) {
5536 SeenFuncSummary = true;
5537 // No need to parse the rest since we found the summary.
5538 return std::error_code();
5540 if (Stream.SkipBlock())
5541 return error("Invalid record");
5545 default: // Skip unknown content.
5546 if (Stream.SkipBlock())
5547 return error("Invalid record");
5549 case bitc::BLOCKINFO_BLOCK_ID:
5550 // Need to parse these to get abbrev ids (e.g. for VST)
5551 if (Stream.ReadBlockInfoBlock())
5552 return error("Malformed block");
5554 case bitc::VALUE_SYMTAB_BLOCK_ID:
5555 if (std::error_code EC = parseValueSymbolTable())
5558 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5559 SeenFuncSummary = true;
5561 // Lazy parsing of summary info, skip it.
5562 if (Stream.SkipBlock())
5563 return error("Invalid record");
5564 } else if (std::error_code EC = parseEntireSummary())
5567 case bitc::MODULE_STRTAB_BLOCK_ID:
5568 if (std::error_code EC = parseModuleStringTable())
5574 case BitstreamEntry::Record:
5575 Stream.skipRecord(Entry.ID);
5581 // Eagerly parse the entire function summary block (i.e. for all functions
5582 // in the index). This populates the FunctionSummary objects in
5584 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5585 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5586 return error("Invalid record");
5588 SmallVector<uint64_t, 64> Record;
5591 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5593 switch (Entry.Kind) {
5594 case BitstreamEntry::SubBlock: // Handled for us already.
5595 case BitstreamEntry::Error:
5596 return error("Malformed block");
5597 case BitstreamEntry::EndBlock:
5598 return std::error_code();
5599 case BitstreamEntry::Record:
5600 // The interesting case.
5604 // Read a record. The record format depends on whether this
5605 // is a per-module index or a combined index file. In the per-module
5606 // case the records contain the associated value's ID for correlation
5607 // with VST entries. In the combined index the correlation is done
5608 // via the bitcode offset of the summary records (which were saved
5609 // in the combined index VST entries). The records also contain
5610 // information used for ThinLTO renaming and importing.
5612 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5613 switch (Stream.readRecord(Entry.ID, Record)) {
5614 default: // Default behavior: ignore.
5616 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5617 case bitc::FS_CODE_PERMODULE_ENTRY: {
5618 unsigned ValueID = Record[0];
5619 bool IsLocal = Record[1];
5620 unsigned InstCount = Record[2];
5621 std::unique_ptr<FunctionSummary> FS =
5622 llvm::make_unique<FunctionSummary>(InstCount);
5623 FS->setLocalFunction(IsLocal);
5624 // The module path string ref set in the summary must be owned by the
5625 // index's module string table. Since we don't have a module path
5626 // string table section in the per-module index, we create a single
5627 // module path string table entry with an empty (0) ID to take
5630 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5631 SummaryMap[ValueID] = std::move(FS);
5633 // FS_COMBINED_ENTRY: [modid, instcount]
5634 case bitc::FS_CODE_COMBINED_ENTRY: {
5635 uint64_t ModuleId = Record[0];
5636 unsigned InstCount = Record[1];
5637 std::unique_ptr<FunctionSummary> FS =
5638 llvm::make_unique<FunctionSummary>(InstCount);
5639 FS->setModulePath(ModuleIdMap[ModuleId]);
5640 SummaryMap[CurRecordBit] = std::move(FS);
5644 llvm_unreachable("Exit infinite loop");
5647 // Parse the module string table block into the Index.
5648 // This populates the ModulePathStringTable map in the index.
5649 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5650 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5651 return error("Invalid record");
5653 SmallVector<uint64_t, 64> Record;
5655 SmallString<128> ModulePath;
5657 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5659 switch (Entry.Kind) {
5660 case BitstreamEntry::SubBlock: // Handled for us already.
5661 case BitstreamEntry::Error:
5662 return error("Malformed block");
5663 case BitstreamEntry::EndBlock:
5664 return std::error_code();
5665 case BitstreamEntry::Record:
5666 // The interesting case.
5671 switch (Stream.readRecord(Entry.ID, Record)) {
5672 default: // Default behavior: ignore.
5674 case bitc::MST_CODE_ENTRY: {
5675 // MST_ENTRY: [modid, namechar x N]
5676 if (convertToString(Record, 1, ModulePath))
5677 return error("Invalid record");
5678 uint64_t ModuleId = Record[0];
5679 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5680 ModuleIdMap[ModuleId] = ModulePathInMap;
5686 llvm_unreachable("Exit infinite loop");
5689 // Parse the function info index from the bitcode streamer into the given index.
5690 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5691 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5694 if (std::error_code EC = initStream(std::move(Streamer)))
5697 // Sniff for the signature.
5698 if (!hasValidBitcodeHeader(Stream))
5699 return error("Invalid bitcode signature");
5701 // We expect a number of well-defined blocks, though we don't necessarily
5702 // need to understand them all.
5704 if (Stream.AtEndOfStream()) {
5705 // We didn't really read a proper Module block.
5706 return error("Malformed block");
5709 BitstreamEntry Entry =
5710 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5712 if (Entry.Kind != BitstreamEntry::SubBlock)
5713 return error("Malformed block");
5715 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5716 // building the function summary index.
5717 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5718 return parseModule();
5720 if (Stream.SkipBlock())
5721 return error("Invalid record");
5725 // Parse the function information at the given offset in the buffer into
5726 // the index. Used to support lazy parsing of function summaries from the
5727 // combined index during importing.
5728 // TODO: This function is not yet complete as it won't have a consumer
5729 // until ThinLTO function importing is added.
5730 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5731 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5732 size_t FunctionSummaryOffset) {
5735 if (std::error_code EC = initStream(std::move(Streamer)))
5738 // Sniff for the signature.
5739 if (!hasValidBitcodeHeader(Stream))
5740 return error("Invalid bitcode signature");
5742 Stream.JumpToBit(FunctionSummaryOffset);
5744 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5746 switch (Entry.Kind) {
5748 return error("Malformed block");
5749 case BitstreamEntry::Record:
5750 // The expected case.
5754 // TODO: Read a record. This interface will be completed when ThinLTO
5755 // importing is added so that it can be tested.
5756 SmallVector<uint64_t, 64> Record;
5757 switch (Stream.readRecord(Entry.ID, Record)) {
5758 case bitc::FS_CODE_COMBINED_ENTRY:
5760 return error("Invalid record");
5763 return std::error_code();
5767 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5769 return initLazyStream(std::move(Streamer));
5770 return initStreamFromBuffer();
5773 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5774 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5775 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5777 if (Buffer->getBufferSize() & 3)
5778 return error("Invalid bitcode signature");
5780 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5781 // The magic number is 0x0B17C0DE stored in little endian.
5782 if (isBitcodeWrapper(BufPtr, BufEnd))
5783 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5784 return error("Invalid bitcode wrapper header");
5786 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5787 Stream.init(&*StreamFile);
5789 return std::error_code();
5792 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5793 std::unique_ptr<DataStreamer> Streamer) {
5794 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5797 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5798 StreamingMemoryObject &Bytes = *OwnedBytes;
5799 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5800 Stream.init(&*StreamFile);
5802 unsigned char buf[16];
5803 if (Bytes.readBytes(buf, 16, 0) != 16)
5804 return error("Invalid bitcode signature");
5806 if (!isBitcode(buf, buf + 16))
5807 return error("Invalid bitcode signature");
5809 if (isBitcodeWrapper(buf, buf + 4)) {
5810 const unsigned char *bitcodeStart = buf;
5811 const unsigned char *bitcodeEnd = buf + 16;
5812 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5813 Bytes.dropLeadingBytes(bitcodeStart - buf);
5814 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5816 return std::error_code();
5820 class BitcodeErrorCategoryType : public std::error_category {
5821 const char *name() const LLVM_NOEXCEPT override {
5822 return "llvm.bitcode";
5824 std::string message(int IE) const override {
5825 BitcodeError E = static_cast<BitcodeError>(IE);
5827 case BitcodeError::InvalidBitcodeSignature:
5828 return "Invalid bitcode signature";
5829 case BitcodeError::CorruptedBitcode:
5830 return "Corrupted bitcode";
5832 llvm_unreachable("Unknown error type!");
5837 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5839 const std::error_category &llvm::BitcodeErrorCategory() {
5840 return *ErrorCategory;
5843 //===----------------------------------------------------------------------===//
5844 // External interface
5845 //===----------------------------------------------------------------------===//
5847 static ErrorOr<std::unique_ptr<Module>>
5848 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5849 BitcodeReader *R, LLVMContext &Context,
5850 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5851 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5852 M->setMaterializer(R);
5854 auto cleanupOnError = [&](std::error_code EC) {
5855 R->releaseBuffer(); // Never take ownership on error.
5859 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5860 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5861 ShouldLazyLoadMetadata))
5862 return cleanupOnError(EC);
5864 if (MaterializeAll) {
5865 // Read in the entire module, and destroy the BitcodeReader.
5866 if (std::error_code EC = M->materializeAllPermanently())
5867 return cleanupOnError(EC);
5869 // Resolve forward references from blockaddresses.
5870 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5871 return cleanupOnError(EC);
5873 return std::move(M);
5876 /// \brief Get a lazy one-at-time loading module from bitcode.
5878 /// This isn't always used in a lazy context. In particular, it's also used by
5879 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5880 /// in forward-referenced functions from block address references.
5882 /// \param[in] MaterializeAll Set to \c true if we should materialize
5884 static ErrorOr<std::unique_ptr<Module>>
5885 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5886 LLVMContext &Context, bool MaterializeAll,
5887 DiagnosticHandlerFunction DiagnosticHandler,
5888 bool ShouldLazyLoadMetadata = false) {
5890 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5892 ErrorOr<std::unique_ptr<Module>> Ret =
5893 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5894 MaterializeAll, ShouldLazyLoadMetadata);
5898 Buffer.release(); // The BitcodeReader owns it now.
5902 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5903 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5904 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5905 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5906 DiagnosticHandler, ShouldLazyLoadMetadata);
5909 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5910 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5911 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5912 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5913 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5915 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5919 ErrorOr<std::unique_ptr<Module>>
5920 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5921 DiagnosticHandlerFunction DiagnosticHandler) {
5922 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5923 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5925 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5926 // written. We must defer until the Module has been fully materialized.
5930 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5931 DiagnosticHandlerFunction DiagnosticHandler) {
5932 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5933 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5935 ErrorOr<std::string> Triple = R->parseTriple();
5936 if (Triple.getError())
5938 return Triple.get();
5942 llvm::getBitcodeProducerString(MemoryBufferRef Buffer, LLVMContext &Context,
5943 DiagnosticHandlerFunction DiagnosticHandler) {
5944 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5945 BitcodeReader R(Buf.release(), Context, DiagnosticHandler);
5946 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5947 if (ProducerString.getError())
5949 return ProducerString.get();
5952 // Parse the specified bitcode buffer, returning the function info index.
5953 // If IsLazy is false, parse the entire function summary into
5954 // the index. Otherwise skip the function summary section, and only create
5955 // an index object with a map from function name to function summary offset.
5956 // The index is used to perform lazy function summary reading later.
5957 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5958 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer,
5959 DiagnosticHandlerFunction DiagnosticHandler,
5961 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5962 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
5964 auto Index = llvm::make_unique<FunctionInfoIndex>();
5966 auto cleanupOnError = [&](std::error_code EC) {
5967 R.releaseBuffer(); // Never take ownership on error.
5971 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5972 return cleanupOnError(EC);
5974 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5975 return std::move(Index);
5978 // Check if the given bitcode buffer contains a function summary block.
5979 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer,
5980 DiagnosticHandlerFunction DiagnosticHandler) {
5981 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5982 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
5984 auto cleanupOnError = [&](std::error_code EC) {
5985 R.releaseBuffer(); // Never take ownership on error.
5989 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5990 return cleanupOnError(EC);
5992 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5993 return R.foundFuncSummary();
5996 // This method supports lazy reading of function summary data from the combined
5997 // index during ThinLTO function importing. When reading the combined index
5998 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5999 // Then this method is called for each function considered for importing,
6000 // to parse the summary information for the given function name into
6002 std::error_code llvm::readFunctionSummary(
6003 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
6004 StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) {
6005 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6006 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
6008 auto cleanupOnError = [&](std::error_code EC) {
6009 R.releaseBuffer(); // Never take ownership on error.
6013 // Lookup the given function name in the FunctionMap, which may
6014 // contain a list of function infos in the case of a COMDAT. Walk through
6015 // and parse each function summary info at the function summary offset
6016 // recorded when parsing the value symbol table.
6017 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
6018 size_t FunctionSummaryOffset = FI->bitcodeIndex();
6019 if (std::error_code EC =
6020 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
6021 return cleanupOnError(EC);
6024 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
6025 return std::error_code();