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 /// Indicates which operator an operand allows (for the few operands that may
46 /// only reference a certain operator).
47 enum OperatorConstraint {
48 OC_None = 0, // No constraint
49 OC_CatchPad, // Must be CatchPadInst
50 OC_CleanupPad // Must be CleanupPadInst
53 class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
56 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
59 /// ResolveConstantForwardRefs for more information about this.
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
75 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
78 assert(ResolveConstants.empty() && "Constants not resolved?");
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
87 Value *back() const { return ValuePtrs.back(); }
88 void pop_back() { ValuePtrs.pop_back(); }
89 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
96 Value *getValueFwdRef(unsigned Idx, Type *Ty,
97 OperatorConstraint OC = OC_None);
99 bool assignValue(Value *V, unsigned Idx);
101 /// Once all constants are read, this method bulk resolves any forward
103 void resolveConstantForwardRefs();
106 class BitcodeReaderMDValueList {
111 std::vector<TrackingMDRef> MDValuePtrs;
113 LLVMContext &Context;
115 BitcodeReaderMDValueList(LLVMContext &C)
116 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
118 // vector compatibility methods
119 unsigned size() const { return MDValuePtrs.size(); }
120 void resize(unsigned N) { MDValuePtrs.resize(N); }
121 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
122 void clear() { MDValuePtrs.clear(); }
123 Metadata *back() const { return MDValuePtrs.back(); }
124 void pop_back() { MDValuePtrs.pop_back(); }
125 bool empty() const { return MDValuePtrs.empty(); }
127 Metadata *operator[](unsigned i) const {
128 assert(i < MDValuePtrs.size());
129 return MDValuePtrs[i];
132 void shrinkTo(unsigned N) {
133 assert(N <= size() && "Invalid shrinkTo request!");
134 MDValuePtrs.resize(N);
137 Metadata *getValueFwdRef(unsigned Idx);
138 void assignValue(Metadata *MD, unsigned Idx);
139 void tryToResolveCycles();
142 class BitcodeReader : public GVMaterializer {
143 LLVMContext &Context;
144 DiagnosticHandlerFunction DiagnosticHandler;
145 Module *TheModule = nullptr;
146 std::unique_ptr<MemoryBuffer> Buffer;
147 std::unique_ptr<BitstreamReader> StreamFile;
148 BitstreamCursor Stream;
149 // Next offset to start scanning for lazy parsing of function bodies.
150 uint64_t NextUnreadBit = 0;
151 // Last function offset found in the VST.
152 uint64_t LastFunctionBlockBit = 0;
153 bool SeenValueSymbolTable = false;
154 uint64_t VSTOffset = 0;
155 // Contains an arbitrary and optional string identifying the bitcode producer
156 std::string ProducerIdentification;
158 std::vector<Type*> TypeList;
159 BitcodeReaderValueList ValueList;
160 BitcodeReaderMDValueList MDValueList;
161 std::vector<Comdat *> ComdatList;
162 SmallVector<Instruction *, 64> InstructionList;
164 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
165 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
166 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
167 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
168 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
170 SmallVector<Instruction*, 64> InstsWithTBAATag;
172 /// The set of attributes by index. Index zero in the file is for null, and
173 /// is thus not represented here. As such all indices are off by one.
174 std::vector<AttributeSet> MAttributes;
176 /// The set of attribute groups.
177 std::map<unsigned, AttributeSet> MAttributeGroups;
179 /// While parsing a function body, this is a list of the basic blocks for the
181 std::vector<BasicBlock*> FunctionBBs;
183 // When reading the module header, this list is populated with functions that
184 // have bodies later in the file.
185 std::vector<Function*> FunctionsWithBodies;
187 // When intrinsic functions are encountered which require upgrading they are
188 // stored here with their replacement function.
189 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
190 UpgradedIntrinsicMap UpgradedIntrinsics;
192 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
193 DenseMap<unsigned, unsigned> MDKindMap;
195 // Several operations happen after the module header has been read, but
196 // before function bodies are processed. This keeps track of whether
197 // we've done this yet.
198 bool SeenFirstFunctionBody = false;
200 /// When function bodies are initially scanned, this map contains info about
201 /// where to find deferred function body in the stream.
202 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
204 /// When Metadata block is initially scanned when parsing the module, we may
205 /// choose to defer parsing of the metadata. This vector contains info about
206 /// which Metadata blocks are deferred.
207 std::vector<uint64_t> DeferredMetadataInfo;
209 /// These are basic blocks forward-referenced by block addresses. They are
210 /// inserted lazily into functions when they're loaded. The basic block ID is
211 /// its index into the vector.
212 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
213 std::deque<Function *> BasicBlockFwdRefQueue;
215 /// Indicates that we are using a new encoding for instruction operands where
216 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
217 /// instruction number, for a more compact encoding. Some instruction
218 /// operands are not relative to the instruction ID: basic block numbers, and
219 /// types. Once the old style function blocks have been phased out, we would
220 /// not need this flag.
221 bool UseRelativeIDs = false;
223 /// True if all functions will be materialized, negating the need to process
224 /// (e.g.) blockaddress forward references.
225 bool WillMaterializeAllForwardRefs = false;
227 /// Functions that have block addresses taken. This is usually empty.
228 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
230 /// True if any Metadata block has been materialized.
231 bool IsMetadataMaterialized = false;
233 bool StripDebugInfo = false;
235 /// Functions that need to be matched with subprograms when upgrading old
237 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
239 std::vector<std::string> BundleTags;
242 std::error_code error(BitcodeError E, const Twine &Message);
243 std::error_code error(BitcodeError E);
244 std::error_code error(const Twine &Message);
246 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
247 DiagnosticHandlerFunction DiagnosticHandler);
248 BitcodeReader(LLVMContext &Context,
249 DiagnosticHandlerFunction DiagnosticHandler);
250 ~BitcodeReader() override { freeState(); }
252 std::error_code materializeForwardReferencedFunctions();
256 void releaseBuffer();
258 bool isDematerializable(const GlobalValue *GV) const override;
259 std::error_code materialize(GlobalValue *GV) override;
260 std::error_code materializeModule(Module *M) override;
261 std::vector<StructType *> getIdentifiedStructTypes() const override;
262 void dematerialize(GlobalValue *GV) override;
264 /// \brief Main interface to parsing a bitcode buffer.
265 /// \returns true if an error occurred.
266 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
268 bool ShouldLazyLoadMetadata = false);
270 /// \brief Cheap mechanism to just extract module triple
271 /// \returns true if an error occurred.
272 ErrorOr<std::string> parseTriple();
274 /// Cheap mechanism to just extract the identification block out of bitcode.
275 ErrorOr<std::string> parseIdentificationBlock();
277 static uint64_t decodeSignRotatedValue(uint64_t V);
279 /// Materialize any deferred Metadata block.
280 std::error_code materializeMetadata() override;
282 void setStripDebugInfo() override;
285 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
286 // ProducerIdentification data member, and do some basic enforcement on the
287 // "epoch" encoded in the bitcode.
288 std::error_code parseBitcodeVersion();
290 std::vector<StructType *> IdentifiedStructTypes;
291 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
292 StructType *createIdentifiedStructType(LLVMContext &Context);
294 Type *getTypeByID(unsigned ID);
295 Value *getFnValueByID(unsigned ID, Type *Ty,
296 OperatorConstraint OC = OC_None) {
297 if (Ty && Ty->isMetadataTy())
298 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
299 return ValueList.getValueFwdRef(ID, Ty, OC);
301 Metadata *getFnMetadataByID(unsigned ID) {
302 return MDValueList.getValueFwdRef(ID);
304 BasicBlock *getBasicBlock(unsigned ID) const {
305 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
306 return FunctionBBs[ID];
308 AttributeSet getAttributes(unsigned i) const {
309 if (i-1 < MAttributes.size())
310 return MAttributes[i-1];
311 return AttributeSet();
314 /// Read a value/type pair out of the specified record from slot 'Slot'.
315 /// Increment Slot past the number of slots used in the record. Return true on
317 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
318 unsigned InstNum, Value *&ResVal) {
319 if (Slot == Record.size()) return true;
320 unsigned ValNo = (unsigned)Record[Slot++];
321 // Adjust the ValNo, if it was encoded relative to the InstNum.
323 ValNo = InstNum - ValNo;
324 if (ValNo < InstNum) {
325 // If this is not a forward reference, just return the value we already
327 ResVal = getFnValueByID(ValNo, nullptr);
328 return ResVal == nullptr;
330 if (Slot == Record.size())
333 unsigned TypeNo = (unsigned)Record[Slot++];
334 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
335 return ResVal == nullptr;
338 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
339 /// past the number of slots used by the value in the record. Return true if
340 /// there is an error.
341 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
342 unsigned InstNum, Type *Ty, Value *&ResVal,
343 OperatorConstraint OC = OC_None) {
344 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
346 // All values currently take a single record slot.
351 /// Like popValue, but does not increment the Slot number.
352 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
353 unsigned InstNum, Type *Ty, Value *&ResVal,
354 OperatorConstraint OC = OC_None) {
355 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
356 return ResVal == nullptr;
359 /// Version of getValue that returns ResVal directly, or 0 if there is an
361 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
362 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
363 if (Slot == Record.size()) return nullptr;
364 unsigned ValNo = (unsigned)Record[Slot];
365 // Adjust the ValNo, if it was encoded relative to the InstNum.
367 ValNo = InstNum - ValNo;
368 return getFnValueByID(ValNo, Ty, OC);
371 /// Like getValue, but decodes signed VBRs.
372 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
373 unsigned InstNum, Type *Ty,
374 OperatorConstraint OC = OC_None) {
375 if (Slot == Record.size()) return nullptr;
376 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
377 // Adjust the ValNo, if it was encoded relative to the InstNum.
379 ValNo = InstNum - ValNo;
380 return getFnValueByID(ValNo, Ty, OC);
383 /// Converts alignment exponent (i.e. power of two (or zero)) to the
384 /// corresponding alignment to use. If alignment is too large, returns
385 /// a corresponding error code.
386 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
387 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
388 std::error_code parseModule(uint64_t ResumeBit,
389 bool ShouldLazyLoadMetadata = false);
390 std::error_code parseAttributeBlock();
391 std::error_code parseAttributeGroupBlock();
392 std::error_code parseTypeTable();
393 std::error_code parseTypeTableBody();
394 std::error_code parseOperandBundleTags();
396 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
397 unsigned NameIndex, Triple &TT);
398 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
399 std::error_code parseConstants();
400 std::error_code rememberAndSkipFunctionBodies();
401 std::error_code rememberAndSkipFunctionBody();
402 /// Save the positions of the Metadata blocks and skip parsing the blocks.
403 std::error_code rememberAndSkipMetadata();
404 std::error_code parseFunctionBody(Function *F);
405 std::error_code globalCleanup();
406 std::error_code resolveGlobalAndAliasInits();
407 std::error_code parseMetadata();
408 std::error_code parseMetadataKinds();
409 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
410 std::error_code parseMetadataAttachment(Function &F);
411 ErrorOr<std::string> parseModuleTriple();
412 std::error_code parseUseLists();
413 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
414 std::error_code initStreamFromBuffer();
415 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
416 std::error_code findFunctionInStream(
418 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
421 /// Class to manage reading and parsing function summary index bitcode
423 class FunctionIndexBitcodeReader {
424 DiagnosticHandlerFunction DiagnosticHandler;
426 /// Eventually points to the function index built during parsing.
427 FunctionInfoIndex *TheIndex = nullptr;
429 std::unique_ptr<MemoryBuffer> Buffer;
430 std::unique_ptr<BitstreamReader> StreamFile;
431 BitstreamCursor Stream;
433 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
435 /// If false, the summary section is fully parsed into the index during
436 /// the initial parse. Otherwise, if true, the caller is expected to
437 /// invoke \a readFunctionSummary for each summary needed, and the summary
438 /// section is thus parsed lazily.
441 /// Used to indicate whether caller only wants to check for the presence
442 /// of the function summary bitcode section. All blocks are skipped,
443 /// but the SeenFuncSummary boolean is set.
444 bool CheckFuncSummaryPresenceOnly = false;
446 /// Indicates whether we have encountered a function summary section
447 /// yet during parsing, used when checking if file contains function
449 bool SeenFuncSummary = false;
451 /// \brief Map populated during function summary section parsing, and
452 /// consumed during ValueSymbolTable parsing.
454 /// Used to correlate summary records with VST entries. For the per-module
455 /// index this maps the ValueID to the parsed function summary, and
456 /// for the combined index this maps the summary record's bitcode
457 /// offset to the function summary (since in the combined index the
458 /// VST records do not hold value IDs but rather hold the function
459 /// summary record offset).
460 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
462 /// Map populated during module path string table parsing, from the
463 /// module ID to a string reference owned by the index's module
464 /// path string table, used to correlate with combined index function
466 DenseMap<uint64_t, StringRef> ModuleIdMap;
469 std::error_code error(BitcodeError E, const Twine &Message);
470 std::error_code error(BitcodeError E);
471 std::error_code error(const Twine &Message);
473 FunctionIndexBitcodeReader(MemoryBuffer *Buffer,
474 DiagnosticHandlerFunction DiagnosticHandler,
476 bool CheckFuncSummaryPresenceOnly = false);
477 FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler,
479 bool CheckFuncSummaryPresenceOnly = false);
480 ~FunctionIndexBitcodeReader() { freeState(); }
484 void releaseBuffer();
486 /// Check if the parser has encountered a function summary section.
487 bool foundFuncSummary() { return SeenFuncSummary; }
489 /// \brief Main interface to parsing a bitcode buffer.
490 /// \returns true if an error occurred.
491 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
492 FunctionInfoIndex *I);
494 /// \brief Interface for parsing a function summary lazily.
495 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
496 FunctionInfoIndex *I,
497 size_t FunctionSummaryOffset);
500 std::error_code parseModule();
501 std::error_code parseValueSymbolTable();
502 std::error_code parseEntireSummary();
503 std::error_code parseModuleStringTable();
504 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
505 std::error_code initStreamFromBuffer();
506 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
510 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
511 DiagnosticSeverity Severity,
513 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
515 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
517 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
518 std::error_code EC, const Twine &Message) {
519 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
520 DiagnosticHandler(DI);
524 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
525 std::error_code EC) {
526 return error(DiagnosticHandler, EC, EC.message());
529 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
530 const Twine &Message) {
531 return error(DiagnosticHandler,
532 make_error_code(BitcodeError::CorruptedBitcode), Message);
535 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
536 if (!ProducerIdentification.empty()) {
537 return ::error(DiagnosticHandler, make_error_code(E),
538 Message + " (Producer: '" + ProducerIdentification +
539 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
541 return ::error(DiagnosticHandler, make_error_code(E), Message);
544 std::error_code BitcodeReader::error(const Twine &Message) {
545 if (!ProducerIdentification.empty()) {
546 return ::error(DiagnosticHandler,
547 make_error_code(BitcodeError::CorruptedBitcode),
548 Message + " (Producer: '" + ProducerIdentification +
549 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
551 return ::error(DiagnosticHandler,
552 make_error_code(BitcodeError::CorruptedBitcode), Message);
555 std::error_code BitcodeReader::error(BitcodeError E) {
556 return ::error(DiagnosticHandler, make_error_code(E));
559 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
563 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
566 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
567 DiagnosticHandlerFunction DiagnosticHandler)
569 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
570 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
572 BitcodeReader::BitcodeReader(LLVMContext &Context,
573 DiagnosticHandlerFunction DiagnosticHandler)
575 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
576 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
578 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
579 if (WillMaterializeAllForwardRefs)
580 return std::error_code();
582 // Prevent recursion.
583 WillMaterializeAllForwardRefs = true;
585 while (!BasicBlockFwdRefQueue.empty()) {
586 Function *F = BasicBlockFwdRefQueue.front();
587 BasicBlockFwdRefQueue.pop_front();
588 assert(F && "Expected valid function");
589 if (!BasicBlockFwdRefs.count(F))
590 // Already materialized.
593 // Check for a function that isn't materializable to prevent an infinite
594 // loop. When parsing a blockaddress stored in a global variable, there
595 // isn't a trivial way to check if a function will have a body without a
596 // linear search through FunctionsWithBodies, so just check it here.
597 if (!F->isMaterializable())
598 return error("Never resolved function from blockaddress");
600 // Try to materialize F.
601 if (std::error_code EC = materialize(F))
604 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
607 WillMaterializeAllForwardRefs = false;
608 return std::error_code();
611 void BitcodeReader::freeState() {
613 std::vector<Type*>().swap(TypeList);
616 std::vector<Comdat *>().swap(ComdatList);
618 std::vector<AttributeSet>().swap(MAttributes);
619 std::vector<BasicBlock*>().swap(FunctionBBs);
620 std::vector<Function*>().swap(FunctionsWithBodies);
621 DeferredFunctionInfo.clear();
622 DeferredMetadataInfo.clear();
625 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
626 BasicBlockFwdRefQueue.clear();
629 //===----------------------------------------------------------------------===//
630 // Helper functions to implement forward reference resolution, etc.
631 //===----------------------------------------------------------------------===//
633 /// Convert a string from a record into an std::string, return true on failure.
634 template <typename StrTy>
635 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
637 if (Idx > Record.size())
640 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
641 Result += (char)Record[i];
645 static bool hasImplicitComdat(size_t Val) {
649 case 1: // Old WeakAnyLinkage
650 case 4: // Old LinkOnceAnyLinkage
651 case 10: // Old WeakODRLinkage
652 case 11: // Old LinkOnceODRLinkage
657 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
659 default: // Map unknown/new linkages to external
661 return GlobalValue::ExternalLinkage;
663 return GlobalValue::AppendingLinkage;
665 return GlobalValue::InternalLinkage;
667 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
669 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
671 return GlobalValue::ExternalWeakLinkage;
673 return GlobalValue::CommonLinkage;
675 return GlobalValue::PrivateLinkage;
677 return GlobalValue::AvailableExternallyLinkage;
679 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
681 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
683 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
684 case 1: // Old value with implicit comdat.
686 return GlobalValue::WeakAnyLinkage;
687 case 10: // Old value with implicit comdat.
689 return GlobalValue::WeakODRLinkage;
690 case 4: // Old value with implicit comdat.
692 return GlobalValue::LinkOnceAnyLinkage;
693 case 11: // Old value with implicit comdat.
695 return GlobalValue::LinkOnceODRLinkage;
699 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
701 default: // Map unknown visibilities to default.
702 case 0: return GlobalValue::DefaultVisibility;
703 case 1: return GlobalValue::HiddenVisibility;
704 case 2: return GlobalValue::ProtectedVisibility;
708 static GlobalValue::DLLStorageClassTypes
709 getDecodedDLLStorageClass(unsigned Val) {
711 default: // Map unknown values to default.
712 case 0: return GlobalValue::DefaultStorageClass;
713 case 1: return GlobalValue::DLLImportStorageClass;
714 case 2: return GlobalValue::DLLExportStorageClass;
718 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
720 case 0: return GlobalVariable::NotThreadLocal;
721 default: // Map unknown non-zero value to general dynamic.
722 case 1: return GlobalVariable::GeneralDynamicTLSModel;
723 case 2: return GlobalVariable::LocalDynamicTLSModel;
724 case 3: return GlobalVariable::InitialExecTLSModel;
725 case 4: return GlobalVariable::LocalExecTLSModel;
729 static int getDecodedCastOpcode(unsigned Val) {
732 case bitc::CAST_TRUNC : return Instruction::Trunc;
733 case bitc::CAST_ZEXT : return Instruction::ZExt;
734 case bitc::CAST_SEXT : return Instruction::SExt;
735 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
736 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
737 case bitc::CAST_UITOFP : return Instruction::UIToFP;
738 case bitc::CAST_SITOFP : return Instruction::SIToFP;
739 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
740 case bitc::CAST_FPEXT : return Instruction::FPExt;
741 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
742 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
743 case bitc::CAST_BITCAST : return Instruction::BitCast;
744 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
748 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
749 bool IsFP = Ty->isFPOrFPVectorTy();
750 // BinOps are only valid for int/fp or vector of int/fp types
751 if (!IsFP && !Ty->isIntOrIntVectorTy())
757 case bitc::BINOP_ADD:
758 return IsFP ? Instruction::FAdd : Instruction::Add;
759 case bitc::BINOP_SUB:
760 return IsFP ? Instruction::FSub : Instruction::Sub;
761 case bitc::BINOP_MUL:
762 return IsFP ? Instruction::FMul : Instruction::Mul;
763 case bitc::BINOP_UDIV:
764 return IsFP ? -1 : Instruction::UDiv;
765 case bitc::BINOP_SDIV:
766 return IsFP ? Instruction::FDiv : Instruction::SDiv;
767 case bitc::BINOP_UREM:
768 return IsFP ? -1 : Instruction::URem;
769 case bitc::BINOP_SREM:
770 return IsFP ? Instruction::FRem : Instruction::SRem;
771 case bitc::BINOP_SHL:
772 return IsFP ? -1 : Instruction::Shl;
773 case bitc::BINOP_LSHR:
774 return IsFP ? -1 : Instruction::LShr;
775 case bitc::BINOP_ASHR:
776 return IsFP ? -1 : Instruction::AShr;
777 case bitc::BINOP_AND:
778 return IsFP ? -1 : Instruction::And;
780 return IsFP ? -1 : Instruction::Or;
781 case bitc::BINOP_XOR:
782 return IsFP ? -1 : Instruction::Xor;
786 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
788 default: return AtomicRMWInst::BAD_BINOP;
789 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
790 case bitc::RMW_ADD: return AtomicRMWInst::Add;
791 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
792 case bitc::RMW_AND: return AtomicRMWInst::And;
793 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
794 case bitc::RMW_OR: return AtomicRMWInst::Or;
795 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
796 case bitc::RMW_MAX: return AtomicRMWInst::Max;
797 case bitc::RMW_MIN: return AtomicRMWInst::Min;
798 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
799 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
803 static AtomicOrdering getDecodedOrdering(unsigned Val) {
805 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
806 case bitc::ORDERING_UNORDERED: return Unordered;
807 case bitc::ORDERING_MONOTONIC: return Monotonic;
808 case bitc::ORDERING_ACQUIRE: return Acquire;
809 case bitc::ORDERING_RELEASE: return Release;
810 case bitc::ORDERING_ACQREL: return AcquireRelease;
811 default: // Map unknown orderings to sequentially-consistent.
812 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
816 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
818 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
819 default: // Map unknown scopes to cross-thread.
820 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
824 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
826 default: // Map unknown selection kinds to any.
827 case bitc::COMDAT_SELECTION_KIND_ANY:
829 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
830 return Comdat::ExactMatch;
831 case bitc::COMDAT_SELECTION_KIND_LARGEST:
832 return Comdat::Largest;
833 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
834 return Comdat::NoDuplicates;
835 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
836 return Comdat::SameSize;
840 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
842 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
843 FMF.setUnsafeAlgebra();
844 if (0 != (Val & FastMathFlags::NoNaNs))
846 if (0 != (Val & FastMathFlags::NoInfs))
848 if (0 != (Val & FastMathFlags::NoSignedZeros))
849 FMF.setNoSignedZeros();
850 if (0 != (Val & FastMathFlags::AllowReciprocal))
851 FMF.setAllowReciprocal();
855 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
857 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
858 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
864 /// \brief A class for maintaining the slot number definition
865 /// as a placeholder for the actual definition for forward constants defs.
866 class ConstantPlaceHolder : public ConstantExpr {
867 void operator=(const ConstantPlaceHolder &) = delete;
870 // allocate space for exactly one operand
871 void *operator new(size_t s) { return User::operator new(s, 1); }
872 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
873 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
874 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
877 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
878 static bool classof(const Value *V) {
879 return isa<ConstantExpr>(V) &&
880 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
883 /// Provide fast operand accessors
884 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
888 // FIXME: can we inherit this from ConstantExpr?
890 struct OperandTraits<ConstantPlaceHolder> :
891 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
893 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
896 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
905 WeakVH &OldV = ValuePtrs[Idx];
911 // Handle constants and non-constants (e.g. instrs) differently for
913 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
914 ResolveConstants.push_back(std::make_pair(PHC, Idx));
917 // If there was a forward reference to this value, replace it.
918 Value *PrevVal = OldV;
919 // Check operator constraints. We only put cleanuppads or catchpads in
920 // the forward value map if the value is constrained to match.
921 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
922 if (!isa<CatchPadInst>(V))
924 // Delete the dummy basic block that was created with the sentinel
926 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
927 assert(DummyBlock == CatchPad->getNormalDest());
928 CatchPad->dropAllReferences();
930 } else if (isa<CleanupPadInst>(PrevVal)) {
931 if (!isa<CleanupPadInst>(V))
934 OldV->replaceAllUsesWith(V);
942 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
947 if (Value *V = ValuePtrs[Idx]) {
948 if (Ty != V->getType())
949 report_fatal_error("Type mismatch in constant table!");
950 return cast<Constant>(V);
953 // Create and return a placeholder, which will later be RAUW'd.
954 Constant *C = new ConstantPlaceHolder(Ty, Context);
959 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
960 OperatorConstraint OC) {
961 // Bail out for a clearly invalid value. This would make us call resize(0)
968 if (Value *V = ValuePtrs[Idx]) {
969 // If the types don't match, it's invalid.
970 if (Ty && Ty != V->getType())
974 // Use dyn_cast to enforce operator constraints
977 return dyn_cast<CatchPadInst>(V);
979 return dyn_cast<CleanupPadInst>(V);
981 llvm_unreachable("Unexpected operator constraint");
985 // No type specified, must be invalid reference.
986 if (!Ty) return nullptr;
988 // Create and return a placeholder, which will later be RAUW'd.
992 V = new Argument(Ty);
995 BasicBlock *BB = BasicBlock::Create(Context);
996 V = CatchPadInst::Create(BB, BB, {});
1000 assert(OC == OC_CleanupPad && "unexpected operator constraint");
1001 V = CleanupPadInst::Create(Context, {});
1009 /// Once all constants are read, this method bulk resolves any forward
1010 /// references. The idea behind this is that we sometimes get constants (such
1011 /// as large arrays) which reference *many* forward ref constants. Replacing
1012 /// each of these causes a lot of thrashing when building/reuniquing the
1013 /// constant. Instead of doing this, we look at all the uses and rewrite all
1014 /// the place holders at once for any constant that uses a placeholder.
1015 void BitcodeReaderValueList::resolveConstantForwardRefs() {
1016 // Sort the values by-pointer so that they are efficient to look up with a
1018 std::sort(ResolveConstants.begin(), ResolveConstants.end());
1020 SmallVector<Constant*, 64> NewOps;
1022 while (!ResolveConstants.empty()) {
1023 Value *RealVal = operator[](ResolveConstants.back().second);
1024 Constant *Placeholder = ResolveConstants.back().first;
1025 ResolveConstants.pop_back();
1027 // Loop over all users of the placeholder, updating them to reference the
1028 // new value. If they reference more than one placeholder, update them all
1030 while (!Placeholder->use_empty()) {
1031 auto UI = Placeholder->user_begin();
1034 // If the using object isn't uniqued, just update the operands. This
1035 // handles instructions and initializers for global variables.
1036 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1037 UI.getUse().set(RealVal);
1041 // Otherwise, we have a constant that uses the placeholder. Replace that
1042 // constant with a new constant that has *all* placeholder uses updated.
1043 Constant *UserC = cast<Constant>(U);
1044 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1047 if (!isa<ConstantPlaceHolder>(*I)) {
1048 // Not a placeholder reference.
1050 } else if (*I == Placeholder) {
1051 // Common case is that it just references this one placeholder.
1054 // Otherwise, look up the placeholder in ResolveConstants.
1055 ResolveConstantsTy::iterator It =
1056 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1057 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1059 assert(It != ResolveConstants.end() && It->first == *I);
1060 NewOp = operator[](It->second);
1063 NewOps.push_back(cast<Constant>(NewOp));
1066 // Make the new constant.
1068 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1069 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1070 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1071 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1072 } else if (isa<ConstantVector>(UserC)) {
1073 NewC = ConstantVector::get(NewOps);
1075 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1076 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1079 UserC->replaceAllUsesWith(NewC);
1080 UserC->destroyConstant();
1084 // Update all ValueHandles, they should be the only users at this point.
1085 Placeholder->replaceAllUsesWith(RealVal);
1090 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1091 if (Idx == size()) {
1099 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1105 // If there was a forward reference to this value, replace it.
1106 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1107 PrevMD->replaceAllUsesWith(MD);
1111 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1115 if (Metadata *MD = MDValuePtrs[Idx])
1118 // Track forward refs to be resolved later.
1120 MinFwdRef = std::min(MinFwdRef, Idx);
1121 MaxFwdRef = std::max(MaxFwdRef, Idx);
1124 MinFwdRef = MaxFwdRef = Idx;
1128 // Create and return a placeholder, which will later be RAUW'd.
1129 Metadata *MD = MDNode::getTemporary(Context, None).release();
1130 MDValuePtrs[Idx].reset(MD);
1134 void BitcodeReaderMDValueList::tryToResolveCycles() {
1140 // Still forward references... can't resolve cycles.
1143 // Resolve any cycles.
1144 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1145 auto &MD = MDValuePtrs[I];
1146 auto *N = dyn_cast_or_null<MDNode>(MD);
1150 assert(!N->isTemporary() && "Unexpected forward reference");
1154 // Make sure we return early again until there's another forward ref.
1158 Type *BitcodeReader::getTypeByID(unsigned ID) {
1159 // The type table size is always specified correctly.
1160 if (ID >= TypeList.size())
1163 if (Type *Ty = TypeList[ID])
1166 // If we have a forward reference, the only possible case is when it is to a
1167 // named struct. Just create a placeholder for now.
1168 return TypeList[ID] = createIdentifiedStructType(Context);
1171 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1173 auto *Ret = StructType::create(Context, Name);
1174 IdentifiedStructTypes.push_back(Ret);
1178 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1179 auto *Ret = StructType::create(Context);
1180 IdentifiedStructTypes.push_back(Ret);
1185 //===----------------------------------------------------------------------===//
1186 // Functions for parsing blocks from the bitcode file
1187 //===----------------------------------------------------------------------===//
1190 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1191 /// been decoded from the given integer. This function must stay in sync with
1192 /// 'encodeLLVMAttributesForBitcode'.
1193 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1194 uint64_t EncodedAttrs) {
1195 // FIXME: Remove in 4.0.
1197 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1198 // the bits above 31 down by 11 bits.
1199 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1200 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1201 "Alignment must be a power of two.");
1204 B.addAlignmentAttr(Alignment);
1205 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1206 (EncodedAttrs & 0xffff));
1209 std::error_code BitcodeReader::parseAttributeBlock() {
1210 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1211 return error("Invalid record");
1213 if (!MAttributes.empty())
1214 return error("Invalid multiple blocks");
1216 SmallVector<uint64_t, 64> Record;
1218 SmallVector<AttributeSet, 8> Attrs;
1220 // Read all the records.
1222 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1224 switch (Entry.Kind) {
1225 case BitstreamEntry::SubBlock: // Handled for us already.
1226 case BitstreamEntry::Error:
1227 return error("Malformed block");
1228 case BitstreamEntry::EndBlock:
1229 return std::error_code();
1230 case BitstreamEntry::Record:
1231 // The interesting case.
1237 switch (Stream.readRecord(Entry.ID, Record)) {
1238 default: // Default behavior: ignore.
1240 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1241 // FIXME: Remove in 4.0.
1242 if (Record.size() & 1)
1243 return error("Invalid record");
1245 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1247 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1248 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1251 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1255 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1256 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1257 Attrs.push_back(MAttributeGroups[Record[i]]);
1259 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1267 // Returns Attribute::None on unrecognized codes.
1268 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1271 return Attribute::None;
1272 case bitc::ATTR_KIND_ALIGNMENT:
1273 return Attribute::Alignment;
1274 case bitc::ATTR_KIND_ALWAYS_INLINE:
1275 return Attribute::AlwaysInline;
1276 case bitc::ATTR_KIND_ARGMEMONLY:
1277 return Attribute::ArgMemOnly;
1278 case bitc::ATTR_KIND_BUILTIN:
1279 return Attribute::Builtin;
1280 case bitc::ATTR_KIND_BY_VAL:
1281 return Attribute::ByVal;
1282 case bitc::ATTR_KIND_IN_ALLOCA:
1283 return Attribute::InAlloca;
1284 case bitc::ATTR_KIND_COLD:
1285 return Attribute::Cold;
1286 case bitc::ATTR_KIND_CONVERGENT:
1287 return Attribute::Convergent;
1288 case bitc::ATTR_KIND_INLINE_HINT:
1289 return Attribute::InlineHint;
1290 case bitc::ATTR_KIND_IN_REG:
1291 return Attribute::InReg;
1292 case bitc::ATTR_KIND_JUMP_TABLE:
1293 return Attribute::JumpTable;
1294 case bitc::ATTR_KIND_MIN_SIZE:
1295 return Attribute::MinSize;
1296 case bitc::ATTR_KIND_NAKED:
1297 return Attribute::Naked;
1298 case bitc::ATTR_KIND_NEST:
1299 return Attribute::Nest;
1300 case bitc::ATTR_KIND_NO_ALIAS:
1301 return Attribute::NoAlias;
1302 case bitc::ATTR_KIND_NO_BUILTIN:
1303 return Attribute::NoBuiltin;
1304 case bitc::ATTR_KIND_NO_CAPTURE:
1305 return Attribute::NoCapture;
1306 case bitc::ATTR_KIND_NO_DUPLICATE:
1307 return Attribute::NoDuplicate;
1308 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1309 return Attribute::NoImplicitFloat;
1310 case bitc::ATTR_KIND_NO_INLINE:
1311 return Attribute::NoInline;
1312 case bitc::ATTR_KIND_NO_RECURSE:
1313 return Attribute::NoRecurse;
1314 case bitc::ATTR_KIND_NON_LAZY_BIND:
1315 return Attribute::NonLazyBind;
1316 case bitc::ATTR_KIND_NON_NULL:
1317 return Attribute::NonNull;
1318 case bitc::ATTR_KIND_DEREFERENCEABLE:
1319 return Attribute::Dereferenceable;
1320 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1321 return Attribute::DereferenceableOrNull;
1322 case bitc::ATTR_KIND_NO_RED_ZONE:
1323 return Attribute::NoRedZone;
1324 case bitc::ATTR_KIND_NO_RETURN:
1325 return Attribute::NoReturn;
1326 case bitc::ATTR_KIND_NO_UNWIND:
1327 return Attribute::NoUnwind;
1328 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1329 return Attribute::OptimizeForSize;
1330 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1331 return Attribute::OptimizeNone;
1332 case bitc::ATTR_KIND_READ_NONE:
1333 return Attribute::ReadNone;
1334 case bitc::ATTR_KIND_READ_ONLY:
1335 return Attribute::ReadOnly;
1336 case bitc::ATTR_KIND_RETURNED:
1337 return Attribute::Returned;
1338 case bitc::ATTR_KIND_RETURNS_TWICE:
1339 return Attribute::ReturnsTwice;
1340 case bitc::ATTR_KIND_S_EXT:
1341 return Attribute::SExt;
1342 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1343 return Attribute::StackAlignment;
1344 case bitc::ATTR_KIND_STACK_PROTECT:
1345 return Attribute::StackProtect;
1346 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1347 return Attribute::StackProtectReq;
1348 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1349 return Attribute::StackProtectStrong;
1350 case bitc::ATTR_KIND_SAFESTACK:
1351 return Attribute::SafeStack;
1352 case bitc::ATTR_KIND_STRUCT_RET:
1353 return Attribute::StructRet;
1354 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1355 return Attribute::SanitizeAddress;
1356 case bitc::ATTR_KIND_SANITIZE_THREAD:
1357 return Attribute::SanitizeThread;
1358 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1359 return Attribute::SanitizeMemory;
1360 case bitc::ATTR_KIND_UW_TABLE:
1361 return Attribute::UWTable;
1362 case bitc::ATTR_KIND_Z_EXT:
1363 return Attribute::ZExt;
1367 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1368 unsigned &Alignment) {
1369 // Note: Alignment in bitcode files is incremented by 1, so that zero
1370 // can be used for default alignment.
1371 if (Exponent > Value::MaxAlignmentExponent + 1)
1372 return error("Invalid alignment value");
1373 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1374 return std::error_code();
1377 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1378 Attribute::AttrKind *Kind) {
1379 *Kind = getAttrFromCode(Code);
1380 if (*Kind == Attribute::None)
1381 return error(BitcodeError::CorruptedBitcode,
1382 "Unknown attribute kind (" + Twine(Code) + ")");
1383 return std::error_code();
1386 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1387 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1388 return error("Invalid record");
1390 if (!MAttributeGroups.empty())
1391 return error("Invalid multiple blocks");
1393 SmallVector<uint64_t, 64> Record;
1395 // Read all the records.
1397 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1399 switch (Entry.Kind) {
1400 case BitstreamEntry::SubBlock: // Handled for us already.
1401 case BitstreamEntry::Error:
1402 return error("Malformed block");
1403 case BitstreamEntry::EndBlock:
1404 return std::error_code();
1405 case BitstreamEntry::Record:
1406 // The interesting case.
1412 switch (Stream.readRecord(Entry.ID, Record)) {
1413 default: // Default behavior: ignore.
1415 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1416 if (Record.size() < 3)
1417 return error("Invalid record");
1419 uint64_t GrpID = Record[0];
1420 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1423 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1424 if (Record[i] == 0) { // Enum attribute
1425 Attribute::AttrKind Kind;
1426 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1429 B.addAttribute(Kind);
1430 } else if (Record[i] == 1) { // Integer attribute
1431 Attribute::AttrKind Kind;
1432 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1434 if (Kind == Attribute::Alignment)
1435 B.addAlignmentAttr(Record[++i]);
1436 else if (Kind == Attribute::StackAlignment)
1437 B.addStackAlignmentAttr(Record[++i]);
1438 else if (Kind == Attribute::Dereferenceable)
1439 B.addDereferenceableAttr(Record[++i]);
1440 else if (Kind == Attribute::DereferenceableOrNull)
1441 B.addDereferenceableOrNullAttr(Record[++i]);
1442 } else { // String attribute
1443 assert((Record[i] == 3 || Record[i] == 4) &&
1444 "Invalid attribute group entry");
1445 bool HasValue = (Record[i++] == 4);
1446 SmallString<64> KindStr;
1447 SmallString<64> ValStr;
1449 while (Record[i] != 0 && i != e)
1450 KindStr += Record[i++];
1451 assert(Record[i] == 0 && "Kind string not null terminated");
1454 // Has a value associated with it.
1455 ++i; // Skip the '0' that terminates the "kind" string.
1456 while (Record[i] != 0 && i != e)
1457 ValStr += Record[i++];
1458 assert(Record[i] == 0 && "Value string not null terminated");
1461 B.addAttribute(KindStr.str(), ValStr.str());
1465 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1472 std::error_code BitcodeReader::parseTypeTable() {
1473 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1474 return error("Invalid record");
1476 return parseTypeTableBody();
1479 std::error_code BitcodeReader::parseTypeTableBody() {
1480 if (!TypeList.empty())
1481 return error("Invalid multiple blocks");
1483 SmallVector<uint64_t, 64> Record;
1484 unsigned NumRecords = 0;
1486 SmallString<64> TypeName;
1488 // Read all the records for this type table.
1490 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1492 switch (Entry.Kind) {
1493 case BitstreamEntry::SubBlock: // Handled for us already.
1494 case BitstreamEntry::Error:
1495 return error("Malformed block");
1496 case BitstreamEntry::EndBlock:
1497 if (NumRecords != TypeList.size())
1498 return error("Malformed block");
1499 return std::error_code();
1500 case BitstreamEntry::Record:
1501 // The interesting case.
1507 Type *ResultTy = nullptr;
1508 switch (Stream.readRecord(Entry.ID, Record)) {
1510 return error("Invalid value");
1511 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1512 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1513 // type list. This allows us to reserve space.
1514 if (Record.size() < 1)
1515 return error("Invalid record");
1516 TypeList.resize(Record[0]);
1518 case bitc::TYPE_CODE_VOID: // VOID
1519 ResultTy = Type::getVoidTy(Context);
1521 case bitc::TYPE_CODE_HALF: // HALF
1522 ResultTy = Type::getHalfTy(Context);
1524 case bitc::TYPE_CODE_FLOAT: // FLOAT
1525 ResultTy = Type::getFloatTy(Context);
1527 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1528 ResultTy = Type::getDoubleTy(Context);
1530 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1531 ResultTy = Type::getX86_FP80Ty(Context);
1533 case bitc::TYPE_CODE_FP128: // FP128
1534 ResultTy = Type::getFP128Ty(Context);
1536 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1537 ResultTy = Type::getPPC_FP128Ty(Context);
1539 case bitc::TYPE_CODE_LABEL: // LABEL
1540 ResultTy = Type::getLabelTy(Context);
1542 case bitc::TYPE_CODE_METADATA: // METADATA
1543 ResultTy = Type::getMetadataTy(Context);
1545 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1546 ResultTy = Type::getX86_MMXTy(Context);
1548 case bitc::TYPE_CODE_TOKEN: // TOKEN
1549 ResultTy = Type::getTokenTy(Context);
1551 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1552 if (Record.size() < 1)
1553 return error("Invalid record");
1555 uint64_t NumBits = Record[0];
1556 if (NumBits < IntegerType::MIN_INT_BITS ||
1557 NumBits > IntegerType::MAX_INT_BITS)
1558 return error("Bitwidth for integer type out of range");
1559 ResultTy = IntegerType::get(Context, NumBits);
1562 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1563 // [pointee type, address space]
1564 if (Record.size() < 1)
1565 return error("Invalid record");
1566 unsigned AddressSpace = 0;
1567 if (Record.size() == 2)
1568 AddressSpace = Record[1];
1569 ResultTy = getTypeByID(Record[0]);
1571 !PointerType::isValidElementType(ResultTy))
1572 return error("Invalid type");
1573 ResultTy = PointerType::get(ResultTy, AddressSpace);
1576 case bitc::TYPE_CODE_FUNCTION_OLD: {
1577 // FIXME: attrid is dead, remove it in LLVM 4.0
1578 // FUNCTION: [vararg, attrid, retty, paramty x N]
1579 if (Record.size() < 3)
1580 return error("Invalid record");
1581 SmallVector<Type*, 8> ArgTys;
1582 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1583 if (Type *T = getTypeByID(Record[i]))
1584 ArgTys.push_back(T);
1589 ResultTy = getTypeByID(Record[2]);
1590 if (!ResultTy || ArgTys.size() < Record.size()-3)
1591 return error("Invalid type");
1593 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1596 case bitc::TYPE_CODE_FUNCTION: {
1597 // FUNCTION: [vararg, retty, paramty x N]
1598 if (Record.size() < 2)
1599 return error("Invalid record");
1600 SmallVector<Type*, 8> ArgTys;
1601 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1602 if (Type *T = getTypeByID(Record[i])) {
1603 if (!FunctionType::isValidArgumentType(T))
1604 return error("Invalid function argument type");
1605 ArgTys.push_back(T);
1611 ResultTy = getTypeByID(Record[1]);
1612 if (!ResultTy || ArgTys.size() < Record.size()-2)
1613 return error("Invalid type");
1615 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1618 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1619 if (Record.size() < 1)
1620 return error("Invalid record");
1621 SmallVector<Type*, 8> EltTys;
1622 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1623 if (Type *T = getTypeByID(Record[i]))
1624 EltTys.push_back(T);
1628 if (EltTys.size() != Record.size()-1)
1629 return error("Invalid type");
1630 ResultTy = StructType::get(Context, EltTys, Record[0]);
1633 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1634 if (convertToString(Record, 0, TypeName))
1635 return error("Invalid record");
1638 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1639 if (Record.size() < 1)
1640 return error("Invalid record");
1642 if (NumRecords >= TypeList.size())
1643 return error("Invalid TYPE table");
1645 // Check to see if this was forward referenced, if so fill in the temp.
1646 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1648 Res->setName(TypeName);
1649 TypeList[NumRecords] = nullptr;
1650 } else // Otherwise, create a new struct.
1651 Res = createIdentifiedStructType(Context, TypeName);
1654 SmallVector<Type*, 8> EltTys;
1655 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1656 if (Type *T = getTypeByID(Record[i]))
1657 EltTys.push_back(T);
1661 if (EltTys.size() != Record.size()-1)
1662 return error("Invalid record");
1663 Res->setBody(EltTys, Record[0]);
1667 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1668 if (Record.size() != 1)
1669 return error("Invalid record");
1671 if (NumRecords >= TypeList.size())
1672 return error("Invalid TYPE table");
1674 // Check to see if this was forward referenced, if so fill in the temp.
1675 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1677 Res->setName(TypeName);
1678 TypeList[NumRecords] = nullptr;
1679 } else // Otherwise, create a new struct with no body.
1680 Res = createIdentifiedStructType(Context, TypeName);
1685 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1686 if (Record.size() < 2)
1687 return error("Invalid record");
1688 ResultTy = getTypeByID(Record[1]);
1689 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1690 return error("Invalid type");
1691 ResultTy = ArrayType::get(ResultTy, Record[0]);
1693 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1694 if (Record.size() < 2)
1695 return error("Invalid record");
1697 return error("Invalid vector length");
1698 ResultTy = getTypeByID(Record[1]);
1699 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1700 return error("Invalid type");
1701 ResultTy = VectorType::get(ResultTy, Record[0]);
1705 if (NumRecords >= TypeList.size())
1706 return error("Invalid TYPE table");
1707 if (TypeList[NumRecords])
1709 "Invalid TYPE table: Only named structs can be forward referenced");
1710 assert(ResultTy && "Didn't read a type?");
1711 TypeList[NumRecords++] = ResultTy;
1715 std::error_code BitcodeReader::parseOperandBundleTags() {
1716 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1717 return error("Invalid record");
1719 if (!BundleTags.empty())
1720 return error("Invalid multiple blocks");
1722 SmallVector<uint64_t, 64> Record;
1725 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1727 switch (Entry.Kind) {
1728 case BitstreamEntry::SubBlock: // Handled for us already.
1729 case BitstreamEntry::Error:
1730 return error("Malformed block");
1731 case BitstreamEntry::EndBlock:
1732 return std::error_code();
1733 case BitstreamEntry::Record:
1734 // The interesting case.
1738 // Tags are implicitly mapped to integers by their order.
1740 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1741 return error("Invalid record");
1743 // OPERAND_BUNDLE_TAG: [strchr x N]
1744 BundleTags.emplace_back();
1745 if (convertToString(Record, 0, BundleTags.back()))
1746 return error("Invalid record");
1751 /// Associate a value with its name from the given index in the provided record.
1752 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1753 unsigned NameIndex, Triple &TT) {
1754 SmallString<128> ValueName;
1755 if (convertToString(Record, NameIndex, ValueName))
1756 return error("Invalid record");
1757 unsigned ValueID = Record[0];
1758 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1759 return error("Invalid record");
1760 Value *V = ValueList[ValueID];
1762 StringRef NameStr(ValueName.data(), ValueName.size());
1763 if (NameStr.find_first_of(0) != StringRef::npos)
1764 return error("Invalid value name");
1765 V->setName(NameStr);
1766 auto *GO = dyn_cast<GlobalObject>(V);
1768 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1769 if (TT.isOSBinFormatMachO())
1770 GO->setComdat(nullptr);
1772 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1778 /// Parse the value symbol table at either the current parsing location or
1779 /// at the given bit offset if provided.
1780 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1781 uint64_t CurrentBit;
1782 // Pass in the Offset to distinguish between calling for the module-level
1783 // VST (where we want to jump to the VST offset) and the function-level
1784 // VST (where we don't).
1786 // Save the current parsing location so we can jump back at the end
1788 CurrentBit = Stream.GetCurrentBitNo();
1789 Stream.JumpToBit(Offset * 32);
1791 // Do some checking if we are in debug mode.
1792 BitstreamEntry Entry = Stream.advance();
1793 assert(Entry.Kind == BitstreamEntry::SubBlock);
1794 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1796 // In NDEBUG mode ignore the output so we don't get an unused variable
1802 // Compute the delta between the bitcode indices in the VST (the word offset
1803 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1804 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1805 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1806 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1807 // just before entering the VST subblock because: 1) the EnterSubBlock
1808 // changes the AbbrevID width; 2) the VST block is nested within the same
1809 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1810 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1811 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1812 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1813 unsigned FuncBitcodeOffsetDelta =
1814 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1816 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1817 return error("Invalid record");
1819 SmallVector<uint64_t, 64> Record;
1821 Triple TT(TheModule->getTargetTriple());
1823 // Read all the records for this value table.
1824 SmallString<128> ValueName;
1826 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1828 switch (Entry.Kind) {
1829 case BitstreamEntry::SubBlock: // Handled for us already.
1830 case BitstreamEntry::Error:
1831 return error("Malformed block");
1832 case BitstreamEntry::EndBlock:
1834 Stream.JumpToBit(CurrentBit);
1835 return std::error_code();
1836 case BitstreamEntry::Record:
1837 // The interesting case.
1843 switch (Stream.readRecord(Entry.ID, Record)) {
1844 default: // Default behavior: unknown type.
1846 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1847 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1848 if (std::error_code EC = ValOrErr.getError())
1853 case bitc::VST_CODE_FNENTRY: {
1854 // VST_FNENTRY: [valueid, offset, namechar x N]
1855 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1856 if (std::error_code EC = ValOrErr.getError())
1858 Value *V = ValOrErr.get();
1860 auto *GO = dyn_cast<GlobalObject>(V);
1862 // If this is an alias, need to get the actual Function object
1863 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1864 auto *GA = dyn_cast<GlobalAlias>(V);
1866 GO = GA->getBaseObject();
1870 uint64_t FuncWordOffset = Record[1];
1871 Function *F = dyn_cast<Function>(GO);
1873 uint64_t FuncBitOffset = FuncWordOffset * 32;
1874 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1875 // Set the LastFunctionBlockBit to point to the last function block.
1876 // Later when parsing is resumed after function materialization,
1877 // we can simply skip that last function block.
1878 if (FuncBitOffset > LastFunctionBlockBit)
1879 LastFunctionBlockBit = FuncBitOffset;
1882 case bitc::VST_CODE_BBENTRY: {
1883 if (convertToString(Record, 1, ValueName))
1884 return error("Invalid record");
1885 BasicBlock *BB = getBasicBlock(Record[0]);
1887 return error("Invalid record");
1889 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1897 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1899 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1900 if (Record.size() < 2)
1901 return error("Invalid record");
1903 unsigned Kind = Record[0];
1904 SmallString<8> Name(Record.begin() + 1, Record.end());
1906 unsigned NewKind = TheModule->getMDKindID(Name.str());
1907 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1908 return error("Conflicting METADATA_KIND records");
1909 return std::error_code();
1912 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1914 std::error_code BitcodeReader::parseMetadata() {
1915 IsMetadataMaterialized = true;
1916 unsigned NextMDValueNo = MDValueList.size();
1918 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1919 return error("Invalid record");
1921 SmallVector<uint64_t, 64> Record;
1924 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1925 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1927 return getMD(ID - 1);
1930 auto getMDString = [&](unsigned ID) -> MDString *{
1931 // This requires that the ID is not really a forward reference. In
1932 // particular, the MDString must already have been resolved.
1933 return cast_or_null<MDString>(getMDOrNull(ID));
1936 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1937 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1939 // Read all the records.
1941 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1943 switch (Entry.Kind) {
1944 case BitstreamEntry::SubBlock: // Handled for us already.
1945 case BitstreamEntry::Error:
1946 return error("Malformed block");
1947 case BitstreamEntry::EndBlock:
1948 MDValueList.tryToResolveCycles();
1949 return std::error_code();
1950 case BitstreamEntry::Record:
1951 // The interesting case.
1957 unsigned Code = Stream.readRecord(Entry.ID, Record);
1958 bool IsDistinct = false;
1960 default: // Default behavior: ignore.
1962 case bitc::METADATA_NAME: {
1963 // Read name of the named metadata.
1964 SmallString<8> Name(Record.begin(), Record.end());
1966 Code = Stream.ReadCode();
1968 unsigned NextBitCode = Stream.readRecord(Code, Record);
1969 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1970 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1972 // Read named metadata elements.
1973 unsigned Size = Record.size();
1974 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1975 for (unsigned i = 0; i != Size; ++i) {
1976 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1978 return error("Invalid record");
1979 NMD->addOperand(MD);
1983 case bitc::METADATA_OLD_FN_NODE: {
1984 // FIXME: Remove in 4.0.
1985 // This is a LocalAsMetadata record, the only type of function-local
1987 if (Record.size() % 2 == 1)
1988 return error("Invalid record");
1990 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1991 // to be legal, but there's no upgrade path.
1992 auto dropRecord = [&] {
1993 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1995 if (Record.size() != 2) {
2000 Type *Ty = getTypeByID(Record[0]);
2001 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2006 MDValueList.assignValue(
2007 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2011 case bitc::METADATA_OLD_NODE: {
2012 // FIXME: Remove in 4.0.
2013 if (Record.size() % 2 == 1)
2014 return error("Invalid record");
2016 unsigned Size = Record.size();
2017 SmallVector<Metadata *, 8> Elts;
2018 for (unsigned i = 0; i != Size; i += 2) {
2019 Type *Ty = getTypeByID(Record[i]);
2021 return error("Invalid record");
2022 if (Ty->isMetadataTy())
2023 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
2024 else if (!Ty->isVoidTy()) {
2026 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2027 assert(isa<ConstantAsMetadata>(MD) &&
2028 "Expected non-function-local metadata");
2031 Elts.push_back(nullptr);
2033 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2036 case bitc::METADATA_VALUE: {
2037 if (Record.size() != 2)
2038 return error("Invalid record");
2040 Type *Ty = getTypeByID(Record[0]);
2041 if (Ty->isMetadataTy() || Ty->isVoidTy())
2042 return error("Invalid record");
2044 MDValueList.assignValue(
2045 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2049 case bitc::METADATA_DISTINCT_NODE:
2052 case bitc::METADATA_NODE: {
2053 SmallVector<Metadata *, 8> Elts;
2054 Elts.reserve(Record.size());
2055 for (unsigned ID : Record)
2056 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2057 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2058 : MDNode::get(Context, Elts),
2062 case bitc::METADATA_LOCATION: {
2063 if (Record.size() != 5)
2064 return error("Invalid record");
2066 unsigned Line = Record[1];
2067 unsigned Column = Record[2];
2068 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2069 Metadata *InlinedAt =
2070 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2071 MDValueList.assignValue(
2072 GET_OR_DISTINCT(DILocation, Record[0],
2073 (Context, Line, Column, Scope, InlinedAt)),
2077 case bitc::METADATA_GENERIC_DEBUG: {
2078 if (Record.size() < 4)
2079 return error("Invalid record");
2081 unsigned Tag = Record[1];
2082 unsigned Version = Record[2];
2084 if (Tag >= 1u << 16 || Version != 0)
2085 return error("Invalid record");
2087 auto *Header = getMDString(Record[3]);
2088 SmallVector<Metadata *, 8> DwarfOps;
2089 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2090 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2092 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2093 (Context, Tag, Header, DwarfOps)),
2097 case bitc::METADATA_SUBRANGE: {
2098 if (Record.size() != 3)
2099 return error("Invalid record");
2101 MDValueList.assignValue(
2102 GET_OR_DISTINCT(DISubrange, Record[0],
2103 (Context, Record[1], unrotateSign(Record[2]))),
2107 case bitc::METADATA_ENUMERATOR: {
2108 if (Record.size() != 3)
2109 return error("Invalid record");
2111 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2112 (Context, unrotateSign(Record[1]),
2113 getMDString(Record[2]))),
2117 case bitc::METADATA_BASIC_TYPE: {
2118 if (Record.size() != 6)
2119 return error("Invalid record");
2121 MDValueList.assignValue(
2122 GET_OR_DISTINCT(DIBasicType, Record[0],
2123 (Context, Record[1], getMDString(Record[2]),
2124 Record[3], Record[4], Record[5])),
2128 case bitc::METADATA_DERIVED_TYPE: {
2129 if (Record.size() != 12)
2130 return error("Invalid record");
2132 MDValueList.assignValue(
2133 GET_OR_DISTINCT(DIDerivedType, Record[0],
2134 (Context, Record[1], getMDString(Record[2]),
2135 getMDOrNull(Record[3]), Record[4],
2136 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2137 Record[7], Record[8], Record[9], Record[10],
2138 getMDOrNull(Record[11]))),
2142 case bitc::METADATA_COMPOSITE_TYPE: {
2143 if (Record.size() != 16)
2144 return error("Invalid record");
2146 MDValueList.assignValue(
2147 GET_OR_DISTINCT(DICompositeType, Record[0],
2148 (Context, Record[1], getMDString(Record[2]),
2149 getMDOrNull(Record[3]), Record[4],
2150 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2151 Record[7], Record[8], Record[9], Record[10],
2152 getMDOrNull(Record[11]), Record[12],
2153 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2154 getMDString(Record[15]))),
2158 case bitc::METADATA_SUBROUTINE_TYPE: {
2159 if (Record.size() != 3)
2160 return error("Invalid record");
2162 MDValueList.assignValue(
2163 GET_OR_DISTINCT(DISubroutineType, Record[0],
2164 (Context, Record[1], getMDOrNull(Record[2]))),
2169 case bitc::METADATA_MODULE: {
2170 if (Record.size() != 6)
2171 return error("Invalid record");
2173 MDValueList.assignValue(
2174 GET_OR_DISTINCT(DIModule, Record[0],
2175 (Context, getMDOrNull(Record[1]),
2176 getMDString(Record[2]), getMDString(Record[3]),
2177 getMDString(Record[4]), getMDString(Record[5]))),
2182 case bitc::METADATA_FILE: {
2183 if (Record.size() != 3)
2184 return error("Invalid record");
2186 MDValueList.assignValue(
2187 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2188 getMDString(Record[2]))),
2192 case bitc::METADATA_COMPILE_UNIT: {
2193 if (Record.size() < 14 || Record.size() > 15)
2194 return error("Invalid record");
2196 // Ignore Record[1], which indicates whether this compile unit is
2197 // distinct. It's always distinct.
2198 MDValueList.assignValue(
2199 DICompileUnit::getDistinct(
2200 Context, Record[1], getMDOrNull(Record[2]),
2201 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2202 Record[6], getMDString(Record[7]), Record[8],
2203 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2204 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2205 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2209 case bitc::METADATA_SUBPROGRAM: {
2210 if (Record.size() != 18 && Record.size() != 19)
2211 return error("Invalid record");
2213 bool HasFn = Record.size() == 19;
2214 DISubprogram *SP = GET_OR_DISTINCT(
2216 Record[0] || Record[8], // All definitions should be distinct.
2217 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2218 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2219 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2220 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2221 Record[14], getMDOrNull(Record[15 + HasFn]),
2222 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2223 MDValueList.assignValue(SP, NextMDValueNo++);
2225 // Upgrade sp->function mapping to function->sp mapping.
2226 if (HasFn && Record[15]) {
2227 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2228 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2229 if (F->isMaterializable())
2230 // Defer until materialized; unmaterialized functions may not have
2232 FunctionsWithSPs[F] = SP;
2233 else if (!F->empty())
2234 F->setSubprogram(SP);
2239 case bitc::METADATA_LEXICAL_BLOCK: {
2240 if (Record.size() != 5)
2241 return error("Invalid record");
2243 MDValueList.assignValue(
2244 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2245 (Context, getMDOrNull(Record[1]),
2246 getMDOrNull(Record[2]), Record[3], Record[4])),
2250 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2251 if (Record.size() != 4)
2252 return error("Invalid record");
2254 MDValueList.assignValue(
2255 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2256 (Context, getMDOrNull(Record[1]),
2257 getMDOrNull(Record[2]), Record[3])),
2261 case bitc::METADATA_NAMESPACE: {
2262 if (Record.size() != 5)
2263 return error("Invalid record");
2265 MDValueList.assignValue(
2266 GET_OR_DISTINCT(DINamespace, Record[0],
2267 (Context, getMDOrNull(Record[1]),
2268 getMDOrNull(Record[2]), getMDString(Record[3]),
2273 case bitc::METADATA_TEMPLATE_TYPE: {
2274 if (Record.size() != 3)
2275 return error("Invalid record");
2277 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2279 (Context, getMDString(Record[1]),
2280 getMDOrNull(Record[2]))),
2284 case bitc::METADATA_TEMPLATE_VALUE: {
2285 if (Record.size() != 5)
2286 return error("Invalid record");
2288 MDValueList.assignValue(
2289 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2290 (Context, Record[1], getMDString(Record[2]),
2291 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2295 case bitc::METADATA_GLOBAL_VAR: {
2296 if (Record.size() != 11)
2297 return error("Invalid record");
2299 MDValueList.assignValue(
2300 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2301 (Context, getMDOrNull(Record[1]),
2302 getMDString(Record[2]), getMDString(Record[3]),
2303 getMDOrNull(Record[4]), Record[5],
2304 getMDOrNull(Record[6]), Record[7], Record[8],
2305 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2309 case bitc::METADATA_LOCAL_VAR: {
2310 // 10th field is for the obseleted 'inlinedAt:' field.
2311 if (Record.size() < 8 || Record.size() > 10)
2312 return error("Invalid record");
2314 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2315 // DW_TAG_arg_variable.
2316 bool HasTag = Record.size() > 8;
2317 MDValueList.assignValue(
2318 GET_OR_DISTINCT(DILocalVariable, Record[0],
2319 (Context, getMDOrNull(Record[1 + HasTag]),
2320 getMDString(Record[2 + HasTag]),
2321 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2322 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2323 Record[7 + HasTag])),
2327 case bitc::METADATA_EXPRESSION: {
2328 if (Record.size() < 1)
2329 return error("Invalid record");
2331 MDValueList.assignValue(
2332 GET_OR_DISTINCT(DIExpression, Record[0],
2333 (Context, makeArrayRef(Record).slice(1))),
2337 case bitc::METADATA_OBJC_PROPERTY: {
2338 if (Record.size() != 8)
2339 return error("Invalid record");
2341 MDValueList.assignValue(
2342 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2343 (Context, getMDString(Record[1]),
2344 getMDOrNull(Record[2]), Record[3],
2345 getMDString(Record[4]), getMDString(Record[5]),
2346 Record[6], getMDOrNull(Record[7]))),
2350 case bitc::METADATA_IMPORTED_ENTITY: {
2351 if (Record.size() != 6)
2352 return error("Invalid record");
2354 MDValueList.assignValue(
2355 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2356 (Context, Record[1], getMDOrNull(Record[2]),
2357 getMDOrNull(Record[3]), Record[4],
2358 getMDString(Record[5]))),
2362 case bitc::METADATA_STRING: {
2363 std::string String(Record.begin(), Record.end());
2364 llvm::UpgradeMDStringConstant(String);
2365 Metadata *MD = MDString::get(Context, String);
2366 MDValueList.assignValue(MD, NextMDValueNo++);
2369 case bitc::METADATA_KIND: {
2370 // Support older bitcode files that had METADATA_KIND records in a
2371 // block with METADATA_BLOCK_ID.
2372 if (std::error_code EC = parseMetadataKindRecord(Record))
2378 #undef GET_OR_DISTINCT
2381 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2382 std::error_code BitcodeReader::parseMetadataKinds() {
2383 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2384 return error("Invalid record");
2386 SmallVector<uint64_t, 64> Record;
2388 // Read all the records.
2390 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2392 switch (Entry.Kind) {
2393 case BitstreamEntry::SubBlock: // Handled for us already.
2394 case BitstreamEntry::Error:
2395 return error("Malformed block");
2396 case BitstreamEntry::EndBlock:
2397 return std::error_code();
2398 case BitstreamEntry::Record:
2399 // The interesting case.
2405 unsigned Code = Stream.readRecord(Entry.ID, Record);
2407 default: // Default behavior: ignore.
2409 case bitc::METADATA_KIND: {
2410 if (std::error_code EC = parseMetadataKindRecord(Record))
2418 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2420 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2425 // There is no such thing as -0 with integers. "-0" really means MININT.
2429 /// Resolve all of the initializers for global values and aliases that we can.
2430 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2431 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2432 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2433 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2434 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2435 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2437 GlobalInitWorklist.swap(GlobalInits);
2438 AliasInitWorklist.swap(AliasInits);
2439 FunctionPrefixWorklist.swap(FunctionPrefixes);
2440 FunctionPrologueWorklist.swap(FunctionPrologues);
2441 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2443 while (!GlobalInitWorklist.empty()) {
2444 unsigned ValID = GlobalInitWorklist.back().second;
2445 if (ValID >= ValueList.size()) {
2446 // Not ready to resolve this yet, it requires something later in the file.
2447 GlobalInits.push_back(GlobalInitWorklist.back());
2449 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2450 GlobalInitWorklist.back().first->setInitializer(C);
2452 return error("Expected a constant");
2454 GlobalInitWorklist.pop_back();
2457 while (!AliasInitWorklist.empty()) {
2458 unsigned ValID = AliasInitWorklist.back().second;
2459 if (ValID >= ValueList.size()) {
2460 AliasInits.push_back(AliasInitWorklist.back());
2462 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2464 return error("Expected a constant");
2465 GlobalAlias *Alias = AliasInitWorklist.back().first;
2466 if (C->getType() != Alias->getType())
2467 return error("Alias and aliasee types don't match");
2468 Alias->setAliasee(C);
2470 AliasInitWorklist.pop_back();
2473 while (!FunctionPrefixWorklist.empty()) {
2474 unsigned ValID = FunctionPrefixWorklist.back().second;
2475 if (ValID >= ValueList.size()) {
2476 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2478 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2479 FunctionPrefixWorklist.back().first->setPrefixData(C);
2481 return error("Expected a constant");
2483 FunctionPrefixWorklist.pop_back();
2486 while (!FunctionPrologueWorklist.empty()) {
2487 unsigned ValID = FunctionPrologueWorklist.back().second;
2488 if (ValID >= ValueList.size()) {
2489 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2491 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2492 FunctionPrologueWorklist.back().first->setPrologueData(C);
2494 return error("Expected a constant");
2496 FunctionPrologueWorklist.pop_back();
2499 while (!FunctionPersonalityFnWorklist.empty()) {
2500 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2501 if (ValID >= ValueList.size()) {
2502 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2504 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2505 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2507 return error("Expected a constant");
2509 FunctionPersonalityFnWorklist.pop_back();
2512 return std::error_code();
2515 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2516 SmallVector<uint64_t, 8> Words(Vals.size());
2517 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2518 BitcodeReader::decodeSignRotatedValue);
2520 return APInt(TypeBits, Words);
2523 std::error_code BitcodeReader::parseConstants() {
2524 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2525 return error("Invalid record");
2527 SmallVector<uint64_t, 64> Record;
2529 // Read all the records for this value table.
2530 Type *CurTy = Type::getInt32Ty(Context);
2531 unsigned NextCstNo = ValueList.size();
2533 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2535 switch (Entry.Kind) {
2536 case BitstreamEntry::SubBlock: // Handled for us already.
2537 case BitstreamEntry::Error:
2538 return error("Malformed block");
2539 case BitstreamEntry::EndBlock:
2540 if (NextCstNo != ValueList.size())
2541 return error("Invalid ronstant reference");
2543 // Once all the constants have been read, go through and resolve forward
2545 ValueList.resolveConstantForwardRefs();
2546 return std::error_code();
2547 case BitstreamEntry::Record:
2548 // The interesting case.
2555 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2557 default: // Default behavior: unknown constant
2558 case bitc::CST_CODE_UNDEF: // UNDEF
2559 V = UndefValue::get(CurTy);
2561 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2563 return error("Invalid record");
2564 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2565 return error("Invalid record");
2566 CurTy = TypeList[Record[0]];
2567 continue; // Skip the ValueList manipulation.
2568 case bitc::CST_CODE_NULL: // NULL
2569 V = Constant::getNullValue(CurTy);
2571 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2572 if (!CurTy->isIntegerTy() || Record.empty())
2573 return error("Invalid record");
2574 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2576 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2577 if (!CurTy->isIntegerTy() || Record.empty())
2578 return error("Invalid record");
2581 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2582 V = ConstantInt::get(Context, VInt);
2586 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2588 return error("Invalid record");
2589 if (CurTy->isHalfTy())
2590 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2591 APInt(16, (uint16_t)Record[0])));
2592 else if (CurTy->isFloatTy())
2593 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2594 APInt(32, (uint32_t)Record[0])));
2595 else if (CurTy->isDoubleTy())
2596 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2597 APInt(64, Record[0])));
2598 else if (CurTy->isX86_FP80Ty()) {
2599 // Bits are not stored the same way as a normal i80 APInt, compensate.
2600 uint64_t Rearrange[2];
2601 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2602 Rearrange[1] = Record[0] >> 48;
2603 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2604 APInt(80, Rearrange)));
2605 } else if (CurTy->isFP128Ty())
2606 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2607 APInt(128, Record)));
2608 else if (CurTy->isPPC_FP128Ty())
2609 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2610 APInt(128, Record)));
2612 V = UndefValue::get(CurTy);
2616 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2618 return error("Invalid record");
2620 unsigned Size = Record.size();
2621 SmallVector<Constant*, 16> Elts;
2623 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2624 for (unsigned i = 0; i != Size; ++i)
2625 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2626 STy->getElementType(i)));
2627 V = ConstantStruct::get(STy, Elts);
2628 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2629 Type *EltTy = ATy->getElementType();
2630 for (unsigned i = 0; i != Size; ++i)
2631 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2632 V = ConstantArray::get(ATy, Elts);
2633 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2634 Type *EltTy = VTy->getElementType();
2635 for (unsigned i = 0; i != Size; ++i)
2636 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2637 V = ConstantVector::get(Elts);
2639 V = UndefValue::get(CurTy);
2643 case bitc::CST_CODE_STRING: // STRING: [values]
2644 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2646 return error("Invalid record");
2648 SmallString<16> Elts(Record.begin(), Record.end());
2649 V = ConstantDataArray::getString(Context, Elts,
2650 BitCode == bitc::CST_CODE_CSTRING);
2653 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2655 return error("Invalid record");
2657 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2658 unsigned Size = Record.size();
2660 if (EltTy->isIntegerTy(8)) {
2661 SmallVector<uint8_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(16)) {
2667 SmallVector<uint16_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(32)) {
2673 SmallVector<uint32_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->isIntegerTy(64)) {
2679 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2680 if (isa<VectorType>(CurTy))
2681 V = ConstantDataVector::get(Context, Elts);
2683 V = ConstantDataArray::get(Context, Elts);
2684 } else if (EltTy->isFloatTy()) {
2685 SmallVector<float, 16> Elts(Size);
2686 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2687 if (isa<VectorType>(CurTy))
2688 V = ConstantDataVector::get(Context, Elts);
2690 V = ConstantDataArray::get(Context, Elts);
2691 } else if (EltTy->isDoubleTy()) {
2692 SmallVector<double, 16> Elts(Size);
2693 std::transform(Record.begin(), Record.end(), Elts.begin(),
2695 if (isa<VectorType>(CurTy))
2696 V = ConstantDataVector::get(Context, Elts);
2698 V = ConstantDataArray::get(Context, Elts);
2700 return error("Invalid type for value");
2705 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2706 if (Record.size() < 3)
2707 return error("Invalid record");
2708 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2710 V = UndefValue::get(CurTy); // Unknown binop.
2712 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2713 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2715 if (Record.size() >= 4) {
2716 if (Opc == Instruction::Add ||
2717 Opc == Instruction::Sub ||
2718 Opc == Instruction::Mul ||
2719 Opc == Instruction::Shl) {
2720 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2721 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2722 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2723 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2724 } else if (Opc == Instruction::SDiv ||
2725 Opc == Instruction::UDiv ||
2726 Opc == Instruction::LShr ||
2727 Opc == Instruction::AShr) {
2728 if (Record[3] & (1 << bitc::PEO_EXACT))
2729 Flags |= SDivOperator::IsExact;
2732 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2736 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2737 if (Record.size() < 3)
2738 return error("Invalid record");
2739 int Opc = getDecodedCastOpcode(Record[0]);
2741 V = UndefValue::get(CurTy); // Unknown cast.
2743 Type *OpTy = getTypeByID(Record[1]);
2745 return error("Invalid record");
2746 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2747 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2748 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2752 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2753 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2755 Type *PointeeType = nullptr;
2756 if (Record.size() % 2)
2757 PointeeType = getTypeByID(Record[OpNum++]);
2758 SmallVector<Constant*, 16> Elts;
2759 while (OpNum != Record.size()) {
2760 Type *ElTy = getTypeByID(Record[OpNum++]);
2762 return error("Invalid record");
2763 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2768 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2770 return error("Explicit gep operator type does not match pointee type "
2771 "of pointer operand");
2773 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2774 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2776 bitc::CST_CODE_CE_INBOUNDS_GEP);
2779 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2780 if (Record.size() < 3)
2781 return error("Invalid record");
2783 Type *SelectorTy = Type::getInt1Ty(Context);
2785 // The selector might be an i1 or an <n x i1>
2786 // Get the type from the ValueList before getting a forward ref.
2787 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2788 if (Value *V = ValueList[Record[0]])
2789 if (SelectorTy != V->getType())
2790 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2792 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2794 ValueList.getConstantFwdRef(Record[1],CurTy),
2795 ValueList.getConstantFwdRef(Record[2],CurTy));
2798 case bitc::CST_CODE_CE_EXTRACTELT
2799 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2800 if (Record.size() < 3)
2801 return error("Invalid record");
2803 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2805 return error("Invalid record");
2806 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2807 Constant *Op1 = nullptr;
2808 if (Record.size() == 4) {
2809 Type *IdxTy = getTypeByID(Record[2]);
2811 return error("Invalid record");
2812 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2813 } else // TODO: Remove with llvm 4.0
2814 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2816 return error("Invalid record");
2817 V = ConstantExpr::getExtractElement(Op0, Op1);
2820 case bitc::CST_CODE_CE_INSERTELT
2821 : { // CE_INSERTELT: [opval, opval, opty, opval]
2822 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2823 if (Record.size() < 3 || !OpTy)
2824 return error("Invalid record");
2825 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2826 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2827 OpTy->getElementType());
2828 Constant *Op2 = nullptr;
2829 if (Record.size() == 4) {
2830 Type *IdxTy = getTypeByID(Record[2]);
2832 return error("Invalid record");
2833 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2834 } else // TODO: Remove with llvm 4.0
2835 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2837 return error("Invalid record");
2838 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2841 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2842 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2843 if (Record.size() < 3 || !OpTy)
2844 return error("Invalid record");
2845 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2846 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2847 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2848 OpTy->getNumElements());
2849 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2850 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2853 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2854 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2856 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2857 if (Record.size() < 4 || !RTy || !OpTy)
2858 return error("Invalid record");
2859 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2860 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2861 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2862 RTy->getNumElements());
2863 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2864 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2867 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2868 if (Record.size() < 4)
2869 return error("Invalid record");
2870 Type *OpTy = getTypeByID(Record[0]);
2872 return error("Invalid record");
2873 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2874 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2876 if (OpTy->isFPOrFPVectorTy())
2877 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2879 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2882 // This maintains backward compatibility, pre-asm dialect keywords.
2883 // FIXME: Remove with the 4.0 release.
2884 case bitc::CST_CODE_INLINEASM_OLD: {
2885 if (Record.size() < 2)
2886 return error("Invalid record");
2887 std::string AsmStr, ConstrStr;
2888 bool HasSideEffects = Record[0] & 1;
2889 bool IsAlignStack = Record[0] >> 1;
2890 unsigned AsmStrSize = Record[1];
2891 if (2+AsmStrSize >= Record.size())
2892 return error("Invalid record");
2893 unsigned ConstStrSize = Record[2+AsmStrSize];
2894 if (3+AsmStrSize+ConstStrSize > Record.size())
2895 return error("Invalid record");
2897 for (unsigned i = 0; i != AsmStrSize; ++i)
2898 AsmStr += (char)Record[2+i];
2899 for (unsigned i = 0; i != ConstStrSize; ++i)
2900 ConstrStr += (char)Record[3+AsmStrSize+i];
2901 PointerType *PTy = cast<PointerType>(CurTy);
2902 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2903 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2906 // This version adds support for the asm dialect keywords (e.g.,
2908 case bitc::CST_CODE_INLINEASM: {
2909 if (Record.size() < 2)
2910 return error("Invalid record");
2911 std::string AsmStr, ConstrStr;
2912 bool HasSideEffects = Record[0] & 1;
2913 bool IsAlignStack = (Record[0] >> 1) & 1;
2914 unsigned AsmDialect = Record[0] >> 2;
2915 unsigned AsmStrSize = Record[1];
2916 if (2+AsmStrSize >= Record.size())
2917 return error("Invalid record");
2918 unsigned ConstStrSize = Record[2+AsmStrSize];
2919 if (3+AsmStrSize+ConstStrSize > Record.size())
2920 return error("Invalid record");
2922 for (unsigned i = 0; i != AsmStrSize; ++i)
2923 AsmStr += (char)Record[2+i];
2924 for (unsigned i = 0; i != ConstStrSize; ++i)
2925 ConstrStr += (char)Record[3+AsmStrSize+i];
2926 PointerType *PTy = cast<PointerType>(CurTy);
2927 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2928 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2929 InlineAsm::AsmDialect(AsmDialect));
2932 case bitc::CST_CODE_BLOCKADDRESS:{
2933 if (Record.size() < 3)
2934 return error("Invalid record");
2935 Type *FnTy = getTypeByID(Record[0]);
2937 return error("Invalid record");
2939 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2941 return error("Invalid record");
2943 // Don't let Fn get dematerialized.
2944 BlockAddressesTaken.insert(Fn);
2946 // If the function is already parsed we can insert the block address right
2949 unsigned BBID = Record[2];
2951 // Invalid reference to entry block.
2952 return error("Invalid ID");
2954 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2955 for (size_t I = 0, E = BBID; I != E; ++I) {
2957 return error("Invalid ID");
2962 // Otherwise insert a placeholder and remember it so it can be inserted
2963 // when the function is parsed.
2964 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2966 BasicBlockFwdRefQueue.push_back(Fn);
2967 if (FwdBBs.size() < BBID + 1)
2968 FwdBBs.resize(BBID + 1);
2970 FwdBBs[BBID] = BasicBlock::Create(Context);
2973 V = BlockAddress::get(Fn, BB);
2978 if (ValueList.assignValue(V, NextCstNo))
2979 return error("Invalid forward reference");
2984 std::error_code BitcodeReader::parseUseLists() {
2985 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2986 return error("Invalid record");
2988 // Read all the records.
2989 SmallVector<uint64_t, 64> Record;
2991 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2993 switch (Entry.Kind) {
2994 case BitstreamEntry::SubBlock: // Handled for us already.
2995 case BitstreamEntry::Error:
2996 return error("Malformed block");
2997 case BitstreamEntry::EndBlock:
2998 return std::error_code();
2999 case BitstreamEntry::Record:
3000 // The interesting case.
3004 // Read a use list record.
3007 switch (Stream.readRecord(Entry.ID, Record)) {
3008 default: // Default behavior: unknown type.
3010 case bitc::USELIST_CODE_BB:
3013 case bitc::USELIST_CODE_DEFAULT: {
3014 unsigned RecordLength = Record.size();
3015 if (RecordLength < 3)
3016 // Records should have at least an ID and two indexes.
3017 return error("Invalid record");
3018 unsigned ID = Record.back();
3023 assert(ID < FunctionBBs.size() && "Basic block not found");
3024 V = FunctionBBs[ID];
3027 unsigned NumUses = 0;
3028 SmallDenseMap<const Use *, unsigned, 16> Order;
3029 for (const Use &U : V->uses()) {
3030 if (++NumUses > Record.size())
3032 Order[&U] = Record[NumUses - 1];
3034 if (Order.size() != Record.size() || NumUses > Record.size())
3035 // Mismatches can happen if the functions are being materialized lazily
3036 // (out-of-order), or a value has been upgraded.
3039 V->sortUseList([&](const Use &L, const Use &R) {
3040 return Order.lookup(&L) < Order.lookup(&R);
3048 /// When we see the block for metadata, remember where it is and then skip it.
3049 /// This lets us lazily deserialize the metadata.
3050 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3051 // Save the current stream state.
3052 uint64_t CurBit = Stream.GetCurrentBitNo();
3053 DeferredMetadataInfo.push_back(CurBit);
3055 // Skip over the block for now.
3056 if (Stream.SkipBlock())
3057 return error("Invalid record");
3058 return std::error_code();
3061 std::error_code BitcodeReader::materializeMetadata() {
3062 for (uint64_t BitPos : DeferredMetadataInfo) {
3063 // Move the bit stream to the saved position.
3064 Stream.JumpToBit(BitPos);
3065 if (std::error_code EC = parseMetadata())
3068 DeferredMetadataInfo.clear();
3069 return std::error_code();
3072 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3074 /// When we see the block for a function body, remember where it is and then
3075 /// skip it. This lets us lazily deserialize the functions.
3076 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3077 // Get the function we are talking about.
3078 if (FunctionsWithBodies.empty())
3079 return error("Insufficient function protos");
3081 Function *Fn = FunctionsWithBodies.back();
3082 FunctionsWithBodies.pop_back();
3084 // Save the current stream state.
3085 uint64_t CurBit = Stream.GetCurrentBitNo();
3087 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3088 "Mismatch between VST and scanned function offsets");
3089 DeferredFunctionInfo[Fn] = CurBit;
3091 // Skip over the function block for now.
3092 if (Stream.SkipBlock())
3093 return error("Invalid record");
3094 return std::error_code();
3097 std::error_code BitcodeReader::globalCleanup() {
3098 // Patch the initializers for globals and aliases up.
3099 resolveGlobalAndAliasInits();
3100 if (!GlobalInits.empty() || !AliasInits.empty())
3101 return error("Malformed global initializer set");
3103 // Look for intrinsic functions which need to be upgraded at some point
3104 for (Function &F : *TheModule) {
3106 if (UpgradeIntrinsicFunction(&F, NewFn))
3107 UpgradedIntrinsics[&F] = NewFn;
3110 // Look for global variables which need to be renamed.
3111 for (GlobalVariable &GV : TheModule->globals())
3112 UpgradeGlobalVariable(&GV);
3114 // Force deallocation of memory for these vectors to favor the client that
3115 // want lazy deserialization.
3116 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3117 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3118 return std::error_code();
3121 /// Support for lazy parsing of function bodies. This is required if we
3122 /// either have an old bitcode file without a VST forward declaration record,
3123 /// or if we have an anonymous function being materialized, since anonymous
3124 /// functions do not have a name and are therefore not in the VST.
3125 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3126 Stream.JumpToBit(NextUnreadBit);
3128 if (Stream.AtEndOfStream())
3129 return error("Could not find function in stream");
3131 if (!SeenFirstFunctionBody)
3132 return error("Trying to materialize functions before seeing function blocks");
3134 // An old bitcode file with the symbol table at the end would have
3135 // finished the parse greedily.
3136 assert(SeenValueSymbolTable);
3138 SmallVector<uint64_t, 64> Record;
3141 BitstreamEntry Entry = Stream.advance();
3142 switch (Entry.Kind) {
3144 return error("Expect SubBlock");
3145 case BitstreamEntry::SubBlock:
3148 return error("Expect function block");
3149 case bitc::FUNCTION_BLOCK_ID:
3150 if (std::error_code EC = rememberAndSkipFunctionBody())
3152 NextUnreadBit = Stream.GetCurrentBitNo();
3153 return std::error_code();
3159 std::error_code BitcodeReader::parseBitcodeVersion() {
3160 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3161 return error("Invalid record");
3163 // Read all the records.
3164 SmallVector<uint64_t, 64> Record;
3166 BitstreamEntry Entry = Stream.advance();
3168 switch (Entry.Kind) {
3170 case BitstreamEntry::Error:
3171 return error("Malformed block");
3172 case BitstreamEntry::EndBlock:
3173 return std::error_code();
3174 case BitstreamEntry::Record:
3175 // The interesting case.
3181 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3183 default: // Default behavior: reject
3184 return error("Invalid value");
3185 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3187 convertToString(Record, 0, ProducerIdentification);
3190 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3191 unsigned epoch = (unsigned)Record[0];
3192 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3194 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3195 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3202 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3203 bool ShouldLazyLoadMetadata) {
3205 Stream.JumpToBit(ResumeBit);
3206 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3207 return error("Invalid record");
3209 SmallVector<uint64_t, 64> Record;
3210 std::vector<std::string> SectionTable;
3211 std::vector<std::string> GCTable;
3213 // Read all the records for this module.
3215 BitstreamEntry Entry = Stream.advance();
3217 switch (Entry.Kind) {
3218 case BitstreamEntry::Error:
3219 return error("Malformed block");
3220 case BitstreamEntry::EndBlock:
3221 return globalCleanup();
3223 case BitstreamEntry::SubBlock:
3225 default: // Skip unknown content.
3226 if (Stream.SkipBlock())
3227 return error("Invalid record");
3229 case bitc::BLOCKINFO_BLOCK_ID:
3230 if (Stream.ReadBlockInfoBlock())
3231 return error("Malformed block");
3233 case bitc::PARAMATTR_BLOCK_ID:
3234 if (std::error_code EC = parseAttributeBlock())
3237 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3238 if (std::error_code EC = parseAttributeGroupBlock())
3241 case bitc::TYPE_BLOCK_ID_NEW:
3242 if (std::error_code EC = parseTypeTable())
3245 case bitc::VALUE_SYMTAB_BLOCK_ID:
3246 if (!SeenValueSymbolTable) {
3247 // Either this is an old form VST without function index and an
3248 // associated VST forward declaration record (which would have caused
3249 // the VST to be jumped to and parsed before it was encountered
3250 // normally in the stream), or there were no function blocks to
3251 // trigger an earlier parsing of the VST.
3252 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3253 if (std::error_code EC = parseValueSymbolTable())
3255 SeenValueSymbolTable = true;
3257 // We must have had a VST forward declaration record, which caused
3258 // the parser to jump to and parse the VST earlier.
3259 assert(VSTOffset > 0);
3260 if (Stream.SkipBlock())
3261 return error("Invalid record");
3264 case bitc::CONSTANTS_BLOCK_ID:
3265 if (std::error_code EC = parseConstants())
3267 if (std::error_code EC = resolveGlobalAndAliasInits())
3270 case bitc::METADATA_BLOCK_ID:
3271 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3272 if (std::error_code EC = rememberAndSkipMetadata())
3276 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3277 if (std::error_code EC = parseMetadata())
3280 case bitc::METADATA_KIND_BLOCK_ID:
3281 if (std::error_code EC = parseMetadataKinds())
3284 case bitc::FUNCTION_BLOCK_ID:
3285 // If this is the first function body we've seen, reverse the
3286 // FunctionsWithBodies list.
3287 if (!SeenFirstFunctionBody) {
3288 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3289 if (std::error_code EC = globalCleanup())
3291 SeenFirstFunctionBody = true;
3294 if (VSTOffset > 0) {
3295 // If we have a VST forward declaration record, make sure we
3296 // parse the VST now if we haven't already. It is needed to
3297 // set up the DeferredFunctionInfo vector for lazy reading.
3298 if (!SeenValueSymbolTable) {
3299 if (std::error_code EC =
3300 BitcodeReader::parseValueSymbolTable(VSTOffset))
3302 SeenValueSymbolTable = true;
3303 // Fall through so that we record the NextUnreadBit below.
3304 // This is necessary in case we have an anonymous function that
3305 // is later materialized. Since it will not have a VST entry we
3306 // need to fall back to the lazy parse to find its offset.
3308 // If we have a VST forward declaration record, but have already
3309 // parsed the VST (just above, when the first function body was
3310 // encountered here), then we are resuming the parse after
3311 // materializing functions. The ResumeBit points to the
3312 // start of the last function block recorded in the
3313 // DeferredFunctionInfo map. Skip it.
3314 if (Stream.SkipBlock())
3315 return error("Invalid record");
3320 // Support older bitcode files that did not have the function
3321 // index in the VST, nor a VST forward declaration record, as
3322 // well as anonymous functions that do not have VST entries.
3323 // Build the DeferredFunctionInfo vector on the fly.
3324 if (std::error_code EC = rememberAndSkipFunctionBody())
3327 // Suspend parsing when we reach the function bodies. Subsequent
3328 // materialization calls will resume it when necessary. If the bitcode
3329 // file is old, the symbol table will be at the end instead and will not
3330 // have been seen yet. In this case, just finish the parse now.
3331 if (SeenValueSymbolTable) {
3332 NextUnreadBit = Stream.GetCurrentBitNo();
3333 return std::error_code();
3336 case bitc::USELIST_BLOCK_ID:
3337 if (std::error_code EC = parseUseLists())
3340 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3341 if (std::error_code EC = parseOperandBundleTags())
3347 case BitstreamEntry::Record:
3348 // The interesting case.
3354 auto BitCode = Stream.readRecord(Entry.ID, Record);
3356 default: break; // Default behavior, ignore unknown content.
3357 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3358 if (Record.size() < 1)
3359 return error("Invalid record");
3360 // Only version #0 and #1 are supported so far.
3361 unsigned module_version = Record[0];
3362 switch (module_version) {
3364 return error("Invalid value");
3366 UseRelativeIDs = false;
3369 UseRelativeIDs = true;
3374 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3376 if (convertToString(Record, 0, S))
3377 return error("Invalid record");
3378 TheModule->setTargetTriple(S);
3381 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3383 if (convertToString(Record, 0, S))
3384 return error("Invalid record");
3385 TheModule->setDataLayout(S);
3388 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3390 if (convertToString(Record, 0, S))
3391 return error("Invalid record");
3392 TheModule->setModuleInlineAsm(S);
3395 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3396 // FIXME: Remove in 4.0.
3398 if (convertToString(Record, 0, S))
3399 return error("Invalid record");
3403 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3405 if (convertToString(Record, 0, S))
3406 return error("Invalid record");
3407 SectionTable.push_back(S);
3410 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3412 if (convertToString(Record, 0, S))
3413 return error("Invalid record");
3414 GCTable.push_back(S);
3417 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3418 if (Record.size() < 2)
3419 return error("Invalid record");
3420 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3421 unsigned ComdatNameSize = Record[1];
3422 std::string ComdatName;
3423 ComdatName.reserve(ComdatNameSize);
3424 for (unsigned i = 0; i != ComdatNameSize; ++i)
3425 ComdatName += (char)Record[2 + i];
3426 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3427 C->setSelectionKind(SK);
3428 ComdatList.push_back(C);
3431 // GLOBALVAR: [pointer type, isconst, initid,
3432 // linkage, alignment, section, visibility, threadlocal,
3433 // unnamed_addr, externally_initialized, dllstorageclass,
3435 case bitc::MODULE_CODE_GLOBALVAR: {
3436 if (Record.size() < 6)
3437 return error("Invalid record");
3438 Type *Ty = getTypeByID(Record[0]);
3440 return error("Invalid record");
3441 bool isConstant = Record[1] & 1;
3442 bool explicitType = Record[1] & 2;
3443 unsigned AddressSpace;
3445 AddressSpace = Record[1] >> 2;
3447 if (!Ty->isPointerTy())
3448 return error("Invalid type for value");
3449 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3450 Ty = cast<PointerType>(Ty)->getElementType();
3453 uint64_t RawLinkage = Record[3];
3454 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3456 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3458 std::string Section;
3460 if (Record[5]-1 >= SectionTable.size())
3461 return error("Invalid ID");
3462 Section = SectionTable[Record[5]-1];
3464 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3465 // Local linkage must have default visibility.
3466 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3467 // FIXME: Change to an error if non-default in 4.0.
3468 Visibility = getDecodedVisibility(Record[6]);
3470 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3471 if (Record.size() > 7)
3472 TLM = getDecodedThreadLocalMode(Record[7]);
3474 bool UnnamedAddr = false;
3475 if (Record.size() > 8)
3476 UnnamedAddr = Record[8];
3478 bool ExternallyInitialized = false;
3479 if (Record.size() > 9)
3480 ExternallyInitialized = Record[9];
3482 GlobalVariable *NewGV =
3483 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3484 TLM, AddressSpace, ExternallyInitialized);
3485 NewGV->setAlignment(Alignment);
3486 if (!Section.empty())
3487 NewGV->setSection(Section);
3488 NewGV->setVisibility(Visibility);
3489 NewGV->setUnnamedAddr(UnnamedAddr);
3491 if (Record.size() > 10)
3492 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3494 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3496 ValueList.push_back(NewGV);
3498 // Remember which value to use for the global initializer.
3499 if (unsigned InitID = Record[2])
3500 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3502 if (Record.size() > 11) {
3503 if (unsigned ComdatID = Record[11]) {
3504 if (ComdatID > ComdatList.size())
3505 return error("Invalid global variable comdat ID");
3506 NewGV->setComdat(ComdatList[ComdatID - 1]);
3508 } else if (hasImplicitComdat(RawLinkage)) {
3509 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3513 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3514 // alignment, section, visibility, gc, unnamed_addr,
3515 // prologuedata, dllstorageclass, comdat, prefixdata]
3516 case bitc::MODULE_CODE_FUNCTION: {
3517 if (Record.size() < 8)
3518 return error("Invalid record");
3519 Type *Ty = getTypeByID(Record[0]);
3521 return error("Invalid record");
3522 if (auto *PTy = dyn_cast<PointerType>(Ty))
3523 Ty = PTy->getElementType();
3524 auto *FTy = dyn_cast<FunctionType>(Ty);
3526 return error("Invalid type for value");
3527 auto CC = static_cast<CallingConv::ID>(Record[1]);
3528 if (CC & ~CallingConv::MaxID)
3529 return error("Invalid calling convention ID");
3531 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3534 Func->setCallingConv(CC);
3535 bool isProto = Record[2];
3536 uint64_t RawLinkage = Record[3];
3537 Func->setLinkage(getDecodedLinkage(RawLinkage));
3538 Func->setAttributes(getAttributes(Record[4]));
3541 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3543 Func->setAlignment(Alignment);
3545 if (Record[6]-1 >= SectionTable.size())
3546 return error("Invalid ID");
3547 Func->setSection(SectionTable[Record[6]-1]);
3549 // Local linkage must have default visibility.
3550 if (!Func->hasLocalLinkage())
3551 // FIXME: Change to an error if non-default in 4.0.
3552 Func->setVisibility(getDecodedVisibility(Record[7]));
3553 if (Record.size() > 8 && Record[8]) {
3554 if (Record[8]-1 >= GCTable.size())
3555 return error("Invalid ID");
3556 Func->setGC(GCTable[Record[8]-1].c_str());
3558 bool UnnamedAddr = false;
3559 if (Record.size() > 9)
3560 UnnamedAddr = Record[9];
3561 Func->setUnnamedAddr(UnnamedAddr);
3562 if (Record.size() > 10 && Record[10] != 0)
3563 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3565 if (Record.size() > 11)
3566 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3568 upgradeDLLImportExportLinkage(Func, RawLinkage);
3570 if (Record.size() > 12) {
3571 if (unsigned ComdatID = Record[12]) {
3572 if (ComdatID > ComdatList.size())
3573 return error("Invalid function comdat ID");
3574 Func->setComdat(ComdatList[ComdatID - 1]);
3576 } else if (hasImplicitComdat(RawLinkage)) {
3577 Func->setComdat(reinterpret_cast<Comdat *>(1));
3580 if (Record.size() > 13 && Record[13] != 0)
3581 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3583 if (Record.size() > 14 && Record[14] != 0)
3584 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3586 ValueList.push_back(Func);
3588 // If this is a function with a body, remember the prototype we are
3589 // creating now, so that we can match up the body with them later.
3591 Func->setIsMaterializable(true);
3592 FunctionsWithBodies.push_back(Func);
3593 DeferredFunctionInfo[Func] = 0;
3597 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3598 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3599 case bitc::MODULE_CODE_ALIAS:
3600 case bitc::MODULE_CODE_ALIAS_OLD: {
3601 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3602 if (Record.size() < (3 + (unsigned)NewRecord))
3603 return error("Invalid record");
3605 Type *Ty = getTypeByID(Record[OpNum++]);
3607 return error("Invalid record");
3611 auto *PTy = dyn_cast<PointerType>(Ty);
3613 return error("Invalid type for value");
3614 Ty = PTy->getElementType();
3615 AddrSpace = PTy->getAddressSpace();
3617 AddrSpace = Record[OpNum++];
3620 auto Val = Record[OpNum++];
3621 auto Linkage = Record[OpNum++];
3622 auto *NewGA = GlobalAlias::create(
3623 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3624 // Old bitcode files didn't have visibility field.
3625 // Local linkage must have default visibility.
3626 if (OpNum != Record.size()) {
3627 auto VisInd = OpNum++;
3628 if (!NewGA->hasLocalLinkage())
3629 // FIXME: Change to an error if non-default in 4.0.
3630 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3632 if (OpNum != Record.size())
3633 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3635 upgradeDLLImportExportLinkage(NewGA, Linkage);
3636 if (OpNum != Record.size())
3637 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3638 if (OpNum != Record.size())
3639 NewGA->setUnnamedAddr(Record[OpNum++]);
3640 ValueList.push_back(NewGA);
3641 AliasInits.push_back(std::make_pair(NewGA, Val));
3644 /// MODULE_CODE_PURGEVALS: [numvals]
3645 case bitc::MODULE_CODE_PURGEVALS:
3646 // Trim down the value list to the specified size.
3647 if (Record.size() < 1 || Record[0] > ValueList.size())
3648 return error("Invalid record");
3649 ValueList.shrinkTo(Record[0]);
3651 /// MODULE_CODE_VSTOFFSET: [offset]
3652 case bitc::MODULE_CODE_VSTOFFSET:
3653 if (Record.size() < 1)
3654 return error("Invalid record");
3655 VSTOffset = Record[0];
3662 /// Helper to read the header common to all bitcode files.
3663 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3664 // Sniff for the signature.
3665 if (Stream.Read(8) != 'B' ||
3666 Stream.Read(8) != 'C' ||
3667 Stream.Read(4) != 0x0 ||
3668 Stream.Read(4) != 0xC ||
3669 Stream.Read(4) != 0xE ||
3670 Stream.Read(4) != 0xD)
3676 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3677 Module *M, bool ShouldLazyLoadMetadata) {
3680 if (std::error_code EC = initStream(std::move(Streamer)))
3683 // Sniff for the signature.
3684 if (!hasValidBitcodeHeader(Stream))
3685 return error("Invalid bitcode signature");
3687 // We expect a number of well-defined blocks, though we don't necessarily
3688 // need to understand them all.
3690 if (Stream.AtEndOfStream()) {
3691 // We didn't really read a proper Module.
3692 return error("Malformed IR file");
3695 BitstreamEntry Entry =
3696 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3698 if (Entry.Kind != BitstreamEntry::SubBlock)
3699 return error("Malformed block");
3701 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3702 parseBitcodeVersion();
3706 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3707 return parseModule(0, ShouldLazyLoadMetadata);
3709 if (Stream.SkipBlock())
3710 return error("Invalid record");
3714 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3715 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3716 return error("Invalid record");
3718 SmallVector<uint64_t, 64> Record;
3721 // Read all the records for this module.
3723 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3725 switch (Entry.Kind) {
3726 case BitstreamEntry::SubBlock: // Handled for us already.
3727 case BitstreamEntry::Error:
3728 return error("Malformed block");
3729 case BitstreamEntry::EndBlock:
3731 case BitstreamEntry::Record:
3732 // The interesting case.
3737 switch (Stream.readRecord(Entry.ID, Record)) {
3738 default: break; // Default behavior, ignore unknown content.
3739 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3741 if (convertToString(Record, 0, S))
3742 return error("Invalid record");
3749 llvm_unreachable("Exit infinite loop");
3752 ErrorOr<std::string> BitcodeReader::parseTriple() {
3753 if (std::error_code EC = initStream(nullptr))
3756 // Sniff for the signature.
3757 if (!hasValidBitcodeHeader(Stream))
3758 return error("Invalid bitcode signature");
3760 // We expect a number of well-defined blocks, though we don't necessarily
3761 // need to understand them all.
3763 BitstreamEntry Entry = Stream.advance();
3765 switch (Entry.Kind) {
3766 case BitstreamEntry::Error:
3767 return error("Malformed block");
3768 case BitstreamEntry::EndBlock:
3769 return std::error_code();
3771 case BitstreamEntry::SubBlock:
3772 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3773 return parseModuleTriple();
3775 // Ignore other sub-blocks.
3776 if (Stream.SkipBlock())
3777 return error("Malformed block");
3780 case BitstreamEntry::Record:
3781 Stream.skipRecord(Entry.ID);
3787 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3788 if (std::error_code EC = initStream(nullptr))
3791 // Sniff for the signature.
3792 if (!hasValidBitcodeHeader(Stream))
3793 return error("Invalid bitcode signature");
3795 // We expect a number of well-defined blocks, though we don't necessarily
3796 // need to understand them all.
3798 BitstreamEntry Entry = Stream.advance();
3799 switch (Entry.Kind) {
3800 case BitstreamEntry::Error:
3801 return error("Malformed block");
3802 case BitstreamEntry::EndBlock:
3803 return std::error_code();
3805 case BitstreamEntry::SubBlock:
3806 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3807 if (std::error_code EC = parseBitcodeVersion())
3809 return ProducerIdentification;
3811 // Ignore other sub-blocks.
3812 if (Stream.SkipBlock())
3813 return error("Malformed block");
3815 case BitstreamEntry::Record:
3816 Stream.skipRecord(Entry.ID);
3822 /// Parse metadata attachments.
3823 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3824 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3825 return error("Invalid record");
3827 SmallVector<uint64_t, 64> Record;
3829 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3831 switch (Entry.Kind) {
3832 case BitstreamEntry::SubBlock: // Handled for us already.
3833 case BitstreamEntry::Error:
3834 return error("Malformed block");
3835 case BitstreamEntry::EndBlock:
3836 return std::error_code();
3837 case BitstreamEntry::Record:
3838 // The interesting case.
3842 // Read a metadata attachment record.
3844 switch (Stream.readRecord(Entry.ID, Record)) {
3845 default: // Default behavior: ignore.
3847 case bitc::METADATA_ATTACHMENT: {
3848 unsigned RecordLength = Record.size();
3850 return error("Invalid record");
3851 if (RecordLength % 2 == 0) {
3852 // A function attachment.
3853 for (unsigned I = 0; I != RecordLength; I += 2) {
3854 auto K = MDKindMap.find(Record[I]);
3855 if (K == MDKindMap.end())
3856 return error("Invalid ID");
3857 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3858 F.setMetadata(K->second, cast<MDNode>(MD));
3863 // An instruction attachment.
3864 Instruction *Inst = InstructionList[Record[0]];
3865 for (unsigned i = 1; i != RecordLength; i = i+2) {
3866 unsigned Kind = Record[i];
3867 DenseMap<unsigned, unsigned>::iterator I =
3868 MDKindMap.find(Kind);
3869 if (I == MDKindMap.end())
3870 return error("Invalid ID");
3871 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3872 if (isa<LocalAsMetadata>(Node))
3873 // Drop the attachment. This used to be legal, but there's no
3876 Inst->setMetadata(I->second, cast<MDNode>(Node));
3877 if (I->second == LLVMContext::MD_tbaa)
3878 InstsWithTBAATag.push_back(Inst);
3886 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3887 Type *ValType, Type *PtrType) {
3888 if (!isa<PointerType>(PtrType))
3889 return error(DH, "Load/Store operand is not a pointer type");
3890 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3892 if (ValType && ValType != ElemType)
3893 return error(DH, "Explicit load/store type does not match pointee type of "
3895 if (!PointerType::isLoadableOrStorableType(ElemType))
3896 return error(DH, "Cannot load/store from pointer");
3897 return std::error_code();
3900 /// Lazily parse the specified function body block.
3901 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3902 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3903 return error("Invalid record");
3905 InstructionList.clear();
3906 unsigned ModuleValueListSize = ValueList.size();
3907 unsigned ModuleMDValueListSize = MDValueList.size();
3909 // Add all the function arguments to the value table.
3910 for (Argument &I : F->args())
3911 ValueList.push_back(&I);
3913 unsigned NextValueNo = ValueList.size();
3914 BasicBlock *CurBB = nullptr;
3915 unsigned CurBBNo = 0;
3918 auto getLastInstruction = [&]() -> Instruction * {
3919 if (CurBB && !CurBB->empty())
3920 return &CurBB->back();
3921 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3922 !FunctionBBs[CurBBNo - 1]->empty())
3923 return &FunctionBBs[CurBBNo - 1]->back();
3927 std::vector<OperandBundleDef> OperandBundles;
3929 // Read all the records.
3930 SmallVector<uint64_t, 64> Record;
3932 BitstreamEntry Entry = Stream.advance();
3934 switch (Entry.Kind) {
3935 case BitstreamEntry::Error:
3936 return error("Malformed block");
3937 case BitstreamEntry::EndBlock:
3938 goto OutOfRecordLoop;
3940 case BitstreamEntry::SubBlock:
3942 default: // Skip unknown content.
3943 if (Stream.SkipBlock())
3944 return error("Invalid record");
3946 case bitc::CONSTANTS_BLOCK_ID:
3947 if (std::error_code EC = parseConstants())
3949 NextValueNo = ValueList.size();
3951 case bitc::VALUE_SYMTAB_BLOCK_ID:
3952 if (std::error_code EC = parseValueSymbolTable())
3955 case bitc::METADATA_ATTACHMENT_ID:
3956 if (std::error_code EC = parseMetadataAttachment(*F))
3959 case bitc::METADATA_BLOCK_ID:
3960 if (std::error_code EC = parseMetadata())
3963 case bitc::USELIST_BLOCK_ID:
3964 if (std::error_code EC = parseUseLists())
3970 case BitstreamEntry::Record:
3971 // The interesting case.
3977 Instruction *I = nullptr;
3978 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3980 default: // Default behavior: reject
3981 return error("Invalid value");
3982 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3983 if (Record.size() < 1 || Record[0] == 0)
3984 return error("Invalid record");
3985 // Create all the basic blocks for the function.
3986 FunctionBBs.resize(Record[0]);
3988 // See if anything took the address of blocks in this function.
3989 auto BBFRI = BasicBlockFwdRefs.find(F);
3990 if (BBFRI == BasicBlockFwdRefs.end()) {
3991 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3992 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3994 auto &BBRefs = BBFRI->second;
3995 // Check for invalid basic block references.
3996 if (BBRefs.size() > FunctionBBs.size())
3997 return error("Invalid ID");
3998 assert(!BBRefs.empty() && "Unexpected empty array");
3999 assert(!BBRefs.front() && "Invalid reference to entry block");
4000 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4002 if (I < RE && BBRefs[I]) {
4003 BBRefs[I]->insertInto(F);
4004 FunctionBBs[I] = BBRefs[I];
4006 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4009 // Erase from the table.
4010 BasicBlockFwdRefs.erase(BBFRI);
4013 CurBB = FunctionBBs[0];
4017 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4018 // This record indicates that the last instruction is at the same
4019 // location as the previous instruction with a location.
4020 I = getLastInstruction();
4023 return error("Invalid record");
4024 I->setDebugLoc(LastLoc);
4028 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4029 I = getLastInstruction();
4030 if (!I || Record.size() < 4)
4031 return error("Invalid record");
4033 unsigned Line = Record[0], Col = Record[1];
4034 unsigned ScopeID = Record[2], IAID = Record[3];
4036 MDNode *Scope = nullptr, *IA = nullptr;
4037 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
4038 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
4039 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4040 I->setDebugLoc(LastLoc);
4045 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4048 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4049 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4050 OpNum+1 > Record.size())
4051 return error("Invalid record");
4053 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4055 return error("Invalid record");
4056 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4057 InstructionList.push_back(I);
4058 if (OpNum < Record.size()) {
4059 if (Opc == Instruction::Add ||
4060 Opc == Instruction::Sub ||
4061 Opc == Instruction::Mul ||
4062 Opc == Instruction::Shl) {
4063 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4064 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4065 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4066 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4067 } else if (Opc == Instruction::SDiv ||
4068 Opc == Instruction::UDiv ||
4069 Opc == Instruction::LShr ||
4070 Opc == Instruction::AShr) {
4071 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4072 cast<BinaryOperator>(I)->setIsExact(true);
4073 } else if (isa<FPMathOperator>(I)) {
4074 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4076 I->setFastMathFlags(FMF);
4082 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4085 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4086 OpNum+2 != Record.size())
4087 return error("Invalid record");
4089 Type *ResTy = getTypeByID(Record[OpNum]);
4090 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4091 if (Opc == -1 || !ResTy)
4092 return error("Invalid record");
4093 Instruction *Temp = nullptr;
4094 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4096 InstructionList.push_back(Temp);
4097 CurBB->getInstList().push_back(Temp);
4100 auto CastOp = (Instruction::CastOps)Opc;
4101 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4102 return error("Invalid cast");
4103 I = CastInst::Create(CastOp, Op, ResTy);
4105 InstructionList.push_back(I);
4108 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4109 case bitc::FUNC_CODE_INST_GEP_OLD:
4110 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4116 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4117 InBounds = Record[OpNum++];
4118 Ty = getTypeByID(Record[OpNum++]);
4120 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4125 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4126 return error("Invalid record");
4129 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4132 cast<SequentialType>(BasePtr->getType()->getScalarType())
4135 "Explicit gep type does not match pointee type of pointer operand");
4137 SmallVector<Value*, 16> GEPIdx;
4138 while (OpNum != Record.size()) {
4140 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4141 return error("Invalid record");
4142 GEPIdx.push_back(Op);
4145 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4147 InstructionList.push_back(I);
4149 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4153 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4154 // EXTRACTVAL: [opty, opval, n x indices]
4157 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4158 return error("Invalid record");
4160 unsigned RecSize = Record.size();
4161 if (OpNum == RecSize)
4162 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4164 SmallVector<unsigned, 4> EXTRACTVALIdx;
4165 Type *CurTy = Agg->getType();
4166 for (; OpNum != RecSize; ++OpNum) {
4167 bool IsArray = CurTy->isArrayTy();
4168 bool IsStruct = CurTy->isStructTy();
4169 uint64_t Index = Record[OpNum];
4171 if (!IsStruct && !IsArray)
4172 return error("EXTRACTVAL: Invalid type");
4173 if ((unsigned)Index != Index)
4174 return error("Invalid value");
4175 if (IsStruct && Index >= CurTy->subtypes().size())
4176 return error("EXTRACTVAL: Invalid struct index");
4177 if (IsArray && Index >= CurTy->getArrayNumElements())
4178 return error("EXTRACTVAL: Invalid array index");
4179 EXTRACTVALIdx.push_back((unsigned)Index);
4182 CurTy = CurTy->subtypes()[Index];
4184 CurTy = CurTy->subtypes()[0];
4187 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4188 InstructionList.push_back(I);
4192 case bitc::FUNC_CODE_INST_INSERTVAL: {
4193 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4196 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4197 return error("Invalid record");
4199 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4200 return error("Invalid record");
4202 unsigned RecSize = Record.size();
4203 if (OpNum == RecSize)
4204 return error("INSERTVAL: Invalid instruction with 0 indices");
4206 SmallVector<unsigned, 4> INSERTVALIdx;
4207 Type *CurTy = Agg->getType();
4208 for (; OpNum != RecSize; ++OpNum) {
4209 bool IsArray = CurTy->isArrayTy();
4210 bool IsStruct = CurTy->isStructTy();
4211 uint64_t Index = Record[OpNum];
4213 if (!IsStruct && !IsArray)
4214 return error("INSERTVAL: Invalid type");
4215 if ((unsigned)Index != Index)
4216 return error("Invalid value");
4217 if (IsStruct && Index >= CurTy->subtypes().size())
4218 return error("INSERTVAL: Invalid struct index");
4219 if (IsArray && Index >= CurTy->getArrayNumElements())
4220 return error("INSERTVAL: Invalid array index");
4222 INSERTVALIdx.push_back((unsigned)Index);
4224 CurTy = CurTy->subtypes()[Index];
4226 CurTy = CurTy->subtypes()[0];
4229 if (CurTy != Val->getType())
4230 return error("Inserted value type doesn't match aggregate type");
4232 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4233 InstructionList.push_back(I);
4237 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4238 // obsolete form of select
4239 // handles select i1 ... in old bitcode
4241 Value *TrueVal, *FalseVal, *Cond;
4242 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4243 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4244 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4245 return error("Invalid record");
4247 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4248 InstructionList.push_back(I);
4252 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4253 // new form of select
4254 // handles select i1 or select [N x i1]
4256 Value *TrueVal, *FalseVal, *Cond;
4257 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4258 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4259 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4260 return error("Invalid record");
4262 // select condition can be either i1 or [N x i1]
4263 if (VectorType* vector_type =
4264 dyn_cast<VectorType>(Cond->getType())) {
4266 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4267 return error("Invalid type for value");
4270 if (Cond->getType() != Type::getInt1Ty(Context))
4271 return error("Invalid type for value");
4274 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4275 InstructionList.push_back(I);
4279 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4282 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4283 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4284 return error("Invalid record");
4285 if (!Vec->getType()->isVectorTy())
4286 return error("Invalid type for value");
4287 I = ExtractElementInst::Create(Vec, Idx);
4288 InstructionList.push_back(I);
4292 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4294 Value *Vec, *Elt, *Idx;
4295 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4296 return error("Invalid record");
4297 if (!Vec->getType()->isVectorTy())
4298 return error("Invalid type for value");
4299 if (popValue(Record, OpNum, NextValueNo,
4300 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4301 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4302 return error("Invalid record");
4303 I = InsertElementInst::Create(Vec, Elt, Idx);
4304 InstructionList.push_back(I);
4308 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4310 Value *Vec1, *Vec2, *Mask;
4311 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4312 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4313 return error("Invalid record");
4315 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4316 return error("Invalid record");
4317 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4318 return error("Invalid type for value");
4319 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4320 InstructionList.push_back(I);
4324 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4325 // Old form of ICmp/FCmp returning bool
4326 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4327 // both legal on vectors but had different behaviour.
4328 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4329 // FCmp/ICmp returning bool or vector of bool
4333 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4334 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4335 return error("Invalid record");
4337 unsigned PredVal = Record[OpNum];
4338 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4340 if (IsFP && Record.size() > OpNum+1)
4341 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4343 if (OpNum+1 != Record.size())
4344 return error("Invalid record");
4346 if (LHS->getType()->isFPOrFPVectorTy())
4347 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4349 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4352 I->setFastMathFlags(FMF);
4353 InstructionList.push_back(I);
4357 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4359 unsigned Size = Record.size();
4361 I = ReturnInst::Create(Context);
4362 InstructionList.push_back(I);
4367 Value *Op = nullptr;
4368 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4369 return error("Invalid record");
4370 if (OpNum != Record.size())
4371 return error("Invalid record");
4373 I = ReturnInst::Create(Context, Op);
4374 InstructionList.push_back(I);
4377 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4378 if (Record.size() != 1 && Record.size() != 3)
4379 return error("Invalid record");
4380 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4382 return error("Invalid record");
4384 if (Record.size() == 1) {
4385 I = BranchInst::Create(TrueDest);
4386 InstructionList.push_back(I);
4389 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4390 Value *Cond = getValue(Record, 2, NextValueNo,
4391 Type::getInt1Ty(Context));
4392 if (!FalseDest || !Cond)
4393 return error("Invalid record");
4394 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4395 InstructionList.push_back(I);
4399 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4400 if (Record.size() != 1 && Record.size() != 2)
4401 return error("Invalid record");
4403 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4404 Type::getTokenTy(Context), OC_CleanupPad);
4406 return error("Invalid record");
4407 BasicBlock *UnwindDest = nullptr;
4408 if (Record.size() == 2) {
4409 UnwindDest = getBasicBlock(Record[Idx++]);
4411 return error("Invalid record");
4414 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4416 InstructionList.push_back(I);
4419 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4420 if (Record.size() != 2)
4421 return error("Invalid record");
4423 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4424 Type::getTokenTy(Context), OC_CatchPad);
4426 return error("Invalid record");
4427 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4429 return error("Invalid record");
4431 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4432 InstructionList.push_back(I);
4435 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4436 if (Record.size() < 3)
4437 return error("Invalid record");
4439 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4441 return error("Invalid record");
4442 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4444 return error("Invalid record");
4445 unsigned NumArgOperands = Record[Idx++];
4446 SmallVector<Value *, 2> Args;
4447 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4449 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4450 return error("Invalid record");
4451 Args.push_back(Val);
4453 if (Record.size() != Idx)
4454 return error("Invalid record");
4456 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4457 InstructionList.push_back(I);
4460 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4461 if (Record.size() < 1)
4462 return error("Invalid record");
4464 bool HasUnwindDest = !!Record[Idx++];
4465 BasicBlock *UnwindDest = nullptr;
4466 if (HasUnwindDest) {
4467 if (Idx == Record.size())
4468 return error("Invalid record");
4469 UnwindDest = getBasicBlock(Record[Idx++]);
4471 return error("Invalid record");
4473 unsigned NumArgOperands = Record[Idx++];
4474 SmallVector<Value *, 2> Args;
4475 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4477 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4478 return error("Invalid record");
4479 Args.push_back(Val);
4481 if (Record.size() != Idx)
4482 return error("Invalid record");
4484 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4485 InstructionList.push_back(I);
4488 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4489 if (Record.size() < 1)
4490 return error("Invalid record");
4492 unsigned NumArgOperands = Record[Idx++];
4493 SmallVector<Value *, 2> Args;
4494 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4496 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4497 return error("Invalid record");
4498 Args.push_back(Val);
4500 if (Record.size() != Idx)
4501 return error("Invalid record");
4503 I = CleanupPadInst::Create(Context, Args);
4504 InstructionList.push_back(I);
4507 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4508 if (Record.size() > 1)
4509 return error("Invalid record");
4510 BasicBlock *BB = nullptr;
4511 if (Record.size() == 1) {
4512 BB = getBasicBlock(Record[0]);
4514 return error("Invalid record");
4516 I = CatchEndPadInst::Create(Context, BB);
4517 InstructionList.push_back(I);
4520 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4521 if (Record.size() != 1 && Record.size() != 2)
4522 return error("Invalid record");
4524 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4525 Type::getTokenTy(Context), OC_CleanupPad);
4527 return error("Invalid record");
4529 BasicBlock *BB = nullptr;
4530 if (Record.size() == 2) {
4531 BB = getBasicBlock(Record[Idx++]);
4533 return error("Invalid record");
4535 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4536 InstructionList.push_back(I);
4539 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4541 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4542 // "New" SwitchInst format with case ranges. The changes to write this
4543 // format were reverted but we still recognize bitcode that uses it.
4544 // Hopefully someday we will have support for case ranges and can use
4545 // this format again.
4547 Type *OpTy = getTypeByID(Record[1]);
4548 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4550 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4551 BasicBlock *Default = getBasicBlock(Record[3]);
4552 if (!OpTy || !Cond || !Default)
4553 return error("Invalid record");
4555 unsigned NumCases = Record[4];
4557 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4558 InstructionList.push_back(SI);
4560 unsigned CurIdx = 5;
4561 for (unsigned i = 0; i != NumCases; ++i) {
4562 SmallVector<ConstantInt*, 1> CaseVals;
4563 unsigned NumItems = Record[CurIdx++];
4564 for (unsigned ci = 0; ci != NumItems; ++ci) {
4565 bool isSingleNumber = Record[CurIdx++];
4568 unsigned ActiveWords = 1;
4569 if (ValueBitWidth > 64)
4570 ActiveWords = Record[CurIdx++];
4571 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4573 CurIdx += ActiveWords;
4575 if (!isSingleNumber) {
4577 if (ValueBitWidth > 64)
4578 ActiveWords = Record[CurIdx++];
4579 APInt High = readWideAPInt(
4580 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4581 CurIdx += ActiveWords;
4583 // FIXME: It is not clear whether values in the range should be
4584 // compared as signed or unsigned values. The partially
4585 // implemented changes that used this format in the past used
4586 // unsigned comparisons.
4587 for ( ; Low.ule(High); ++Low)
4588 CaseVals.push_back(ConstantInt::get(Context, Low));
4590 CaseVals.push_back(ConstantInt::get(Context, Low));
4592 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4593 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4594 cve = CaseVals.end(); cvi != cve; ++cvi)
4595 SI->addCase(*cvi, DestBB);
4601 // Old SwitchInst format without case ranges.
4603 if (Record.size() < 3 || (Record.size() & 1) == 0)
4604 return error("Invalid record");
4605 Type *OpTy = getTypeByID(Record[0]);
4606 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4607 BasicBlock *Default = getBasicBlock(Record[2]);
4608 if (!OpTy || !Cond || !Default)
4609 return error("Invalid record");
4610 unsigned NumCases = (Record.size()-3)/2;
4611 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4612 InstructionList.push_back(SI);
4613 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4614 ConstantInt *CaseVal =
4615 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4616 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4617 if (!CaseVal || !DestBB) {
4619 return error("Invalid record");
4621 SI->addCase(CaseVal, DestBB);
4626 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4627 if (Record.size() < 2)
4628 return error("Invalid record");
4629 Type *OpTy = getTypeByID(Record[0]);
4630 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4631 if (!OpTy || !Address)
4632 return error("Invalid record");
4633 unsigned NumDests = Record.size()-2;
4634 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4635 InstructionList.push_back(IBI);
4636 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4637 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4638 IBI->addDestination(DestBB);
4641 return error("Invalid record");
4648 case bitc::FUNC_CODE_INST_INVOKE: {
4649 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4650 if (Record.size() < 4)
4651 return error("Invalid record");
4653 AttributeSet PAL = getAttributes(Record[OpNum++]);
4654 unsigned CCInfo = Record[OpNum++];
4655 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4656 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4658 FunctionType *FTy = nullptr;
4659 if (CCInfo >> 13 & 1 &&
4660 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4661 return error("Explicit invoke type is not a function type");
4664 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4665 return error("Invalid record");
4667 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4669 return error("Callee is not a pointer");
4671 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4673 return error("Callee is not of pointer to function type");
4674 } else if (CalleeTy->getElementType() != FTy)
4675 return error("Explicit invoke type does not match pointee type of "
4677 if (Record.size() < FTy->getNumParams() + OpNum)
4678 return error("Insufficient operands to call");
4680 SmallVector<Value*, 16> Ops;
4681 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4682 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4683 FTy->getParamType(i)));
4685 return error("Invalid record");
4688 if (!FTy->isVarArg()) {
4689 if (Record.size() != OpNum)
4690 return error("Invalid record");
4692 // Read type/value pairs for varargs params.
4693 while (OpNum != Record.size()) {
4695 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4696 return error("Invalid record");
4701 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4702 OperandBundles.clear();
4703 InstructionList.push_back(I);
4704 cast<InvokeInst>(I)->setCallingConv(
4705 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4706 cast<InvokeInst>(I)->setAttributes(PAL);
4709 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4711 Value *Val = nullptr;
4712 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4713 return error("Invalid record");
4714 I = ResumeInst::Create(Val);
4715 InstructionList.push_back(I);
4718 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4719 I = new UnreachableInst(Context);
4720 InstructionList.push_back(I);
4722 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4723 if (Record.size() < 1 || ((Record.size()-1)&1))
4724 return error("Invalid record");
4725 Type *Ty = getTypeByID(Record[0]);
4727 return error("Invalid record");
4729 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4730 InstructionList.push_back(PN);
4732 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4734 // With the new function encoding, it is possible that operands have
4735 // negative IDs (for forward references). Use a signed VBR
4736 // representation to keep the encoding small.
4738 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4740 V = getValue(Record, 1+i, NextValueNo, Ty);
4741 BasicBlock *BB = getBasicBlock(Record[2+i]);
4743 return error("Invalid record");
4744 PN->addIncoming(V, BB);
4750 case bitc::FUNC_CODE_INST_LANDINGPAD:
4751 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4752 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4754 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4755 if (Record.size() < 3)
4756 return error("Invalid record");
4758 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4759 if (Record.size() < 4)
4760 return error("Invalid record");
4762 Type *Ty = getTypeByID(Record[Idx++]);
4764 return error("Invalid record");
4765 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4766 Value *PersFn = nullptr;
4767 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4768 return error("Invalid record");
4770 if (!F->hasPersonalityFn())
4771 F->setPersonalityFn(cast<Constant>(PersFn));
4772 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4773 return error("Personality function mismatch");
4776 bool IsCleanup = !!Record[Idx++];
4777 unsigned NumClauses = Record[Idx++];
4778 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4779 LP->setCleanup(IsCleanup);
4780 for (unsigned J = 0; J != NumClauses; ++J) {
4781 LandingPadInst::ClauseType CT =
4782 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4785 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4787 return error("Invalid record");
4790 assert((CT != LandingPadInst::Catch ||
4791 !isa<ArrayType>(Val->getType())) &&
4792 "Catch clause has a invalid type!");
4793 assert((CT != LandingPadInst::Filter ||
4794 isa<ArrayType>(Val->getType())) &&
4795 "Filter clause has invalid type!");
4796 LP->addClause(cast<Constant>(Val));
4800 InstructionList.push_back(I);
4804 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4805 if (Record.size() != 4)
4806 return error("Invalid record");
4807 uint64_t AlignRecord = Record[3];
4808 const uint64_t InAllocaMask = uint64_t(1) << 5;
4809 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4810 // Reserve bit 7 for SwiftError flag.
4811 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4812 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4813 bool InAlloca = AlignRecord & InAllocaMask;
4814 Type *Ty = getTypeByID(Record[0]);
4815 if ((AlignRecord & ExplicitTypeMask) == 0) {
4816 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4818 return error("Old-style alloca with a non-pointer type");
4819 Ty = PTy->getElementType();
4821 Type *OpTy = getTypeByID(Record[1]);
4822 Value *Size = getFnValueByID(Record[2], OpTy);
4824 if (std::error_code EC =
4825 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4829 return error("Invalid record");
4830 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4831 AI->setUsedWithInAlloca(InAlloca);
4833 InstructionList.push_back(I);
4836 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4839 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4840 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4841 return error("Invalid record");
4844 if (OpNum + 3 == Record.size())
4845 Ty = getTypeByID(Record[OpNum++]);
4846 if (std::error_code EC =
4847 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4850 Ty = cast<PointerType>(Op->getType())->getElementType();
4853 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4855 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4857 InstructionList.push_back(I);
4860 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4861 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4864 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4865 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4866 return error("Invalid record");
4869 if (OpNum + 5 == Record.size())
4870 Ty = getTypeByID(Record[OpNum++]);
4871 if (std::error_code EC =
4872 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4875 Ty = cast<PointerType>(Op->getType())->getElementType();
4877 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4878 if (Ordering == NotAtomic || Ordering == Release ||
4879 Ordering == AcquireRelease)
4880 return error("Invalid record");
4881 if (Ordering != NotAtomic && Record[OpNum] == 0)
4882 return error("Invalid record");
4883 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4886 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4888 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4890 InstructionList.push_back(I);
4893 case bitc::FUNC_CODE_INST_STORE:
4894 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4897 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4898 (BitCode == bitc::FUNC_CODE_INST_STORE
4899 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4900 : popValue(Record, OpNum, NextValueNo,
4901 cast<PointerType>(Ptr->getType())->getElementType(),
4903 OpNum + 2 != Record.size())
4904 return error("Invalid record");
4906 if (std::error_code EC = typeCheckLoadStoreInst(
4907 DiagnosticHandler, Val->getType(), Ptr->getType()))
4910 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4912 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4913 InstructionList.push_back(I);
4916 case bitc::FUNC_CODE_INST_STOREATOMIC:
4917 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4918 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4921 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4922 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4923 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4924 : popValue(Record, OpNum, NextValueNo,
4925 cast<PointerType>(Ptr->getType())->getElementType(),
4927 OpNum + 4 != Record.size())
4928 return error("Invalid record");
4930 if (std::error_code EC = typeCheckLoadStoreInst(
4931 DiagnosticHandler, Val->getType(), Ptr->getType()))
4933 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4934 if (Ordering == NotAtomic || Ordering == Acquire ||
4935 Ordering == AcquireRelease)
4936 return error("Invalid record");
4937 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4938 if (Ordering != NotAtomic && Record[OpNum] == 0)
4939 return error("Invalid record");
4942 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4944 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4945 InstructionList.push_back(I);
4948 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4949 case bitc::FUNC_CODE_INST_CMPXCHG: {
4950 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4951 // failureordering?, isweak?]
4953 Value *Ptr, *Cmp, *New;
4954 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4955 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4956 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4957 : popValue(Record, OpNum, NextValueNo,
4958 cast<PointerType>(Ptr->getType())->getElementType(),
4960 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4961 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4962 return error("Invalid record");
4963 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4964 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4965 return error("Invalid record");
4966 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4968 if (std::error_code EC = typeCheckLoadStoreInst(
4969 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4971 AtomicOrdering FailureOrdering;
4972 if (Record.size() < 7)
4974 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4976 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4978 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4980 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4982 if (Record.size() < 8) {
4983 // Before weak cmpxchgs existed, the instruction simply returned the
4984 // value loaded from memory, so bitcode files from that era will be
4985 // expecting the first component of a modern cmpxchg.
4986 CurBB->getInstList().push_back(I);
4987 I = ExtractValueInst::Create(I, 0);
4989 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4992 InstructionList.push_back(I);
4995 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4996 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4999 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5000 popValue(Record, OpNum, NextValueNo,
5001 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5002 OpNum+4 != Record.size())
5003 return error("Invalid record");
5004 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5005 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5006 Operation > AtomicRMWInst::LAST_BINOP)
5007 return error("Invalid record");
5008 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5009 if (Ordering == NotAtomic || Ordering == Unordered)
5010 return error("Invalid record");
5011 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5012 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5013 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5014 InstructionList.push_back(I);
5017 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5018 if (2 != Record.size())
5019 return error("Invalid record");
5020 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5021 if (Ordering == NotAtomic || Ordering == Unordered ||
5022 Ordering == Monotonic)
5023 return error("Invalid record");
5024 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5025 I = new FenceInst(Context, Ordering, SynchScope);
5026 InstructionList.push_back(I);
5029 case bitc::FUNC_CODE_INST_CALL: {
5030 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
5031 if (Record.size() < 3)
5032 return error("Invalid record");
5035 AttributeSet PAL = getAttributes(Record[OpNum++]);
5036 unsigned CCInfo = Record[OpNum++];
5038 FunctionType *FTy = nullptr;
5039 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5040 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5041 return error("Explicit call type is not a function type");
5044 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5045 return error("Invalid record");
5047 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5049 return error("Callee is not a pointer type");
5051 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5053 return error("Callee is not of pointer to function type");
5054 } else if (OpTy->getElementType() != FTy)
5055 return error("Explicit call type does not match pointee type of "
5057 if (Record.size() < FTy->getNumParams() + OpNum)
5058 return error("Insufficient operands to call");
5060 SmallVector<Value*, 16> Args;
5061 // Read the fixed params.
5062 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5063 if (FTy->getParamType(i)->isLabelTy())
5064 Args.push_back(getBasicBlock(Record[OpNum]));
5066 Args.push_back(getValue(Record, OpNum, NextValueNo,
5067 FTy->getParamType(i)));
5069 return error("Invalid record");
5072 // Read type/value pairs for varargs params.
5073 if (!FTy->isVarArg()) {
5074 if (OpNum != Record.size())
5075 return error("Invalid record");
5077 while (OpNum != Record.size()) {
5079 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5080 return error("Invalid record");
5085 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5086 OperandBundles.clear();
5087 InstructionList.push_back(I);
5088 cast<CallInst>(I)->setCallingConv(
5089 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5090 CallInst::TailCallKind TCK = CallInst::TCK_None;
5091 if (CCInfo & 1 << bitc::CALL_TAIL)
5092 TCK = CallInst::TCK_Tail;
5093 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5094 TCK = CallInst::TCK_MustTail;
5095 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5096 TCK = CallInst::TCK_NoTail;
5097 cast<CallInst>(I)->setTailCallKind(TCK);
5098 cast<CallInst>(I)->setAttributes(PAL);
5101 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5102 if (Record.size() < 3)
5103 return error("Invalid record");
5104 Type *OpTy = getTypeByID(Record[0]);
5105 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5106 Type *ResTy = getTypeByID(Record[2]);
5107 if (!OpTy || !Op || !ResTy)
5108 return error("Invalid record");
5109 I = new VAArgInst(Op, ResTy);
5110 InstructionList.push_back(I);
5114 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5115 // A call or an invoke can be optionally prefixed with some variable
5116 // number of operand bundle blocks. These blocks are read into
5117 // OperandBundles and consumed at the next call or invoke instruction.
5119 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5120 return error("Invalid record");
5122 std::vector<Value *> Inputs;
5125 while (OpNum != Record.size()) {
5127 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5128 return error("Invalid record");
5129 Inputs.push_back(Op);
5132 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5137 // Add instruction to end of current BB. If there is no current BB, reject
5141 return error("Invalid instruction with no BB");
5143 if (!OperandBundles.empty()) {
5145 return error("Operand bundles found with no consumer");
5147 CurBB->getInstList().push_back(I);
5149 // If this was a terminator instruction, move to the next block.
5150 if (isa<TerminatorInst>(I)) {
5152 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5155 // Non-void values get registered in the value table for future use.
5156 if (I && !I->getType()->isVoidTy())
5157 if (ValueList.assignValue(I, NextValueNo++))
5158 return error("Invalid forward reference");
5163 if (!OperandBundles.empty())
5164 return error("Operand bundles found with no consumer");
5166 // Check the function list for unresolved values.
5167 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5168 if (!A->getParent()) {
5169 // We found at least one unresolved value. Nuke them all to avoid leaks.
5170 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5171 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5172 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5176 return error("Never resolved value found in function");
5180 // FIXME: Check for unresolved forward-declared metadata references
5181 // and clean up leaks.
5183 // Trim the value list down to the size it was before we parsed this function.
5184 ValueList.shrinkTo(ModuleValueListSize);
5185 MDValueList.shrinkTo(ModuleMDValueListSize);
5186 std::vector<BasicBlock*>().swap(FunctionBBs);
5187 return std::error_code();
5190 /// Find the function body in the bitcode stream
5191 std::error_code BitcodeReader::findFunctionInStream(
5193 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5194 while (DeferredFunctionInfoIterator->second == 0) {
5195 // This is the fallback handling for the old format bitcode that
5196 // didn't contain the function index in the VST, or when we have
5197 // an anonymous function which would not have a VST entry.
5198 // Assert that we have one of those two cases.
5199 assert(VSTOffset == 0 || !F->hasName());
5200 // Parse the next body in the stream and set its position in the
5201 // DeferredFunctionInfo map.
5202 if (std::error_code EC = rememberAndSkipFunctionBodies())
5205 return std::error_code();
5208 //===----------------------------------------------------------------------===//
5209 // GVMaterializer implementation
5210 //===----------------------------------------------------------------------===//
5212 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5214 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5215 if (std::error_code EC = materializeMetadata())
5218 Function *F = dyn_cast<Function>(GV);
5219 // If it's not a function or is already material, ignore the request.
5220 if (!F || !F->isMaterializable())
5221 return std::error_code();
5223 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5224 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5225 // If its position is recorded as 0, its body is somewhere in the stream
5226 // but we haven't seen it yet.
5227 if (DFII->second == 0)
5228 if (std::error_code EC = findFunctionInStream(F, DFII))
5231 // Move the bit stream to the saved position of the deferred function body.
5232 Stream.JumpToBit(DFII->second);
5234 if (std::error_code EC = parseFunctionBody(F))
5236 F->setIsMaterializable(false);
5241 // Upgrade any old intrinsic calls in the function.
5242 for (auto &I : UpgradedIntrinsics) {
5243 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5246 if (CallInst *CI = dyn_cast<CallInst>(U))
5247 UpgradeIntrinsicCall(CI, I.second);
5251 // Finish fn->subprogram upgrade for materialized functions.
5252 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5253 F->setSubprogram(SP);
5255 // Bring in any functions that this function forward-referenced via
5257 return materializeForwardReferencedFunctions();
5260 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5261 const Function *F = dyn_cast<Function>(GV);
5262 if (!F || F->isDeclaration())
5265 // Dematerializing F would leave dangling references that wouldn't be
5266 // reconnected on re-materialization.
5267 if (BlockAddressesTaken.count(F))
5270 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5273 void BitcodeReader::dematerialize(GlobalValue *GV) {
5274 Function *F = dyn_cast<Function>(GV);
5275 // If this function isn't dematerializable, this is a noop.
5276 if (!F || !isDematerializable(F))
5279 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5281 // Just forget the function body, we can remat it later.
5282 F->dropAllReferences();
5283 F->setIsMaterializable(true);
5286 std::error_code BitcodeReader::materializeModule(Module *M) {
5287 assert(M == TheModule &&
5288 "Can only Materialize the Module this BitcodeReader is attached to.");
5290 if (std::error_code EC = materializeMetadata())
5293 // Promise to materialize all forward references.
5294 WillMaterializeAllForwardRefs = true;
5296 // Iterate over the module, deserializing any functions that are still on
5298 for (Function &F : *TheModule) {
5299 if (std::error_code EC = materialize(&F))
5302 // At this point, if there are any function bodies, parse the rest of
5303 // the bits in the module past the last function block we have recorded
5304 // through either lazy scanning or the VST.
5305 if (LastFunctionBlockBit || NextUnreadBit)
5306 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5309 // Check that all block address forward references got resolved (as we
5311 if (!BasicBlockFwdRefs.empty())
5312 return error("Never resolved function from blockaddress");
5314 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5315 // delete the old functions to clean up. We can't do this unless the entire
5316 // module is materialized because there could always be another function body
5317 // with calls to the old function.
5318 for (auto &I : UpgradedIntrinsics) {
5319 for (auto *U : I.first->users()) {
5320 if (CallInst *CI = dyn_cast<CallInst>(U))
5321 UpgradeIntrinsicCall(CI, I.second);
5323 if (!I.first->use_empty())
5324 I.first->replaceAllUsesWith(I.second);
5325 I.first->eraseFromParent();
5327 UpgradedIntrinsics.clear();
5329 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5330 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5332 UpgradeDebugInfo(*M);
5333 return std::error_code();
5336 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5337 return IdentifiedStructTypes;
5341 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5343 return initLazyStream(std::move(Streamer));
5344 return initStreamFromBuffer();
5347 std::error_code BitcodeReader::initStreamFromBuffer() {
5348 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5349 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5351 if (Buffer->getBufferSize() & 3)
5352 return error("Invalid bitcode signature");
5354 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5355 // The magic number is 0x0B17C0DE stored in little endian.
5356 if (isBitcodeWrapper(BufPtr, BufEnd))
5357 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5358 return error("Invalid bitcode wrapper header");
5360 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5361 Stream.init(&*StreamFile);
5363 return std::error_code();
5367 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5368 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5371 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5372 StreamingMemoryObject &Bytes = *OwnedBytes;
5373 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5374 Stream.init(&*StreamFile);
5376 unsigned char buf[16];
5377 if (Bytes.readBytes(buf, 16, 0) != 16)
5378 return error("Invalid bitcode signature");
5380 if (!isBitcode(buf, buf + 16))
5381 return error("Invalid bitcode signature");
5383 if (isBitcodeWrapper(buf, buf + 4)) {
5384 const unsigned char *bitcodeStart = buf;
5385 const unsigned char *bitcodeEnd = buf + 16;
5386 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5387 Bytes.dropLeadingBytes(bitcodeStart - buf);
5388 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5390 return std::error_code();
5393 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5394 const Twine &Message) {
5395 return ::error(DiagnosticHandler, make_error_code(E), Message);
5398 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5399 return ::error(DiagnosticHandler,
5400 make_error_code(BitcodeError::CorruptedBitcode), Message);
5403 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5404 return ::error(DiagnosticHandler, make_error_code(E));
5407 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5408 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5409 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5410 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
5411 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5413 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5414 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5415 bool CheckFuncSummaryPresenceOnly)
5416 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
5417 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5419 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5421 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5423 // Specialized value symbol table parser used when reading function index
5424 // blocks where we don't actually create global values.
5425 // At the end of this routine the function index is populated with a map
5426 // from function name to FunctionInfo. The function info contains
5427 // the function block's bitcode offset as well as the offset into the
5428 // function summary section.
5429 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5430 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5431 return error("Invalid record");
5433 SmallVector<uint64_t, 64> Record;
5435 // Read all the records for this value table.
5436 SmallString<128> ValueName;
5438 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5440 switch (Entry.Kind) {
5441 case BitstreamEntry::SubBlock: // Handled for us already.
5442 case BitstreamEntry::Error:
5443 return error("Malformed block");
5444 case BitstreamEntry::EndBlock:
5445 return std::error_code();
5446 case BitstreamEntry::Record:
5447 // The interesting case.
5453 switch (Stream.readRecord(Entry.ID, Record)) {
5454 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5456 case bitc::VST_CODE_FNENTRY: {
5457 // VST_FNENTRY: [valueid, offset, namechar x N]
5458 if (convertToString(Record, 2, ValueName))
5459 return error("Invalid record");
5460 unsigned ValueID = Record[0];
5461 uint64_t FuncOffset = Record[1];
5462 std::unique_ptr<FunctionInfo> FuncInfo =
5463 llvm::make_unique<FunctionInfo>(FuncOffset);
5464 if (foundFuncSummary() && !IsLazy) {
5465 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5466 SummaryMap.find(ValueID);
5467 assert(SMI != SummaryMap.end() && "Summary info not found");
5468 FuncInfo->setFunctionSummary(std::move(SMI->second));
5470 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5475 case bitc::VST_CODE_COMBINED_FNENTRY: {
5476 // VST_FNENTRY: [offset, namechar x N]
5477 if (convertToString(Record, 1, ValueName))
5478 return error("Invalid record");
5479 uint64_t FuncSummaryOffset = Record[0];
5480 std::unique_ptr<FunctionInfo> FuncInfo =
5481 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5482 if (foundFuncSummary() && !IsLazy) {
5483 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5484 SummaryMap.find(FuncSummaryOffset);
5485 assert(SMI != SummaryMap.end() && "Summary info not found");
5486 FuncInfo->setFunctionSummary(std::move(SMI->second));
5488 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5497 // Parse just the blocks needed for function index building out of the module.
5498 // At the end of this routine the function Index is populated with a map
5499 // from function name to FunctionInfo. The function info contains
5500 // either the parsed function summary information (when parsing summaries
5501 // eagerly), or just to the function summary record's offset
5502 // if parsing lazily (IsLazy).
5503 std::error_code FunctionIndexBitcodeReader::parseModule() {
5504 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5505 return error("Invalid record");
5507 // Read the function index for this module.
5509 BitstreamEntry Entry = Stream.advance();
5511 switch (Entry.Kind) {
5512 case BitstreamEntry::Error:
5513 return error("Malformed block");
5514 case BitstreamEntry::EndBlock:
5515 return std::error_code();
5517 case BitstreamEntry::SubBlock:
5518 if (CheckFuncSummaryPresenceOnly) {
5519 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5520 SeenFuncSummary = true;
5521 if (Stream.SkipBlock())
5522 return error("Invalid record");
5523 // No need to parse the rest since we found the summary.
5524 return std::error_code();
5527 default: // Skip unknown content.
5528 if (Stream.SkipBlock())
5529 return error("Invalid record");
5531 case bitc::BLOCKINFO_BLOCK_ID:
5532 // Need to parse these to get abbrev ids (e.g. for VST)
5533 if (Stream.ReadBlockInfoBlock())
5534 return error("Malformed block");
5536 case bitc::VALUE_SYMTAB_BLOCK_ID:
5537 if (std::error_code EC = parseValueSymbolTable())
5540 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5541 SeenFuncSummary = true;
5543 // Lazy parsing of summary info, skip it.
5544 if (Stream.SkipBlock())
5545 return error("Invalid record");
5546 } else if (std::error_code EC = parseEntireSummary())
5549 case bitc::MODULE_STRTAB_BLOCK_ID:
5550 if (std::error_code EC = parseModuleStringTable())
5556 case BitstreamEntry::Record:
5557 Stream.skipRecord(Entry.ID);
5563 // Eagerly parse the entire function summary block (i.e. for all functions
5564 // in the index). This populates the FunctionSummary objects in
5566 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5567 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5568 return error("Invalid record");
5570 SmallVector<uint64_t, 64> Record;
5573 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5575 switch (Entry.Kind) {
5576 case BitstreamEntry::SubBlock: // Handled for us already.
5577 case BitstreamEntry::Error:
5578 return error("Malformed block");
5579 case BitstreamEntry::EndBlock:
5580 return std::error_code();
5581 case BitstreamEntry::Record:
5582 // The interesting case.
5586 // Read a record. The record format depends on whether this
5587 // is a per-module index or a combined index file. In the per-module
5588 // case the records contain the associated value's ID for correlation
5589 // with VST entries. In the combined index the correlation is done
5590 // via the bitcode offset of the summary records (which were saved
5591 // in the combined index VST entries). The records also contain
5592 // information used for ThinLTO renaming and importing.
5594 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5595 switch (Stream.readRecord(Entry.ID, Record)) {
5596 default: // Default behavior: ignore.
5598 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5599 case bitc::FS_CODE_PERMODULE_ENTRY: {
5600 unsigned ValueID = Record[0];
5601 bool IsLocal = Record[1];
5602 unsigned InstCount = Record[2];
5603 std::unique_ptr<FunctionSummary> FS =
5604 llvm::make_unique<FunctionSummary>(InstCount);
5605 FS->setLocalFunction(IsLocal);
5606 // The module path string ref set in the summary must be owned by the
5607 // index's module string table. Since we don't have a module path
5608 // string table section in the per-module index, we create a single
5609 // module path string table entry with an empty (0) ID to take
5612 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5613 SummaryMap[ValueID] = std::move(FS);
5615 // FS_COMBINED_ENTRY: [modid, instcount]
5616 case bitc::FS_CODE_COMBINED_ENTRY: {
5617 uint64_t ModuleId = Record[0];
5618 unsigned InstCount = Record[1];
5619 std::unique_ptr<FunctionSummary> FS =
5620 llvm::make_unique<FunctionSummary>(InstCount);
5621 FS->setModulePath(ModuleIdMap[ModuleId]);
5622 SummaryMap[CurRecordBit] = std::move(FS);
5626 llvm_unreachable("Exit infinite loop");
5629 // Parse the module string table block into the Index.
5630 // This populates the ModulePathStringTable map in the index.
5631 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5632 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5633 return error("Invalid record");
5635 SmallVector<uint64_t, 64> Record;
5637 SmallString<128> ModulePath;
5639 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5641 switch (Entry.Kind) {
5642 case BitstreamEntry::SubBlock: // Handled for us already.
5643 case BitstreamEntry::Error:
5644 return error("Malformed block");
5645 case BitstreamEntry::EndBlock:
5646 return std::error_code();
5647 case BitstreamEntry::Record:
5648 // The interesting case.
5653 switch (Stream.readRecord(Entry.ID, Record)) {
5654 default: // Default behavior: ignore.
5656 case bitc::MST_CODE_ENTRY: {
5657 // MST_ENTRY: [modid, namechar x N]
5658 if (convertToString(Record, 1, ModulePath))
5659 return error("Invalid record");
5660 uint64_t ModuleId = Record[0];
5661 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5662 ModuleIdMap[ModuleId] = ModulePathInMap;
5668 llvm_unreachable("Exit infinite loop");
5671 // Parse the function info index from the bitcode streamer into the given index.
5672 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5673 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5676 if (std::error_code EC = initStream(std::move(Streamer)))
5679 // Sniff for the signature.
5680 if (!hasValidBitcodeHeader(Stream))
5681 return error("Invalid bitcode signature");
5683 // We expect a number of well-defined blocks, though we don't necessarily
5684 // need to understand them all.
5686 if (Stream.AtEndOfStream()) {
5687 // We didn't really read a proper Module block.
5688 return error("Malformed block");
5691 BitstreamEntry Entry =
5692 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5694 if (Entry.Kind != BitstreamEntry::SubBlock)
5695 return error("Malformed block");
5697 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5698 // building the function summary index.
5699 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5700 return parseModule();
5702 if (Stream.SkipBlock())
5703 return error("Invalid record");
5707 // Parse the function information at the given offset in the buffer into
5708 // the index. Used to support lazy parsing of function summaries from the
5709 // combined index during importing.
5710 // TODO: This function is not yet complete as it won't have a consumer
5711 // until ThinLTO function importing is added.
5712 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5713 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5714 size_t FunctionSummaryOffset) {
5717 if (std::error_code EC = initStream(std::move(Streamer)))
5720 // Sniff for the signature.
5721 if (!hasValidBitcodeHeader(Stream))
5722 return error("Invalid bitcode signature");
5724 Stream.JumpToBit(FunctionSummaryOffset);
5726 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5728 switch (Entry.Kind) {
5730 return error("Malformed block");
5731 case BitstreamEntry::Record:
5732 // The expected case.
5736 // TODO: Read a record. This interface will be completed when ThinLTO
5737 // importing is added so that it can be tested.
5738 SmallVector<uint64_t, 64> Record;
5739 switch (Stream.readRecord(Entry.ID, Record)) {
5740 case bitc::FS_CODE_COMBINED_ENTRY:
5742 return error("Invalid record");
5745 return std::error_code();
5749 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5751 return initLazyStream(std::move(Streamer));
5752 return initStreamFromBuffer();
5755 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5756 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5757 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5759 if (Buffer->getBufferSize() & 3)
5760 return error("Invalid bitcode signature");
5762 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5763 // The magic number is 0x0B17C0DE stored in little endian.
5764 if (isBitcodeWrapper(BufPtr, BufEnd))
5765 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5766 return error("Invalid bitcode wrapper header");
5768 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5769 Stream.init(&*StreamFile);
5771 return std::error_code();
5774 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5775 std::unique_ptr<DataStreamer> Streamer) {
5776 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5779 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5780 StreamingMemoryObject &Bytes = *OwnedBytes;
5781 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5782 Stream.init(&*StreamFile);
5784 unsigned char buf[16];
5785 if (Bytes.readBytes(buf, 16, 0) != 16)
5786 return error("Invalid bitcode signature");
5788 if (!isBitcode(buf, buf + 16))
5789 return error("Invalid bitcode signature");
5791 if (isBitcodeWrapper(buf, buf + 4)) {
5792 const unsigned char *bitcodeStart = buf;
5793 const unsigned char *bitcodeEnd = buf + 16;
5794 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5795 Bytes.dropLeadingBytes(bitcodeStart - buf);
5796 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5798 return std::error_code();
5802 class BitcodeErrorCategoryType : public std::error_category {
5803 const char *name() const LLVM_NOEXCEPT override {
5804 return "llvm.bitcode";
5806 std::string message(int IE) const override {
5807 BitcodeError E = static_cast<BitcodeError>(IE);
5809 case BitcodeError::InvalidBitcodeSignature:
5810 return "Invalid bitcode signature";
5811 case BitcodeError::CorruptedBitcode:
5812 return "Corrupted bitcode";
5814 llvm_unreachable("Unknown error type!");
5819 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5821 const std::error_category &llvm::BitcodeErrorCategory() {
5822 return *ErrorCategory;
5825 //===----------------------------------------------------------------------===//
5826 // External interface
5827 //===----------------------------------------------------------------------===//
5829 static ErrorOr<std::unique_ptr<Module>>
5830 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5831 BitcodeReader *R, LLVMContext &Context,
5832 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5833 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5834 M->setMaterializer(R);
5836 auto cleanupOnError = [&](std::error_code EC) {
5837 R->releaseBuffer(); // Never take ownership on error.
5841 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5842 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5843 ShouldLazyLoadMetadata))
5844 return cleanupOnError(EC);
5846 if (MaterializeAll) {
5847 // Read in the entire module, and destroy the BitcodeReader.
5848 if (std::error_code EC = M->materializeAllPermanently())
5849 return cleanupOnError(EC);
5851 // Resolve forward references from blockaddresses.
5852 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5853 return cleanupOnError(EC);
5855 return std::move(M);
5858 /// \brief Get a lazy one-at-time loading module from bitcode.
5860 /// This isn't always used in a lazy context. In particular, it's also used by
5861 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5862 /// in forward-referenced functions from block address references.
5864 /// \param[in] MaterializeAll Set to \c true if we should materialize
5866 static ErrorOr<std::unique_ptr<Module>>
5867 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5868 LLVMContext &Context, bool MaterializeAll,
5869 DiagnosticHandlerFunction DiagnosticHandler,
5870 bool ShouldLazyLoadMetadata = false) {
5872 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5874 ErrorOr<std::unique_ptr<Module>> Ret =
5875 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5876 MaterializeAll, ShouldLazyLoadMetadata);
5880 Buffer.release(); // The BitcodeReader owns it now.
5884 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5885 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5886 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5887 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5888 DiagnosticHandler, ShouldLazyLoadMetadata);
5891 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5892 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5893 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5894 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5895 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5897 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5901 ErrorOr<std::unique_ptr<Module>>
5902 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5903 DiagnosticHandlerFunction DiagnosticHandler) {
5904 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5905 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5907 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5908 // written. We must defer until the Module has been fully materialized.
5912 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5913 DiagnosticHandlerFunction DiagnosticHandler) {
5914 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5915 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5917 ErrorOr<std::string> Triple = R->parseTriple();
5918 if (Triple.getError())
5920 return Triple.get();
5924 llvm::getBitcodeProducerString(MemoryBufferRef Buffer, LLVMContext &Context,
5925 DiagnosticHandlerFunction DiagnosticHandler) {
5926 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5927 BitcodeReader R(Buf.release(), Context, DiagnosticHandler);
5928 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5929 if (ProducerString.getError())
5931 return ProducerString.get();
5934 // Parse the specified bitcode buffer, returning the function info index.
5935 // If IsLazy is false, parse the entire function summary into
5936 // the index. Otherwise skip the function summary section, and only create
5937 // an index object with a map from function name to function summary offset.
5938 // The index is used to perform lazy function summary reading later.
5939 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5940 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer,
5941 DiagnosticHandlerFunction DiagnosticHandler,
5942 const Module *ExportingModule, bool IsLazy) {
5943 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5944 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
5946 std::unique_ptr<FunctionInfoIndex> Index =
5947 llvm::make_unique<FunctionInfoIndex>(ExportingModule);
5949 auto cleanupOnError = [&](std::error_code EC) {
5950 R.releaseBuffer(); // Never take ownership on error.
5954 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5955 return cleanupOnError(EC);
5957 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5958 return std::move(Index);
5961 // Check if the given bitcode buffer contains a function summary block.
5962 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer,
5963 DiagnosticHandlerFunction DiagnosticHandler) {
5964 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5965 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
5967 auto cleanupOnError = [&](std::error_code EC) {
5968 R.releaseBuffer(); // Never take ownership on error.
5972 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5973 return cleanupOnError(EC);
5975 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5976 return R.foundFuncSummary();
5979 // This method supports lazy reading of function summary data from the combined
5980 // index during ThinLTO function importing. When reading the combined index
5981 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5982 // Then this method is called for each function considered for importing,
5983 // to parse the summary information for the given function name into
5985 std::error_code llvm::readFunctionSummary(
5986 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5987 StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) {
5988 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5989 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
5991 auto cleanupOnError = [&](std::error_code EC) {
5992 R.releaseBuffer(); // Never take ownership on error.
5996 // Lookup the given function name in the FunctionMap, which may
5997 // contain a list of function infos in the case of a COMDAT. Walk through
5998 // and parse each function summary info at the function summary offset
5999 // recorded when parsing the value symbol table.
6000 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
6001 size_t FunctionSummaryOffset = FI->bitcodeIndex();
6002 if (std::error_code EC =
6003 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
6004 return cleanupOnError(EC);
6007 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
6008 return std::error_code();