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 parseMetadataAttachment(Function &F);
409 ErrorOr<std::string> parseModuleTriple();
410 std::error_code parseUseLists();
411 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
412 std::error_code initStreamFromBuffer();
413 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
414 std::error_code findFunctionInStream(
416 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
419 /// Class to manage reading and parsing function summary index bitcode
421 class FunctionIndexBitcodeReader {
422 DiagnosticHandlerFunction DiagnosticHandler;
424 /// Eventually points to the function index built during parsing.
425 FunctionInfoIndex *TheIndex = nullptr;
427 std::unique_ptr<MemoryBuffer> Buffer;
428 std::unique_ptr<BitstreamReader> StreamFile;
429 BitstreamCursor Stream;
431 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
433 /// If false, the summary section is fully parsed into the index during
434 /// the initial parse. Otherwise, if true, the caller is expected to
435 /// invoke \a readFunctionSummary for each summary needed, and the summary
436 /// section is thus parsed lazily.
439 /// Used to indicate whether caller only wants to check for the presence
440 /// of the function summary bitcode section. All blocks are skipped,
441 /// but the SeenFuncSummary boolean is set.
442 bool CheckFuncSummaryPresenceOnly = false;
444 /// Indicates whether we have encountered a function summary section
445 /// yet during parsing, used when checking if file contains function
447 bool SeenFuncSummary = false;
449 /// \brief Map populated during function summary section parsing, and
450 /// consumed during ValueSymbolTable parsing.
452 /// Used to correlate summary records with VST entries. For the per-module
453 /// index this maps the ValueID to the parsed function summary, and
454 /// for the combined index this maps the summary record's bitcode
455 /// offset to the function summary (since in the combined index the
456 /// VST records do not hold value IDs but rather hold the function
457 /// summary record offset).
458 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
460 /// Map populated during module path string table parsing, from the
461 /// module ID to a string reference owned by the index's module
462 /// path string table, used to correlate with combined index function
464 DenseMap<uint64_t, StringRef> ModuleIdMap;
467 std::error_code error(BitcodeError E, const Twine &Message);
468 std::error_code error(BitcodeError E);
469 std::error_code error(const Twine &Message);
471 FunctionIndexBitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
472 DiagnosticHandlerFunction DiagnosticHandler,
474 bool CheckFuncSummaryPresenceOnly = false);
475 FunctionIndexBitcodeReader(LLVMContext &Context,
476 DiagnosticHandlerFunction DiagnosticHandler,
478 bool CheckFuncSummaryPresenceOnly = false);
479 ~FunctionIndexBitcodeReader() { freeState(); }
483 void releaseBuffer();
485 /// Check if the parser has encountered a function summary section.
486 bool foundFuncSummary() { return SeenFuncSummary; }
488 /// \brief Main interface to parsing a bitcode buffer.
489 /// \returns true if an error occurred.
490 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
491 FunctionInfoIndex *I);
493 /// \brief Interface for parsing a function summary lazily.
494 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
495 FunctionInfoIndex *I,
496 size_t FunctionSummaryOffset);
499 std::error_code parseModule();
500 std::error_code parseValueSymbolTable();
501 std::error_code parseEntireSummary();
502 std::error_code parseModuleStringTable();
503 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
504 std::error_code initStreamFromBuffer();
505 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
509 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
510 DiagnosticSeverity Severity,
512 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
514 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
516 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
517 std::error_code EC, const Twine &Message) {
518 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
519 DiagnosticHandler(DI);
523 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
524 std::error_code EC) {
525 return error(DiagnosticHandler, EC, EC.message());
528 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
529 const Twine &Message) {
530 return error(DiagnosticHandler,
531 make_error_code(BitcodeError::CorruptedBitcode), Message);
534 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
535 if (!ProducerIdentification.empty()) {
536 return ::error(DiagnosticHandler, make_error_code(E),
537 Message + " (Producer: '" + ProducerIdentification +
538 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
540 return ::error(DiagnosticHandler, make_error_code(E), Message);
543 std::error_code BitcodeReader::error(const Twine &Message) {
544 if (!ProducerIdentification.empty()) {
545 return ::error(DiagnosticHandler,
546 make_error_code(BitcodeError::CorruptedBitcode),
547 Message + " (Producer: '" + ProducerIdentification +
548 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
550 return ::error(DiagnosticHandler,
551 make_error_code(BitcodeError::CorruptedBitcode), Message);
554 std::error_code BitcodeReader::error(BitcodeError E) {
555 return ::error(DiagnosticHandler, make_error_code(E));
558 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
562 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
565 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
566 DiagnosticHandlerFunction DiagnosticHandler)
568 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
569 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
571 BitcodeReader::BitcodeReader(LLVMContext &Context,
572 DiagnosticHandlerFunction DiagnosticHandler)
574 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
575 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
577 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
578 if (WillMaterializeAllForwardRefs)
579 return std::error_code();
581 // Prevent recursion.
582 WillMaterializeAllForwardRefs = true;
584 while (!BasicBlockFwdRefQueue.empty()) {
585 Function *F = BasicBlockFwdRefQueue.front();
586 BasicBlockFwdRefQueue.pop_front();
587 assert(F && "Expected valid function");
588 if (!BasicBlockFwdRefs.count(F))
589 // Already materialized.
592 // Check for a function that isn't materializable to prevent an infinite
593 // loop. When parsing a blockaddress stored in a global variable, there
594 // isn't a trivial way to check if a function will have a body without a
595 // linear search through FunctionsWithBodies, so just check it here.
596 if (!F->isMaterializable())
597 return error("Never resolved function from blockaddress");
599 // Try to materialize F.
600 if (std::error_code EC = materialize(F))
603 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
606 WillMaterializeAllForwardRefs = false;
607 return std::error_code();
610 void BitcodeReader::freeState() {
612 std::vector<Type*>().swap(TypeList);
615 std::vector<Comdat *>().swap(ComdatList);
617 std::vector<AttributeSet>().swap(MAttributes);
618 std::vector<BasicBlock*>().swap(FunctionBBs);
619 std::vector<Function*>().swap(FunctionsWithBodies);
620 DeferredFunctionInfo.clear();
621 DeferredMetadataInfo.clear();
624 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
625 BasicBlockFwdRefQueue.clear();
628 //===----------------------------------------------------------------------===//
629 // Helper functions to implement forward reference resolution, etc.
630 //===----------------------------------------------------------------------===//
632 /// Convert a string from a record into an std::string, return true on failure.
633 template <typename StrTy>
634 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
636 if (Idx > Record.size())
639 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
640 Result += (char)Record[i];
644 static bool hasImplicitComdat(size_t Val) {
648 case 1: // Old WeakAnyLinkage
649 case 4: // Old LinkOnceAnyLinkage
650 case 10: // Old WeakODRLinkage
651 case 11: // Old LinkOnceODRLinkage
656 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
658 default: // Map unknown/new linkages to external
660 return GlobalValue::ExternalLinkage;
662 return GlobalValue::AppendingLinkage;
664 return GlobalValue::InternalLinkage;
666 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
668 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
670 return GlobalValue::ExternalWeakLinkage;
672 return GlobalValue::CommonLinkage;
674 return GlobalValue::PrivateLinkage;
676 return GlobalValue::AvailableExternallyLinkage;
678 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
680 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
682 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
683 case 1: // Old value with implicit comdat.
685 return GlobalValue::WeakAnyLinkage;
686 case 10: // Old value with implicit comdat.
688 return GlobalValue::WeakODRLinkage;
689 case 4: // Old value with implicit comdat.
691 return GlobalValue::LinkOnceAnyLinkage;
692 case 11: // Old value with implicit comdat.
694 return GlobalValue::LinkOnceODRLinkage;
698 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
700 default: // Map unknown visibilities to default.
701 case 0: return GlobalValue::DefaultVisibility;
702 case 1: return GlobalValue::HiddenVisibility;
703 case 2: return GlobalValue::ProtectedVisibility;
707 static GlobalValue::DLLStorageClassTypes
708 getDecodedDLLStorageClass(unsigned Val) {
710 default: // Map unknown values to default.
711 case 0: return GlobalValue::DefaultStorageClass;
712 case 1: return GlobalValue::DLLImportStorageClass;
713 case 2: return GlobalValue::DLLExportStorageClass;
717 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
719 case 0: return GlobalVariable::NotThreadLocal;
720 default: // Map unknown non-zero value to general dynamic.
721 case 1: return GlobalVariable::GeneralDynamicTLSModel;
722 case 2: return GlobalVariable::LocalDynamicTLSModel;
723 case 3: return GlobalVariable::InitialExecTLSModel;
724 case 4: return GlobalVariable::LocalExecTLSModel;
728 static int getDecodedCastOpcode(unsigned Val) {
731 case bitc::CAST_TRUNC : return Instruction::Trunc;
732 case bitc::CAST_ZEXT : return Instruction::ZExt;
733 case bitc::CAST_SEXT : return Instruction::SExt;
734 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
735 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
736 case bitc::CAST_UITOFP : return Instruction::UIToFP;
737 case bitc::CAST_SITOFP : return Instruction::SIToFP;
738 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
739 case bitc::CAST_FPEXT : return Instruction::FPExt;
740 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
741 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
742 case bitc::CAST_BITCAST : return Instruction::BitCast;
743 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
747 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
748 bool IsFP = Ty->isFPOrFPVectorTy();
749 // BinOps are only valid for int/fp or vector of int/fp types
750 if (!IsFP && !Ty->isIntOrIntVectorTy())
756 case bitc::BINOP_ADD:
757 return IsFP ? Instruction::FAdd : Instruction::Add;
758 case bitc::BINOP_SUB:
759 return IsFP ? Instruction::FSub : Instruction::Sub;
760 case bitc::BINOP_MUL:
761 return IsFP ? Instruction::FMul : Instruction::Mul;
762 case bitc::BINOP_UDIV:
763 return IsFP ? -1 : Instruction::UDiv;
764 case bitc::BINOP_SDIV:
765 return IsFP ? Instruction::FDiv : Instruction::SDiv;
766 case bitc::BINOP_UREM:
767 return IsFP ? -1 : Instruction::URem;
768 case bitc::BINOP_SREM:
769 return IsFP ? Instruction::FRem : Instruction::SRem;
770 case bitc::BINOP_SHL:
771 return IsFP ? -1 : Instruction::Shl;
772 case bitc::BINOP_LSHR:
773 return IsFP ? -1 : Instruction::LShr;
774 case bitc::BINOP_ASHR:
775 return IsFP ? -1 : Instruction::AShr;
776 case bitc::BINOP_AND:
777 return IsFP ? -1 : Instruction::And;
779 return IsFP ? -1 : Instruction::Or;
780 case bitc::BINOP_XOR:
781 return IsFP ? -1 : Instruction::Xor;
785 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
787 default: return AtomicRMWInst::BAD_BINOP;
788 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
789 case bitc::RMW_ADD: return AtomicRMWInst::Add;
790 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
791 case bitc::RMW_AND: return AtomicRMWInst::And;
792 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
793 case bitc::RMW_OR: return AtomicRMWInst::Or;
794 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
795 case bitc::RMW_MAX: return AtomicRMWInst::Max;
796 case bitc::RMW_MIN: return AtomicRMWInst::Min;
797 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
798 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
802 static AtomicOrdering getDecodedOrdering(unsigned Val) {
804 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
805 case bitc::ORDERING_UNORDERED: return Unordered;
806 case bitc::ORDERING_MONOTONIC: return Monotonic;
807 case bitc::ORDERING_ACQUIRE: return Acquire;
808 case bitc::ORDERING_RELEASE: return Release;
809 case bitc::ORDERING_ACQREL: return AcquireRelease;
810 default: // Map unknown orderings to sequentially-consistent.
811 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
815 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
817 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
818 default: // Map unknown scopes to cross-thread.
819 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
823 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
825 default: // Map unknown selection kinds to any.
826 case bitc::COMDAT_SELECTION_KIND_ANY:
828 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
829 return Comdat::ExactMatch;
830 case bitc::COMDAT_SELECTION_KIND_LARGEST:
831 return Comdat::Largest;
832 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
833 return Comdat::NoDuplicates;
834 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
835 return Comdat::SameSize;
839 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
841 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
842 FMF.setUnsafeAlgebra();
843 if (0 != (Val & FastMathFlags::NoNaNs))
845 if (0 != (Val & FastMathFlags::NoInfs))
847 if (0 != (Val & FastMathFlags::NoSignedZeros))
848 FMF.setNoSignedZeros();
849 if (0 != (Val & FastMathFlags::AllowReciprocal))
850 FMF.setAllowReciprocal();
854 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
856 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
857 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
863 /// \brief A class for maintaining the slot number definition
864 /// as a placeholder for the actual definition for forward constants defs.
865 class ConstantPlaceHolder : public ConstantExpr {
866 void operator=(const ConstantPlaceHolder &) = delete;
869 // allocate space for exactly one operand
870 void *operator new(size_t s) { return User::operator new(s, 1); }
871 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
872 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
873 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
876 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
877 static bool classof(const Value *V) {
878 return isa<ConstantExpr>(V) &&
879 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
882 /// Provide fast operand accessors
883 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
887 // FIXME: can we inherit this from ConstantExpr?
889 struct OperandTraits<ConstantPlaceHolder> :
890 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
892 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
895 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
904 WeakVH &OldV = ValuePtrs[Idx];
910 // Handle constants and non-constants (e.g. instrs) differently for
912 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
913 ResolveConstants.push_back(std::make_pair(PHC, Idx));
916 // If there was a forward reference to this value, replace it.
917 Value *PrevVal = OldV;
918 // Check operator constraints. We only put cleanuppads or catchpads in
919 // the forward value map if the value is constrained to match.
920 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
921 if (!isa<CatchPadInst>(V))
923 // Delete the dummy basic block that was created with the sentinel
925 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
926 assert(DummyBlock == CatchPad->getNormalDest());
927 CatchPad->dropAllReferences();
929 } else if (isa<CleanupPadInst>(PrevVal)) {
930 if (!isa<CleanupPadInst>(V))
933 OldV->replaceAllUsesWith(V);
941 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
946 if (Value *V = ValuePtrs[Idx]) {
947 if (Ty != V->getType())
948 report_fatal_error("Type mismatch in constant table!");
949 return cast<Constant>(V);
952 // Create and return a placeholder, which will later be RAUW'd.
953 Constant *C = new ConstantPlaceHolder(Ty, Context);
958 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
959 OperatorConstraint OC) {
960 // Bail out for a clearly invalid value. This would make us call resize(0)
967 if (Value *V = ValuePtrs[Idx]) {
968 // If the types don't match, it's invalid.
969 if (Ty && Ty != V->getType())
973 // Use dyn_cast to enforce operator constraints
976 return dyn_cast<CatchPadInst>(V);
978 return dyn_cast<CleanupPadInst>(V);
980 llvm_unreachable("Unexpected operator constraint");
984 // No type specified, must be invalid reference.
985 if (!Ty) return nullptr;
987 // Create and return a placeholder, which will later be RAUW'd.
991 V = new Argument(Ty);
994 BasicBlock *BB = BasicBlock::Create(Context);
995 V = CatchPadInst::Create(BB, BB, {});
999 assert(OC == OC_CleanupPad && "unexpected operator constraint");
1000 V = CleanupPadInst::Create(Context, {});
1008 /// Once all constants are read, this method bulk resolves any forward
1009 /// references. The idea behind this is that we sometimes get constants (such
1010 /// as large arrays) which reference *many* forward ref constants. Replacing
1011 /// each of these causes a lot of thrashing when building/reuniquing the
1012 /// constant. Instead of doing this, we look at all the uses and rewrite all
1013 /// the place holders at once for any constant that uses a placeholder.
1014 void BitcodeReaderValueList::resolveConstantForwardRefs() {
1015 // Sort the values by-pointer so that they are efficient to look up with a
1017 std::sort(ResolveConstants.begin(), ResolveConstants.end());
1019 SmallVector<Constant*, 64> NewOps;
1021 while (!ResolveConstants.empty()) {
1022 Value *RealVal = operator[](ResolveConstants.back().second);
1023 Constant *Placeholder = ResolveConstants.back().first;
1024 ResolveConstants.pop_back();
1026 // Loop over all users of the placeholder, updating them to reference the
1027 // new value. If they reference more than one placeholder, update them all
1029 while (!Placeholder->use_empty()) {
1030 auto UI = Placeholder->user_begin();
1033 // If the using object isn't uniqued, just update the operands. This
1034 // handles instructions and initializers for global variables.
1035 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1036 UI.getUse().set(RealVal);
1040 // Otherwise, we have a constant that uses the placeholder. Replace that
1041 // constant with a new constant that has *all* placeholder uses updated.
1042 Constant *UserC = cast<Constant>(U);
1043 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1046 if (!isa<ConstantPlaceHolder>(*I)) {
1047 // Not a placeholder reference.
1049 } else if (*I == Placeholder) {
1050 // Common case is that it just references this one placeholder.
1053 // Otherwise, look up the placeholder in ResolveConstants.
1054 ResolveConstantsTy::iterator It =
1055 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1056 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1058 assert(It != ResolveConstants.end() && It->first == *I);
1059 NewOp = operator[](It->second);
1062 NewOps.push_back(cast<Constant>(NewOp));
1065 // Make the new constant.
1067 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1068 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1069 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1070 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1071 } else if (isa<ConstantVector>(UserC)) {
1072 NewC = ConstantVector::get(NewOps);
1074 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1075 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1078 UserC->replaceAllUsesWith(NewC);
1079 UserC->destroyConstant();
1083 // Update all ValueHandles, they should be the only users at this point.
1084 Placeholder->replaceAllUsesWith(RealVal);
1089 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1090 if (Idx == size()) {
1098 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1104 // If there was a forward reference to this value, replace it.
1105 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1106 PrevMD->replaceAllUsesWith(MD);
1110 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1114 if (Metadata *MD = MDValuePtrs[Idx])
1117 // Track forward refs to be resolved later.
1119 MinFwdRef = std::min(MinFwdRef, Idx);
1120 MaxFwdRef = std::max(MaxFwdRef, Idx);
1123 MinFwdRef = MaxFwdRef = Idx;
1127 // Create and return a placeholder, which will later be RAUW'd.
1128 Metadata *MD = MDNode::getTemporary(Context, None).release();
1129 MDValuePtrs[Idx].reset(MD);
1133 void BitcodeReaderMDValueList::tryToResolveCycles() {
1139 // Still forward references... can't resolve cycles.
1142 // Resolve any cycles.
1143 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1144 auto &MD = MDValuePtrs[I];
1145 auto *N = dyn_cast_or_null<MDNode>(MD);
1149 assert(!N->isTemporary() && "Unexpected forward reference");
1153 // Make sure we return early again until there's another forward ref.
1157 Type *BitcodeReader::getTypeByID(unsigned ID) {
1158 // The type table size is always specified correctly.
1159 if (ID >= TypeList.size())
1162 if (Type *Ty = TypeList[ID])
1165 // If we have a forward reference, the only possible case is when it is to a
1166 // named struct. Just create a placeholder for now.
1167 return TypeList[ID] = createIdentifiedStructType(Context);
1170 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1172 auto *Ret = StructType::create(Context, Name);
1173 IdentifiedStructTypes.push_back(Ret);
1177 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1178 auto *Ret = StructType::create(Context);
1179 IdentifiedStructTypes.push_back(Ret);
1184 //===----------------------------------------------------------------------===//
1185 // Functions for parsing blocks from the bitcode file
1186 //===----------------------------------------------------------------------===//
1189 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1190 /// been decoded from the given integer. This function must stay in sync with
1191 /// 'encodeLLVMAttributesForBitcode'.
1192 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1193 uint64_t EncodedAttrs) {
1194 // FIXME: Remove in 4.0.
1196 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1197 // the bits above 31 down by 11 bits.
1198 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1199 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1200 "Alignment must be a power of two.");
1203 B.addAlignmentAttr(Alignment);
1204 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1205 (EncodedAttrs & 0xffff));
1208 std::error_code BitcodeReader::parseAttributeBlock() {
1209 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1210 return error("Invalid record");
1212 if (!MAttributes.empty())
1213 return error("Invalid multiple blocks");
1215 SmallVector<uint64_t, 64> Record;
1217 SmallVector<AttributeSet, 8> Attrs;
1219 // Read all the records.
1221 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1223 switch (Entry.Kind) {
1224 case BitstreamEntry::SubBlock: // Handled for us already.
1225 case BitstreamEntry::Error:
1226 return error("Malformed block");
1227 case BitstreamEntry::EndBlock:
1228 return std::error_code();
1229 case BitstreamEntry::Record:
1230 // The interesting case.
1236 switch (Stream.readRecord(Entry.ID, Record)) {
1237 default: // Default behavior: ignore.
1239 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1240 // FIXME: Remove in 4.0.
1241 if (Record.size() & 1)
1242 return error("Invalid record");
1244 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1246 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1247 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1250 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1254 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1255 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1256 Attrs.push_back(MAttributeGroups[Record[i]]);
1258 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1266 // Returns Attribute::None on unrecognized codes.
1267 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1270 return Attribute::None;
1271 case bitc::ATTR_KIND_ALIGNMENT:
1272 return Attribute::Alignment;
1273 case bitc::ATTR_KIND_ALWAYS_INLINE:
1274 return Attribute::AlwaysInline;
1275 case bitc::ATTR_KIND_ARGMEMONLY:
1276 return Attribute::ArgMemOnly;
1277 case bitc::ATTR_KIND_BUILTIN:
1278 return Attribute::Builtin;
1279 case bitc::ATTR_KIND_BY_VAL:
1280 return Attribute::ByVal;
1281 case bitc::ATTR_KIND_IN_ALLOCA:
1282 return Attribute::InAlloca;
1283 case bitc::ATTR_KIND_COLD:
1284 return Attribute::Cold;
1285 case bitc::ATTR_KIND_CONVERGENT:
1286 return Attribute::Convergent;
1287 case bitc::ATTR_KIND_INLINE_HINT:
1288 return Attribute::InlineHint;
1289 case bitc::ATTR_KIND_IN_REG:
1290 return Attribute::InReg;
1291 case bitc::ATTR_KIND_JUMP_TABLE:
1292 return Attribute::JumpTable;
1293 case bitc::ATTR_KIND_MIN_SIZE:
1294 return Attribute::MinSize;
1295 case bitc::ATTR_KIND_NAKED:
1296 return Attribute::Naked;
1297 case bitc::ATTR_KIND_NEST:
1298 return Attribute::Nest;
1299 case bitc::ATTR_KIND_NO_ALIAS:
1300 return Attribute::NoAlias;
1301 case bitc::ATTR_KIND_NO_BUILTIN:
1302 return Attribute::NoBuiltin;
1303 case bitc::ATTR_KIND_NO_CAPTURE:
1304 return Attribute::NoCapture;
1305 case bitc::ATTR_KIND_NO_DUPLICATE:
1306 return Attribute::NoDuplicate;
1307 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1308 return Attribute::NoImplicitFloat;
1309 case bitc::ATTR_KIND_NO_INLINE:
1310 return Attribute::NoInline;
1311 case bitc::ATTR_KIND_NO_RECURSE:
1312 return Attribute::NoRecurse;
1313 case bitc::ATTR_KIND_NON_LAZY_BIND:
1314 return Attribute::NonLazyBind;
1315 case bitc::ATTR_KIND_NON_NULL:
1316 return Attribute::NonNull;
1317 case bitc::ATTR_KIND_DEREFERENCEABLE:
1318 return Attribute::Dereferenceable;
1319 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1320 return Attribute::DereferenceableOrNull;
1321 case bitc::ATTR_KIND_NO_RED_ZONE:
1322 return Attribute::NoRedZone;
1323 case bitc::ATTR_KIND_NO_RETURN:
1324 return Attribute::NoReturn;
1325 case bitc::ATTR_KIND_NO_UNWIND:
1326 return Attribute::NoUnwind;
1327 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1328 return Attribute::OptimizeForSize;
1329 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1330 return Attribute::OptimizeNone;
1331 case bitc::ATTR_KIND_READ_NONE:
1332 return Attribute::ReadNone;
1333 case bitc::ATTR_KIND_READ_ONLY:
1334 return Attribute::ReadOnly;
1335 case bitc::ATTR_KIND_RETURNED:
1336 return Attribute::Returned;
1337 case bitc::ATTR_KIND_RETURNS_TWICE:
1338 return Attribute::ReturnsTwice;
1339 case bitc::ATTR_KIND_S_EXT:
1340 return Attribute::SExt;
1341 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1342 return Attribute::StackAlignment;
1343 case bitc::ATTR_KIND_STACK_PROTECT:
1344 return Attribute::StackProtect;
1345 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1346 return Attribute::StackProtectReq;
1347 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1348 return Attribute::StackProtectStrong;
1349 case bitc::ATTR_KIND_SAFESTACK:
1350 return Attribute::SafeStack;
1351 case bitc::ATTR_KIND_STRUCT_RET:
1352 return Attribute::StructRet;
1353 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1354 return Attribute::SanitizeAddress;
1355 case bitc::ATTR_KIND_SANITIZE_THREAD:
1356 return Attribute::SanitizeThread;
1357 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1358 return Attribute::SanitizeMemory;
1359 case bitc::ATTR_KIND_UW_TABLE:
1360 return Attribute::UWTable;
1361 case bitc::ATTR_KIND_Z_EXT:
1362 return Attribute::ZExt;
1366 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1367 unsigned &Alignment) {
1368 // Note: Alignment in bitcode files is incremented by 1, so that zero
1369 // can be used for default alignment.
1370 if (Exponent > Value::MaxAlignmentExponent + 1)
1371 return error("Invalid alignment value");
1372 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1373 return std::error_code();
1376 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1377 Attribute::AttrKind *Kind) {
1378 *Kind = getAttrFromCode(Code);
1379 if (*Kind == Attribute::None)
1380 return error(BitcodeError::CorruptedBitcode,
1381 "Unknown attribute kind (" + Twine(Code) + ")");
1382 return std::error_code();
1385 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1386 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1387 return error("Invalid record");
1389 if (!MAttributeGroups.empty())
1390 return error("Invalid multiple blocks");
1392 SmallVector<uint64_t, 64> Record;
1394 // Read all the records.
1396 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1398 switch (Entry.Kind) {
1399 case BitstreamEntry::SubBlock: // Handled for us already.
1400 case BitstreamEntry::Error:
1401 return error("Malformed block");
1402 case BitstreamEntry::EndBlock:
1403 return std::error_code();
1404 case BitstreamEntry::Record:
1405 // The interesting case.
1411 switch (Stream.readRecord(Entry.ID, Record)) {
1412 default: // Default behavior: ignore.
1414 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1415 if (Record.size() < 3)
1416 return error("Invalid record");
1418 uint64_t GrpID = Record[0];
1419 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1422 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1423 if (Record[i] == 0) { // Enum attribute
1424 Attribute::AttrKind Kind;
1425 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1428 B.addAttribute(Kind);
1429 } else if (Record[i] == 1) { // Integer attribute
1430 Attribute::AttrKind Kind;
1431 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1433 if (Kind == Attribute::Alignment)
1434 B.addAlignmentAttr(Record[++i]);
1435 else if (Kind == Attribute::StackAlignment)
1436 B.addStackAlignmentAttr(Record[++i]);
1437 else if (Kind == Attribute::Dereferenceable)
1438 B.addDereferenceableAttr(Record[++i]);
1439 else if (Kind == Attribute::DereferenceableOrNull)
1440 B.addDereferenceableOrNullAttr(Record[++i]);
1441 } else { // String attribute
1442 assert((Record[i] == 3 || Record[i] == 4) &&
1443 "Invalid attribute group entry");
1444 bool HasValue = (Record[i++] == 4);
1445 SmallString<64> KindStr;
1446 SmallString<64> ValStr;
1448 while (Record[i] != 0 && i != e)
1449 KindStr += Record[i++];
1450 assert(Record[i] == 0 && "Kind string not null terminated");
1453 // Has a value associated with it.
1454 ++i; // Skip the '0' that terminates the "kind" string.
1455 while (Record[i] != 0 && i != e)
1456 ValStr += Record[i++];
1457 assert(Record[i] == 0 && "Value string not null terminated");
1460 B.addAttribute(KindStr.str(), ValStr.str());
1464 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1471 std::error_code BitcodeReader::parseTypeTable() {
1472 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1473 return error("Invalid record");
1475 return parseTypeTableBody();
1478 std::error_code BitcodeReader::parseTypeTableBody() {
1479 if (!TypeList.empty())
1480 return error("Invalid multiple blocks");
1482 SmallVector<uint64_t, 64> Record;
1483 unsigned NumRecords = 0;
1485 SmallString<64> TypeName;
1487 // Read all the records for this type table.
1489 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1491 switch (Entry.Kind) {
1492 case BitstreamEntry::SubBlock: // Handled for us already.
1493 case BitstreamEntry::Error:
1494 return error("Malformed block");
1495 case BitstreamEntry::EndBlock:
1496 if (NumRecords != TypeList.size())
1497 return error("Malformed block");
1498 return std::error_code();
1499 case BitstreamEntry::Record:
1500 // The interesting case.
1506 Type *ResultTy = nullptr;
1507 switch (Stream.readRecord(Entry.ID, Record)) {
1509 return error("Invalid value");
1510 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1511 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1512 // type list. This allows us to reserve space.
1513 if (Record.size() < 1)
1514 return error("Invalid record");
1515 TypeList.resize(Record[0]);
1517 case bitc::TYPE_CODE_VOID: // VOID
1518 ResultTy = Type::getVoidTy(Context);
1520 case bitc::TYPE_CODE_HALF: // HALF
1521 ResultTy = Type::getHalfTy(Context);
1523 case bitc::TYPE_CODE_FLOAT: // FLOAT
1524 ResultTy = Type::getFloatTy(Context);
1526 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1527 ResultTy = Type::getDoubleTy(Context);
1529 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1530 ResultTy = Type::getX86_FP80Ty(Context);
1532 case bitc::TYPE_CODE_FP128: // FP128
1533 ResultTy = Type::getFP128Ty(Context);
1535 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1536 ResultTy = Type::getPPC_FP128Ty(Context);
1538 case bitc::TYPE_CODE_LABEL: // LABEL
1539 ResultTy = Type::getLabelTy(Context);
1541 case bitc::TYPE_CODE_METADATA: // METADATA
1542 ResultTy = Type::getMetadataTy(Context);
1544 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1545 ResultTy = Type::getX86_MMXTy(Context);
1547 case bitc::TYPE_CODE_TOKEN: // TOKEN
1548 ResultTy = Type::getTokenTy(Context);
1550 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1551 if (Record.size() < 1)
1552 return error("Invalid record");
1554 uint64_t NumBits = Record[0];
1555 if (NumBits < IntegerType::MIN_INT_BITS ||
1556 NumBits > IntegerType::MAX_INT_BITS)
1557 return error("Bitwidth for integer type out of range");
1558 ResultTy = IntegerType::get(Context, NumBits);
1561 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1562 // [pointee type, address space]
1563 if (Record.size() < 1)
1564 return error("Invalid record");
1565 unsigned AddressSpace = 0;
1566 if (Record.size() == 2)
1567 AddressSpace = Record[1];
1568 ResultTy = getTypeByID(Record[0]);
1570 !PointerType::isValidElementType(ResultTy))
1571 return error("Invalid type");
1572 ResultTy = PointerType::get(ResultTy, AddressSpace);
1575 case bitc::TYPE_CODE_FUNCTION_OLD: {
1576 // FIXME: attrid is dead, remove it in LLVM 4.0
1577 // FUNCTION: [vararg, attrid, retty, paramty x N]
1578 if (Record.size() < 3)
1579 return error("Invalid record");
1580 SmallVector<Type*, 8> ArgTys;
1581 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1582 if (Type *T = getTypeByID(Record[i]))
1583 ArgTys.push_back(T);
1588 ResultTy = getTypeByID(Record[2]);
1589 if (!ResultTy || ArgTys.size() < Record.size()-3)
1590 return error("Invalid type");
1592 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1595 case bitc::TYPE_CODE_FUNCTION: {
1596 // FUNCTION: [vararg, retty, paramty x N]
1597 if (Record.size() < 2)
1598 return error("Invalid record");
1599 SmallVector<Type*, 8> ArgTys;
1600 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1601 if (Type *T = getTypeByID(Record[i])) {
1602 if (!FunctionType::isValidArgumentType(T))
1603 return error("Invalid function argument type");
1604 ArgTys.push_back(T);
1610 ResultTy = getTypeByID(Record[1]);
1611 if (!ResultTy || ArgTys.size() < Record.size()-2)
1612 return error("Invalid type");
1614 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1617 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1618 if (Record.size() < 1)
1619 return error("Invalid record");
1620 SmallVector<Type*, 8> EltTys;
1621 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1622 if (Type *T = getTypeByID(Record[i]))
1623 EltTys.push_back(T);
1627 if (EltTys.size() != Record.size()-1)
1628 return error("Invalid type");
1629 ResultTy = StructType::get(Context, EltTys, Record[0]);
1632 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1633 if (convertToString(Record, 0, TypeName))
1634 return error("Invalid record");
1637 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1638 if (Record.size() < 1)
1639 return error("Invalid record");
1641 if (NumRecords >= TypeList.size())
1642 return error("Invalid TYPE table");
1644 // Check to see if this was forward referenced, if so fill in the temp.
1645 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1647 Res->setName(TypeName);
1648 TypeList[NumRecords] = nullptr;
1649 } else // Otherwise, create a new struct.
1650 Res = createIdentifiedStructType(Context, TypeName);
1653 SmallVector<Type*, 8> EltTys;
1654 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1655 if (Type *T = getTypeByID(Record[i]))
1656 EltTys.push_back(T);
1660 if (EltTys.size() != Record.size()-1)
1661 return error("Invalid record");
1662 Res->setBody(EltTys, Record[0]);
1666 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1667 if (Record.size() != 1)
1668 return error("Invalid record");
1670 if (NumRecords >= TypeList.size())
1671 return error("Invalid TYPE table");
1673 // Check to see if this was forward referenced, if so fill in the temp.
1674 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1676 Res->setName(TypeName);
1677 TypeList[NumRecords] = nullptr;
1678 } else // Otherwise, create a new struct with no body.
1679 Res = createIdentifiedStructType(Context, TypeName);
1684 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1685 if (Record.size() < 2)
1686 return error("Invalid record");
1687 ResultTy = getTypeByID(Record[1]);
1688 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1689 return error("Invalid type");
1690 ResultTy = ArrayType::get(ResultTy, Record[0]);
1692 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1693 if (Record.size() < 2)
1694 return error("Invalid record");
1696 return error("Invalid vector length");
1697 ResultTy = getTypeByID(Record[1]);
1698 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1699 return error("Invalid type");
1700 ResultTy = VectorType::get(ResultTy, Record[0]);
1704 if (NumRecords >= TypeList.size())
1705 return error("Invalid TYPE table");
1706 if (TypeList[NumRecords])
1708 "Invalid TYPE table: Only named structs can be forward referenced");
1709 assert(ResultTy && "Didn't read a type?");
1710 TypeList[NumRecords++] = ResultTy;
1714 std::error_code BitcodeReader::parseOperandBundleTags() {
1715 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1716 return error("Invalid record");
1718 if (!BundleTags.empty())
1719 return error("Invalid multiple blocks");
1721 SmallVector<uint64_t, 64> Record;
1724 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1726 switch (Entry.Kind) {
1727 case BitstreamEntry::SubBlock: // Handled for us already.
1728 case BitstreamEntry::Error:
1729 return error("Malformed block");
1730 case BitstreamEntry::EndBlock:
1731 return std::error_code();
1732 case BitstreamEntry::Record:
1733 // The interesting case.
1737 // Tags are implicitly mapped to integers by their order.
1739 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1740 return error("Invalid record");
1742 // OPERAND_BUNDLE_TAG: [strchr x N]
1743 BundleTags.emplace_back();
1744 if (convertToString(Record, 0, BundleTags.back()))
1745 return error("Invalid record");
1750 /// Associate a value with its name from the given index in the provided record.
1751 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1752 unsigned NameIndex, Triple &TT) {
1753 SmallString<128> ValueName;
1754 if (convertToString(Record, NameIndex, ValueName))
1755 return error("Invalid record");
1756 unsigned ValueID = Record[0];
1757 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1758 return error("Invalid record");
1759 Value *V = ValueList[ValueID];
1761 StringRef NameStr(ValueName.data(), ValueName.size());
1762 if (NameStr.find_first_of(0) != StringRef::npos)
1763 return error("Invalid value name");
1764 V->setName(NameStr);
1765 auto *GO = dyn_cast<GlobalObject>(V);
1767 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1768 if (TT.isOSBinFormatMachO())
1769 GO->setComdat(nullptr);
1771 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1777 /// Parse the value symbol table at either the current parsing location or
1778 /// at the given bit offset if provided.
1779 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1780 uint64_t CurrentBit;
1781 // Pass in the Offset to distinguish between calling for the module-level
1782 // VST (where we want to jump to the VST offset) and the function-level
1783 // VST (where we don't).
1785 // Save the current parsing location so we can jump back at the end
1787 CurrentBit = Stream.GetCurrentBitNo();
1788 Stream.JumpToBit(Offset * 32);
1790 // Do some checking if we are in debug mode.
1791 BitstreamEntry Entry = Stream.advance();
1792 assert(Entry.Kind == BitstreamEntry::SubBlock);
1793 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1795 // In NDEBUG mode ignore the output so we don't get an unused variable
1801 // Compute the delta between the bitcode indices in the VST (the word offset
1802 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1803 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1804 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1805 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1806 // just before entering the VST subblock because: 1) the EnterSubBlock
1807 // changes the AbbrevID width; 2) the VST block is nested within the same
1808 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1809 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1810 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1811 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1812 unsigned FuncBitcodeOffsetDelta =
1813 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1815 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1816 return error("Invalid record");
1818 SmallVector<uint64_t, 64> Record;
1820 Triple TT(TheModule->getTargetTriple());
1822 // Read all the records for this value table.
1823 SmallString<128> ValueName;
1825 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1827 switch (Entry.Kind) {
1828 case BitstreamEntry::SubBlock: // Handled for us already.
1829 case BitstreamEntry::Error:
1830 return error("Malformed block");
1831 case BitstreamEntry::EndBlock:
1833 Stream.JumpToBit(CurrentBit);
1834 return std::error_code();
1835 case BitstreamEntry::Record:
1836 // The interesting case.
1842 switch (Stream.readRecord(Entry.ID, Record)) {
1843 default: // Default behavior: unknown type.
1845 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1846 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1847 if (std::error_code EC = ValOrErr.getError())
1852 case bitc::VST_CODE_FNENTRY: {
1853 // VST_FNENTRY: [valueid, offset, namechar x N]
1854 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1855 if (std::error_code EC = ValOrErr.getError())
1857 Value *V = ValOrErr.get();
1859 auto *GO = dyn_cast<GlobalObject>(V);
1861 // If this is an alias, need to get the actual Function object
1862 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1863 auto *GA = dyn_cast<GlobalAlias>(V);
1865 GO = GA->getBaseObject();
1869 uint64_t FuncWordOffset = Record[1];
1870 Function *F = dyn_cast<Function>(GO);
1872 uint64_t FuncBitOffset = FuncWordOffset * 32;
1873 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1874 // Set the LastFunctionBlockBit to point to the last function block.
1875 // Later when parsing is resumed after function materialization,
1876 // we can simply skip that last function block.
1877 if (FuncBitOffset > LastFunctionBlockBit)
1878 LastFunctionBlockBit = FuncBitOffset;
1881 case bitc::VST_CODE_BBENTRY: {
1882 if (convertToString(Record, 1, ValueName))
1883 return error("Invalid record");
1884 BasicBlock *BB = getBasicBlock(Record[0]);
1886 return error("Invalid record");
1888 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1896 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1898 std::error_code BitcodeReader::parseMetadata() {
1899 IsMetadataMaterialized = true;
1900 unsigned NextMDValueNo = MDValueList.size();
1902 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1903 return error("Invalid record");
1905 SmallVector<uint64_t, 64> Record;
1908 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1909 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1911 return getMD(ID - 1);
1914 auto getMDString = [&](unsigned ID) -> MDString *{
1915 // This requires that the ID is not really a forward reference. In
1916 // particular, the MDString must already have been resolved.
1917 return cast_or_null<MDString>(getMDOrNull(ID));
1920 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1921 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1923 // Read all the records.
1925 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1927 switch (Entry.Kind) {
1928 case BitstreamEntry::SubBlock: // Handled for us already.
1929 case BitstreamEntry::Error:
1930 return error("Malformed block");
1931 case BitstreamEntry::EndBlock:
1932 MDValueList.tryToResolveCycles();
1933 return std::error_code();
1934 case BitstreamEntry::Record:
1935 // The interesting case.
1941 unsigned Code = Stream.readRecord(Entry.ID, Record);
1942 bool IsDistinct = false;
1944 default: // Default behavior: ignore.
1946 case bitc::METADATA_NAME: {
1947 // Read name of the named metadata.
1948 SmallString<8> Name(Record.begin(), Record.end());
1950 Code = Stream.ReadCode();
1952 unsigned NextBitCode = Stream.readRecord(Code, Record);
1953 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1954 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1956 // Read named metadata elements.
1957 unsigned Size = Record.size();
1958 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1959 for (unsigned i = 0; i != Size; ++i) {
1960 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1962 return error("Invalid record");
1963 NMD->addOperand(MD);
1967 case bitc::METADATA_OLD_FN_NODE: {
1968 // FIXME: Remove in 4.0.
1969 // This is a LocalAsMetadata record, the only type of function-local
1971 if (Record.size() % 2 == 1)
1972 return error("Invalid record");
1974 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1975 // to be legal, but there's no upgrade path.
1976 auto dropRecord = [&] {
1977 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1979 if (Record.size() != 2) {
1984 Type *Ty = getTypeByID(Record[0]);
1985 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1990 MDValueList.assignValue(
1991 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1995 case bitc::METADATA_OLD_NODE: {
1996 // FIXME: Remove in 4.0.
1997 if (Record.size() % 2 == 1)
1998 return error("Invalid record");
2000 unsigned Size = Record.size();
2001 SmallVector<Metadata *, 8> Elts;
2002 for (unsigned i = 0; i != Size; i += 2) {
2003 Type *Ty = getTypeByID(Record[i]);
2005 return error("Invalid record");
2006 if (Ty->isMetadataTy())
2007 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
2008 else if (!Ty->isVoidTy()) {
2010 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2011 assert(isa<ConstantAsMetadata>(MD) &&
2012 "Expected non-function-local metadata");
2015 Elts.push_back(nullptr);
2017 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2020 case bitc::METADATA_VALUE: {
2021 if (Record.size() != 2)
2022 return error("Invalid record");
2024 Type *Ty = getTypeByID(Record[0]);
2025 if (Ty->isMetadataTy() || Ty->isVoidTy())
2026 return error("Invalid record");
2028 MDValueList.assignValue(
2029 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2033 case bitc::METADATA_DISTINCT_NODE:
2036 case bitc::METADATA_NODE: {
2037 SmallVector<Metadata *, 8> Elts;
2038 Elts.reserve(Record.size());
2039 for (unsigned ID : Record)
2040 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2041 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2042 : MDNode::get(Context, Elts),
2046 case bitc::METADATA_LOCATION: {
2047 if (Record.size() != 5)
2048 return error("Invalid record");
2050 unsigned Line = Record[1];
2051 unsigned Column = Record[2];
2052 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2053 Metadata *InlinedAt =
2054 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2055 MDValueList.assignValue(
2056 GET_OR_DISTINCT(DILocation, Record[0],
2057 (Context, Line, Column, Scope, InlinedAt)),
2061 case bitc::METADATA_GENERIC_DEBUG: {
2062 if (Record.size() < 4)
2063 return error("Invalid record");
2065 unsigned Tag = Record[1];
2066 unsigned Version = Record[2];
2068 if (Tag >= 1u << 16 || Version != 0)
2069 return error("Invalid record");
2071 auto *Header = getMDString(Record[3]);
2072 SmallVector<Metadata *, 8> DwarfOps;
2073 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2074 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2076 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2077 (Context, Tag, Header, DwarfOps)),
2081 case bitc::METADATA_SUBRANGE: {
2082 if (Record.size() != 3)
2083 return error("Invalid record");
2085 MDValueList.assignValue(
2086 GET_OR_DISTINCT(DISubrange, Record[0],
2087 (Context, Record[1], unrotateSign(Record[2]))),
2091 case bitc::METADATA_ENUMERATOR: {
2092 if (Record.size() != 3)
2093 return error("Invalid record");
2095 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2096 (Context, unrotateSign(Record[1]),
2097 getMDString(Record[2]))),
2101 case bitc::METADATA_BASIC_TYPE: {
2102 if (Record.size() != 6)
2103 return error("Invalid record");
2105 MDValueList.assignValue(
2106 GET_OR_DISTINCT(DIBasicType, Record[0],
2107 (Context, Record[1], getMDString(Record[2]),
2108 Record[3], Record[4], Record[5])),
2112 case bitc::METADATA_DERIVED_TYPE: {
2113 if (Record.size() != 12)
2114 return error("Invalid record");
2116 MDValueList.assignValue(
2117 GET_OR_DISTINCT(DIDerivedType, Record[0],
2118 (Context, Record[1], getMDString(Record[2]),
2119 getMDOrNull(Record[3]), Record[4],
2120 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2121 Record[7], Record[8], Record[9], Record[10],
2122 getMDOrNull(Record[11]))),
2126 case bitc::METADATA_COMPOSITE_TYPE: {
2127 if (Record.size() != 16)
2128 return error("Invalid record");
2130 MDValueList.assignValue(
2131 GET_OR_DISTINCT(DICompositeType, Record[0],
2132 (Context, Record[1], getMDString(Record[2]),
2133 getMDOrNull(Record[3]), Record[4],
2134 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2135 Record[7], Record[8], Record[9], Record[10],
2136 getMDOrNull(Record[11]), Record[12],
2137 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2138 getMDString(Record[15]))),
2142 case bitc::METADATA_SUBROUTINE_TYPE: {
2143 if (Record.size() != 3)
2144 return error("Invalid record");
2146 MDValueList.assignValue(
2147 GET_OR_DISTINCT(DISubroutineType, Record[0],
2148 (Context, Record[1], getMDOrNull(Record[2]))),
2153 case bitc::METADATA_MODULE: {
2154 if (Record.size() != 6)
2155 return error("Invalid record");
2157 MDValueList.assignValue(
2158 GET_OR_DISTINCT(DIModule, Record[0],
2159 (Context, getMDOrNull(Record[1]),
2160 getMDString(Record[2]), getMDString(Record[3]),
2161 getMDString(Record[4]), getMDString(Record[5]))),
2166 case bitc::METADATA_FILE: {
2167 if (Record.size() != 3)
2168 return error("Invalid record");
2170 MDValueList.assignValue(
2171 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2172 getMDString(Record[2]))),
2176 case bitc::METADATA_COMPILE_UNIT: {
2177 if (Record.size() < 14 || Record.size() > 15)
2178 return error("Invalid record");
2180 // Ignore Record[1], which indicates whether this compile unit is
2181 // distinct. It's always distinct.
2182 MDValueList.assignValue(
2183 DICompileUnit::getDistinct(
2184 Context, Record[1], getMDOrNull(Record[2]),
2185 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2186 Record[6], getMDString(Record[7]), Record[8],
2187 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2188 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2189 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2193 case bitc::METADATA_SUBPROGRAM: {
2194 if (Record.size() != 18 && Record.size() != 19)
2195 return error("Invalid record");
2197 bool HasFn = Record.size() == 19;
2198 DISubprogram *SP = GET_OR_DISTINCT(
2200 Record[0] || Record[8], // All definitions should be distinct.
2201 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2202 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2203 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2204 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2205 Record[14], getMDOrNull(Record[15 + HasFn]),
2206 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2207 MDValueList.assignValue(SP, NextMDValueNo++);
2209 // Upgrade sp->function mapping to function->sp mapping.
2210 if (HasFn && Record[15]) {
2211 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2212 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2213 if (F->isMaterializable())
2214 // Defer until materialized; unmaterialized functions may not have
2216 FunctionsWithSPs[F] = SP;
2217 else if (!F->empty())
2218 F->setSubprogram(SP);
2223 case bitc::METADATA_LEXICAL_BLOCK: {
2224 if (Record.size() != 5)
2225 return error("Invalid record");
2227 MDValueList.assignValue(
2228 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2229 (Context, getMDOrNull(Record[1]),
2230 getMDOrNull(Record[2]), Record[3], Record[4])),
2234 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2235 if (Record.size() != 4)
2236 return error("Invalid record");
2238 MDValueList.assignValue(
2239 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2240 (Context, getMDOrNull(Record[1]),
2241 getMDOrNull(Record[2]), Record[3])),
2245 case bitc::METADATA_NAMESPACE: {
2246 if (Record.size() != 5)
2247 return error("Invalid record");
2249 MDValueList.assignValue(
2250 GET_OR_DISTINCT(DINamespace, Record[0],
2251 (Context, getMDOrNull(Record[1]),
2252 getMDOrNull(Record[2]), getMDString(Record[3]),
2257 case bitc::METADATA_TEMPLATE_TYPE: {
2258 if (Record.size() != 3)
2259 return error("Invalid record");
2261 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2263 (Context, getMDString(Record[1]),
2264 getMDOrNull(Record[2]))),
2268 case bitc::METADATA_TEMPLATE_VALUE: {
2269 if (Record.size() != 5)
2270 return error("Invalid record");
2272 MDValueList.assignValue(
2273 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2274 (Context, Record[1], getMDString(Record[2]),
2275 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2279 case bitc::METADATA_GLOBAL_VAR: {
2280 if (Record.size() != 11)
2281 return error("Invalid record");
2283 MDValueList.assignValue(
2284 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2285 (Context, getMDOrNull(Record[1]),
2286 getMDString(Record[2]), getMDString(Record[3]),
2287 getMDOrNull(Record[4]), Record[5],
2288 getMDOrNull(Record[6]), Record[7], Record[8],
2289 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2293 case bitc::METADATA_LOCAL_VAR: {
2294 // 10th field is for the obseleted 'inlinedAt:' field.
2295 if (Record.size() < 8 || Record.size() > 10)
2296 return error("Invalid record");
2298 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2299 // DW_TAG_arg_variable.
2300 bool HasTag = Record.size() > 8;
2301 MDValueList.assignValue(
2302 GET_OR_DISTINCT(DILocalVariable, Record[0],
2303 (Context, getMDOrNull(Record[1 + HasTag]),
2304 getMDString(Record[2 + HasTag]),
2305 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2306 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2307 Record[7 + HasTag])),
2311 case bitc::METADATA_EXPRESSION: {
2312 if (Record.size() < 1)
2313 return error("Invalid record");
2315 MDValueList.assignValue(
2316 GET_OR_DISTINCT(DIExpression, Record[0],
2317 (Context, makeArrayRef(Record).slice(1))),
2321 case bitc::METADATA_OBJC_PROPERTY: {
2322 if (Record.size() != 8)
2323 return error("Invalid record");
2325 MDValueList.assignValue(
2326 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2327 (Context, getMDString(Record[1]),
2328 getMDOrNull(Record[2]), Record[3],
2329 getMDString(Record[4]), getMDString(Record[5]),
2330 Record[6], getMDOrNull(Record[7]))),
2334 case bitc::METADATA_IMPORTED_ENTITY: {
2335 if (Record.size() != 6)
2336 return error("Invalid record");
2338 MDValueList.assignValue(
2339 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2340 (Context, Record[1], getMDOrNull(Record[2]),
2341 getMDOrNull(Record[3]), Record[4],
2342 getMDString(Record[5]))),
2346 case bitc::METADATA_STRING: {
2347 std::string String(Record.begin(), Record.end());
2348 llvm::UpgradeMDStringConstant(String);
2349 Metadata *MD = MDString::get(Context, String);
2350 MDValueList.assignValue(MD, NextMDValueNo++);
2353 case bitc::METADATA_KIND: {
2354 if (Record.size() < 2)
2355 return error("Invalid record");
2357 unsigned Kind = Record[0];
2358 SmallString<8> Name(Record.begin()+1, Record.end());
2360 unsigned NewKind = TheModule->getMDKindID(Name.str());
2361 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2362 return error("Conflicting METADATA_KIND records");
2367 #undef GET_OR_DISTINCT
2370 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2372 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2377 // There is no such thing as -0 with integers. "-0" really means MININT.
2381 /// Resolve all of the initializers for global values and aliases that we can.
2382 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2383 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2384 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2385 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2386 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2387 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2389 GlobalInitWorklist.swap(GlobalInits);
2390 AliasInitWorklist.swap(AliasInits);
2391 FunctionPrefixWorklist.swap(FunctionPrefixes);
2392 FunctionPrologueWorklist.swap(FunctionPrologues);
2393 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2395 while (!GlobalInitWorklist.empty()) {
2396 unsigned ValID = GlobalInitWorklist.back().second;
2397 if (ValID >= ValueList.size()) {
2398 // Not ready to resolve this yet, it requires something later in the file.
2399 GlobalInits.push_back(GlobalInitWorklist.back());
2401 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2402 GlobalInitWorklist.back().first->setInitializer(C);
2404 return error("Expected a constant");
2406 GlobalInitWorklist.pop_back();
2409 while (!AliasInitWorklist.empty()) {
2410 unsigned ValID = AliasInitWorklist.back().second;
2411 if (ValID >= ValueList.size()) {
2412 AliasInits.push_back(AliasInitWorklist.back());
2414 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2416 return error("Expected a constant");
2417 GlobalAlias *Alias = AliasInitWorklist.back().first;
2418 if (C->getType() != Alias->getType())
2419 return error("Alias and aliasee types don't match");
2420 Alias->setAliasee(C);
2422 AliasInitWorklist.pop_back();
2425 while (!FunctionPrefixWorklist.empty()) {
2426 unsigned ValID = FunctionPrefixWorklist.back().second;
2427 if (ValID >= ValueList.size()) {
2428 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2430 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2431 FunctionPrefixWorklist.back().first->setPrefixData(C);
2433 return error("Expected a constant");
2435 FunctionPrefixWorklist.pop_back();
2438 while (!FunctionPrologueWorklist.empty()) {
2439 unsigned ValID = FunctionPrologueWorklist.back().second;
2440 if (ValID >= ValueList.size()) {
2441 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2443 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2444 FunctionPrologueWorklist.back().first->setPrologueData(C);
2446 return error("Expected a constant");
2448 FunctionPrologueWorklist.pop_back();
2451 while (!FunctionPersonalityFnWorklist.empty()) {
2452 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2453 if (ValID >= ValueList.size()) {
2454 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2456 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2457 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2459 return error("Expected a constant");
2461 FunctionPersonalityFnWorklist.pop_back();
2464 return std::error_code();
2467 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2468 SmallVector<uint64_t, 8> Words(Vals.size());
2469 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2470 BitcodeReader::decodeSignRotatedValue);
2472 return APInt(TypeBits, Words);
2475 std::error_code BitcodeReader::parseConstants() {
2476 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2477 return error("Invalid record");
2479 SmallVector<uint64_t, 64> Record;
2481 // Read all the records for this value table.
2482 Type *CurTy = Type::getInt32Ty(Context);
2483 unsigned NextCstNo = ValueList.size();
2485 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2487 switch (Entry.Kind) {
2488 case BitstreamEntry::SubBlock: // Handled for us already.
2489 case BitstreamEntry::Error:
2490 return error("Malformed block");
2491 case BitstreamEntry::EndBlock:
2492 if (NextCstNo != ValueList.size())
2493 return error("Invalid ronstant reference");
2495 // Once all the constants have been read, go through and resolve forward
2497 ValueList.resolveConstantForwardRefs();
2498 return std::error_code();
2499 case BitstreamEntry::Record:
2500 // The interesting case.
2507 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2509 default: // Default behavior: unknown constant
2510 case bitc::CST_CODE_UNDEF: // UNDEF
2511 V = UndefValue::get(CurTy);
2513 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2515 return error("Invalid record");
2516 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2517 return error("Invalid record");
2518 CurTy = TypeList[Record[0]];
2519 continue; // Skip the ValueList manipulation.
2520 case bitc::CST_CODE_NULL: // NULL
2521 V = Constant::getNullValue(CurTy);
2523 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2524 if (!CurTy->isIntegerTy() || Record.empty())
2525 return error("Invalid record");
2526 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2528 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2529 if (!CurTy->isIntegerTy() || Record.empty())
2530 return error("Invalid record");
2533 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2534 V = ConstantInt::get(Context, VInt);
2538 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2540 return error("Invalid record");
2541 if (CurTy->isHalfTy())
2542 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2543 APInt(16, (uint16_t)Record[0])));
2544 else if (CurTy->isFloatTy())
2545 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2546 APInt(32, (uint32_t)Record[0])));
2547 else if (CurTy->isDoubleTy())
2548 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2549 APInt(64, Record[0])));
2550 else if (CurTy->isX86_FP80Ty()) {
2551 // Bits are not stored the same way as a normal i80 APInt, compensate.
2552 uint64_t Rearrange[2];
2553 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2554 Rearrange[1] = Record[0] >> 48;
2555 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2556 APInt(80, Rearrange)));
2557 } else if (CurTy->isFP128Ty())
2558 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2559 APInt(128, Record)));
2560 else if (CurTy->isPPC_FP128Ty())
2561 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2562 APInt(128, Record)));
2564 V = UndefValue::get(CurTy);
2568 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2570 return error("Invalid record");
2572 unsigned Size = Record.size();
2573 SmallVector<Constant*, 16> Elts;
2575 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2576 for (unsigned i = 0; i != Size; ++i)
2577 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2578 STy->getElementType(i)));
2579 V = ConstantStruct::get(STy, Elts);
2580 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2581 Type *EltTy = ATy->getElementType();
2582 for (unsigned i = 0; i != Size; ++i)
2583 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2584 V = ConstantArray::get(ATy, Elts);
2585 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2586 Type *EltTy = VTy->getElementType();
2587 for (unsigned i = 0; i != Size; ++i)
2588 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2589 V = ConstantVector::get(Elts);
2591 V = UndefValue::get(CurTy);
2595 case bitc::CST_CODE_STRING: // STRING: [values]
2596 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2598 return error("Invalid record");
2600 SmallString<16> Elts(Record.begin(), Record.end());
2601 V = ConstantDataArray::getString(Context, Elts,
2602 BitCode == bitc::CST_CODE_CSTRING);
2605 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2607 return error("Invalid record");
2609 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2610 unsigned Size = Record.size();
2612 if (EltTy->isIntegerTy(8)) {
2613 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2614 if (isa<VectorType>(CurTy))
2615 V = ConstantDataVector::get(Context, Elts);
2617 V = ConstantDataArray::get(Context, Elts);
2618 } else if (EltTy->isIntegerTy(16)) {
2619 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2620 if (isa<VectorType>(CurTy))
2621 V = ConstantDataVector::get(Context, Elts);
2623 V = ConstantDataArray::get(Context, Elts);
2624 } else if (EltTy->isIntegerTy(32)) {
2625 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2626 if (isa<VectorType>(CurTy))
2627 V = ConstantDataVector::get(Context, Elts);
2629 V = ConstantDataArray::get(Context, Elts);
2630 } else if (EltTy->isIntegerTy(64)) {
2631 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2632 if (isa<VectorType>(CurTy))
2633 V = ConstantDataVector::get(Context, Elts);
2635 V = ConstantDataArray::get(Context, Elts);
2636 } else if (EltTy->isFloatTy()) {
2637 SmallVector<float, 16> Elts(Size);
2638 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2639 if (isa<VectorType>(CurTy))
2640 V = ConstantDataVector::get(Context, Elts);
2642 V = ConstantDataArray::get(Context, Elts);
2643 } else if (EltTy->isDoubleTy()) {
2644 SmallVector<double, 16> Elts(Size);
2645 std::transform(Record.begin(), Record.end(), Elts.begin(),
2647 if (isa<VectorType>(CurTy))
2648 V = ConstantDataVector::get(Context, Elts);
2650 V = ConstantDataArray::get(Context, Elts);
2652 return error("Invalid type for value");
2657 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2658 if (Record.size() < 3)
2659 return error("Invalid record");
2660 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2662 V = UndefValue::get(CurTy); // Unknown binop.
2664 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2665 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2667 if (Record.size() >= 4) {
2668 if (Opc == Instruction::Add ||
2669 Opc == Instruction::Sub ||
2670 Opc == Instruction::Mul ||
2671 Opc == Instruction::Shl) {
2672 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2673 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2674 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2675 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2676 } else if (Opc == Instruction::SDiv ||
2677 Opc == Instruction::UDiv ||
2678 Opc == Instruction::LShr ||
2679 Opc == Instruction::AShr) {
2680 if (Record[3] & (1 << bitc::PEO_EXACT))
2681 Flags |= SDivOperator::IsExact;
2684 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2688 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2689 if (Record.size() < 3)
2690 return error("Invalid record");
2691 int Opc = getDecodedCastOpcode(Record[0]);
2693 V = UndefValue::get(CurTy); // Unknown cast.
2695 Type *OpTy = getTypeByID(Record[1]);
2697 return error("Invalid record");
2698 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2699 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2700 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2704 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2705 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2707 Type *PointeeType = nullptr;
2708 if (Record.size() % 2)
2709 PointeeType = getTypeByID(Record[OpNum++]);
2710 SmallVector<Constant*, 16> Elts;
2711 while (OpNum != Record.size()) {
2712 Type *ElTy = getTypeByID(Record[OpNum++]);
2714 return error("Invalid record");
2715 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2720 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2722 return error("Explicit gep operator type does not match pointee type "
2723 "of pointer operand");
2725 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2726 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2728 bitc::CST_CODE_CE_INBOUNDS_GEP);
2731 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2732 if (Record.size() < 3)
2733 return error("Invalid record");
2735 Type *SelectorTy = Type::getInt1Ty(Context);
2737 // The selector might be an i1 or an <n x i1>
2738 // Get the type from the ValueList before getting a forward ref.
2739 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2740 if (Value *V = ValueList[Record[0]])
2741 if (SelectorTy != V->getType())
2742 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2744 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2746 ValueList.getConstantFwdRef(Record[1],CurTy),
2747 ValueList.getConstantFwdRef(Record[2],CurTy));
2750 case bitc::CST_CODE_CE_EXTRACTELT
2751 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2752 if (Record.size() < 3)
2753 return error("Invalid record");
2755 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2757 return error("Invalid record");
2758 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2759 Constant *Op1 = nullptr;
2760 if (Record.size() == 4) {
2761 Type *IdxTy = getTypeByID(Record[2]);
2763 return error("Invalid record");
2764 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2765 } else // TODO: Remove with llvm 4.0
2766 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2768 return error("Invalid record");
2769 V = ConstantExpr::getExtractElement(Op0, Op1);
2772 case bitc::CST_CODE_CE_INSERTELT
2773 : { // CE_INSERTELT: [opval, opval, opty, opval]
2774 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2775 if (Record.size() < 3 || !OpTy)
2776 return error("Invalid record");
2777 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2778 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2779 OpTy->getElementType());
2780 Constant *Op2 = nullptr;
2781 if (Record.size() == 4) {
2782 Type *IdxTy = getTypeByID(Record[2]);
2784 return error("Invalid record");
2785 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2786 } else // TODO: Remove with llvm 4.0
2787 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2789 return error("Invalid record");
2790 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2793 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2794 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2795 if (Record.size() < 3 || !OpTy)
2796 return error("Invalid record");
2797 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2798 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2799 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2800 OpTy->getNumElements());
2801 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2802 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2805 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2806 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2808 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2809 if (Record.size() < 4 || !RTy || !OpTy)
2810 return error("Invalid record");
2811 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2812 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2813 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2814 RTy->getNumElements());
2815 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2816 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2819 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2820 if (Record.size() < 4)
2821 return error("Invalid record");
2822 Type *OpTy = getTypeByID(Record[0]);
2824 return error("Invalid record");
2825 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2826 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2828 if (OpTy->isFPOrFPVectorTy())
2829 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2831 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2834 // This maintains backward compatibility, pre-asm dialect keywords.
2835 // FIXME: Remove with the 4.0 release.
2836 case bitc::CST_CODE_INLINEASM_OLD: {
2837 if (Record.size() < 2)
2838 return error("Invalid record");
2839 std::string AsmStr, ConstrStr;
2840 bool HasSideEffects = Record[0] & 1;
2841 bool IsAlignStack = Record[0] >> 1;
2842 unsigned AsmStrSize = Record[1];
2843 if (2+AsmStrSize >= Record.size())
2844 return error("Invalid record");
2845 unsigned ConstStrSize = Record[2+AsmStrSize];
2846 if (3+AsmStrSize+ConstStrSize > Record.size())
2847 return error("Invalid record");
2849 for (unsigned i = 0; i != AsmStrSize; ++i)
2850 AsmStr += (char)Record[2+i];
2851 for (unsigned i = 0; i != ConstStrSize; ++i)
2852 ConstrStr += (char)Record[3+AsmStrSize+i];
2853 PointerType *PTy = cast<PointerType>(CurTy);
2854 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2855 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2858 // This version adds support for the asm dialect keywords (e.g.,
2860 case bitc::CST_CODE_INLINEASM: {
2861 if (Record.size() < 2)
2862 return error("Invalid record");
2863 std::string AsmStr, ConstrStr;
2864 bool HasSideEffects = Record[0] & 1;
2865 bool IsAlignStack = (Record[0] >> 1) & 1;
2866 unsigned AsmDialect = Record[0] >> 2;
2867 unsigned AsmStrSize = Record[1];
2868 if (2+AsmStrSize >= Record.size())
2869 return error("Invalid record");
2870 unsigned ConstStrSize = Record[2+AsmStrSize];
2871 if (3+AsmStrSize+ConstStrSize > Record.size())
2872 return error("Invalid record");
2874 for (unsigned i = 0; i != AsmStrSize; ++i)
2875 AsmStr += (char)Record[2+i];
2876 for (unsigned i = 0; i != ConstStrSize; ++i)
2877 ConstrStr += (char)Record[3+AsmStrSize+i];
2878 PointerType *PTy = cast<PointerType>(CurTy);
2879 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2880 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2881 InlineAsm::AsmDialect(AsmDialect));
2884 case bitc::CST_CODE_BLOCKADDRESS:{
2885 if (Record.size() < 3)
2886 return error("Invalid record");
2887 Type *FnTy = getTypeByID(Record[0]);
2889 return error("Invalid record");
2891 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2893 return error("Invalid record");
2895 // Don't let Fn get dematerialized.
2896 BlockAddressesTaken.insert(Fn);
2898 // If the function is already parsed we can insert the block address right
2901 unsigned BBID = Record[2];
2903 // Invalid reference to entry block.
2904 return error("Invalid ID");
2906 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2907 for (size_t I = 0, E = BBID; I != E; ++I) {
2909 return error("Invalid ID");
2914 // Otherwise insert a placeholder and remember it so it can be inserted
2915 // when the function is parsed.
2916 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2918 BasicBlockFwdRefQueue.push_back(Fn);
2919 if (FwdBBs.size() < BBID + 1)
2920 FwdBBs.resize(BBID + 1);
2922 FwdBBs[BBID] = BasicBlock::Create(Context);
2925 V = BlockAddress::get(Fn, BB);
2930 if (ValueList.assignValue(V, NextCstNo))
2931 return error("Invalid forward reference");
2936 std::error_code BitcodeReader::parseUseLists() {
2937 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2938 return error("Invalid record");
2940 // Read all the records.
2941 SmallVector<uint64_t, 64> Record;
2943 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2945 switch (Entry.Kind) {
2946 case BitstreamEntry::SubBlock: // Handled for us already.
2947 case BitstreamEntry::Error:
2948 return error("Malformed block");
2949 case BitstreamEntry::EndBlock:
2950 return std::error_code();
2951 case BitstreamEntry::Record:
2952 // The interesting case.
2956 // Read a use list record.
2959 switch (Stream.readRecord(Entry.ID, Record)) {
2960 default: // Default behavior: unknown type.
2962 case bitc::USELIST_CODE_BB:
2965 case bitc::USELIST_CODE_DEFAULT: {
2966 unsigned RecordLength = Record.size();
2967 if (RecordLength < 3)
2968 // Records should have at least an ID and two indexes.
2969 return error("Invalid record");
2970 unsigned ID = Record.back();
2975 assert(ID < FunctionBBs.size() && "Basic block not found");
2976 V = FunctionBBs[ID];
2979 unsigned NumUses = 0;
2980 SmallDenseMap<const Use *, unsigned, 16> Order;
2981 for (const Use &U : V->uses()) {
2982 if (++NumUses > Record.size())
2984 Order[&U] = Record[NumUses - 1];
2986 if (Order.size() != Record.size() || NumUses > Record.size())
2987 // Mismatches can happen if the functions are being materialized lazily
2988 // (out-of-order), or a value has been upgraded.
2991 V->sortUseList([&](const Use &L, const Use &R) {
2992 return Order.lookup(&L) < Order.lookup(&R);
3000 /// When we see the block for metadata, remember where it is and then skip it.
3001 /// This lets us lazily deserialize the metadata.
3002 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3003 // Save the current stream state.
3004 uint64_t CurBit = Stream.GetCurrentBitNo();
3005 DeferredMetadataInfo.push_back(CurBit);
3007 // Skip over the block for now.
3008 if (Stream.SkipBlock())
3009 return error("Invalid record");
3010 return std::error_code();
3013 std::error_code BitcodeReader::materializeMetadata() {
3014 for (uint64_t BitPos : DeferredMetadataInfo) {
3015 // Move the bit stream to the saved position.
3016 Stream.JumpToBit(BitPos);
3017 if (std::error_code EC = parseMetadata())
3020 DeferredMetadataInfo.clear();
3021 return std::error_code();
3024 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3026 /// When we see the block for a function body, remember where it is and then
3027 /// skip it. This lets us lazily deserialize the functions.
3028 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3029 // Get the function we are talking about.
3030 if (FunctionsWithBodies.empty())
3031 return error("Insufficient function protos");
3033 Function *Fn = FunctionsWithBodies.back();
3034 FunctionsWithBodies.pop_back();
3036 // Save the current stream state.
3037 uint64_t CurBit = Stream.GetCurrentBitNo();
3039 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3040 "Mismatch between VST and scanned function offsets");
3041 DeferredFunctionInfo[Fn] = CurBit;
3043 // Skip over the function block for now.
3044 if (Stream.SkipBlock())
3045 return error("Invalid record");
3046 return std::error_code();
3049 std::error_code BitcodeReader::globalCleanup() {
3050 // Patch the initializers for globals and aliases up.
3051 resolveGlobalAndAliasInits();
3052 if (!GlobalInits.empty() || !AliasInits.empty())
3053 return error("Malformed global initializer set");
3055 // Look for intrinsic functions which need to be upgraded at some point
3056 for (Function &F : *TheModule) {
3058 if (UpgradeIntrinsicFunction(&F, NewFn))
3059 UpgradedIntrinsics[&F] = NewFn;
3062 // Look for global variables which need to be renamed.
3063 for (GlobalVariable &GV : TheModule->globals())
3064 UpgradeGlobalVariable(&GV);
3066 // Force deallocation of memory for these vectors to favor the client that
3067 // want lazy deserialization.
3068 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3069 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3070 return std::error_code();
3073 /// Support for lazy parsing of function bodies. This is required if we
3074 /// either have an old bitcode file without a VST forward declaration record,
3075 /// or if we have an anonymous function being materialized, since anonymous
3076 /// functions do not have a name and are therefore not in the VST.
3077 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3078 Stream.JumpToBit(NextUnreadBit);
3080 if (Stream.AtEndOfStream())
3081 return error("Could not find function in stream");
3083 if (!SeenFirstFunctionBody)
3084 return error("Trying to materialize functions before seeing function blocks");
3086 // An old bitcode file with the symbol table at the end would have
3087 // finished the parse greedily.
3088 assert(SeenValueSymbolTable);
3090 SmallVector<uint64_t, 64> Record;
3093 BitstreamEntry Entry = Stream.advance();
3094 switch (Entry.Kind) {
3096 return error("Expect SubBlock");
3097 case BitstreamEntry::SubBlock:
3100 return error("Expect function block");
3101 case bitc::FUNCTION_BLOCK_ID:
3102 if (std::error_code EC = rememberAndSkipFunctionBody())
3104 NextUnreadBit = Stream.GetCurrentBitNo();
3105 return std::error_code();
3111 std::error_code BitcodeReader::parseBitcodeVersion() {
3112 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3113 return error("Invalid record");
3115 // Read all the records.
3116 SmallVector<uint64_t, 64> Record;
3118 BitstreamEntry Entry = Stream.advance();
3120 switch (Entry.Kind) {
3122 case BitstreamEntry::Error:
3123 return error("Malformed block");
3124 case BitstreamEntry::EndBlock:
3125 return std::error_code();
3126 case BitstreamEntry::Record:
3127 // The interesting case.
3133 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3135 default: // Default behavior: reject
3136 return error("Invalid value");
3137 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3139 convertToString(Record, 0, ProducerIdentification);
3142 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3143 unsigned epoch = (unsigned)Record[0];
3144 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3146 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3147 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3154 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3155 bool ShouldLazyLoadMetadata) {
3157 Stream.JumpToBit(ResumeBit);
3158 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3159 return error("Invalid record");
3161 SmallVector<uint64_t, 64> Record;
3162 std::vector<std::string> SectionTable;
3163 std::vector<std::string> GCTable;
3165 // Read all the records for this module.
3167 BitstreamEntry Entry = Stream.advance();
3169 switch (Entry.Kind) {
3170 case BitstreamEntry::Error:
3171 return error("Malformed block");
3172 case BitstreamEntry::EndBlock:
3173 return globalCleanup();
3175 case BitstreamEntry::SubBlock:
3177 default: // Skip unknown content.
3178 if (Stream.SkipBlock())
3179 return error("Invalid record");
3181 case bitc::BLOCKINFO_BLOCK_ID:
3182 if (Stream.ReadBlockInfoBlock())
3183 return error("Malformed block");
3185 case bitc::PARAMATTR_BLOCK_ID:
3186 if (std::error_code EC = parseAttributeBlock())
3189 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3190 if (std::error_code EC = parseAttributeGroupBlock())
3193 case bitc::TYPE_BLOCK_ID_NEW:
3194 if (std::error_code EC = parseTypeTable())
3197 case bitc::VALUE_SYMTAB_BLOCK_ID:
3198 if (!SeenValueSymbolTable) {
3199 // Either this is an old form VST without function index and an
3200 // associated VST forward declaration record (which would have caused
3201 // the VST to be jumped to and parsed before it was encountered
3202 // normally in the stream), or there were no function blocks to
3203 // trigger an earlier parsing of the VST.
3204 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3205 if (std::error_code EC = parseValueSymbolTable())
3207 SeenValueSymbolTable = true;
3209 // We must have had a VST forward declaration record, which caused
3210 // the parser to jump to and parse the VST earlier.
3211 assert(VSTOffset > 0);
3212 if (Stream.SkipBlock())
3213 return error("Invalid record");
3216 case bitc::CONSTANTS_BLOCK_ID:
3217 if (std::error_code EC = parseConstants())
3219 if (std::error_code EC = resolveGlobalAndAliasInits())
3222 case bitc::METADATA_BLOCK_ID:
3223 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3224 if (std::error_code EC = rememberAndSkipMetadata())
3228 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3229 if (std::error_code EC = parseMetadata())
3232 case bitc::FUNCTION_BLOCK_ID:
3233 // If this is the first function body we've seen, reverse the
3234 // FunctionsWithBodies list.
3235 if (!SeenFirstFunctionBody) {
3236 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3237 if (std::error_code EC = globalCleanup())
3239 SeenFirstFunctionBody = true;
3242 if (VSTOffset > 0) {
3243 // If we have a VST forward declaration record, make sure we
3244 // parse the VST now if we haven't already. It is needed to
3245 // set up the DeferredFunctionInfo vector for lazy reading.
3246 if (!SeenValueSymbolTable) {
3247 if (std::error_code EC =
3248 BitcodeReader::parseValueSymbolTable(VSTOffset))
3250 SeenValueSymbolTable = true;
3251 // Fall through so that we record the NextUnreadBit below.
3252 // This is necessary in case we have an anonymous function that
3253 // is later materialized. Since it will not have a VST entry we
3254 // need to fall back to the lazy parse to find its offset.
3256 // If we have a VST forward declaration record, but have already
3257 // parsed the VST (just above, when the first function body was
3258 // encountered here), then we are resuming the parse after
3259 // materializing functions. The ResumeBit points to the
3260 // start of the last function block recorded in the
3261 // DeferredFunctionInfo map. Skip it.
3262 if (Stream.SkipBlock())
3263 return error("Invalid record");
3268 // Support older bitcode files that did not have the function
3269 // index in the VST, nor a VST forward declaration record, as
3270 // well as anonymous functions that do not have VST entries.
3271 // Build the DeferredFunctionInfo vector on the fly.
3272 if (std::error_code EC = rememberAndSkipFunctionBody())
3275 // Suspend parsing when we reach the function bodies. Subsequent
3276 // materialization calls will resume it when necessary. If the bitcode
3277 // file is old, the symbol table will be at the end instead and will not
3278 // have been seen yet. In this case, just finish the parse now.
3279 if (SeenValueSymbolTable) {
3280 NextUnreadBit = Stream.GetCurrentBitNo();
3281 return std::error_code();
3284 case bitc::USELIST_BLOCK_ID:
3285 if (std::error_code EC = parseUseLists())
3288 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3289 if (std::error_code EC = parseOperandBundleTags())
3295 case BitstreamEntry::Record:
3296 // The interesting case.
3302 auto BitCode = Stream.readRecord(Entry.ID, Record);
3304 default: break; // Default behavior, ignore unknown content.
3305 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3306 if (Record.size() < 1)
3307 return error("Invalid record");
3308 // Only version #0 and #1 are supported so far.
3309 unsigned module_version = Record[0];
3310 switch (module_version) {
3312 return error("Invalid value");
3314 UseRelativeIDs = false;
3317 UseRelativeIDs = true;
3322 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3324 if (convertToString(Record, 0, S))
3325 return error("Invalid record");
3326 TheModule->setTargetTriple(S);
3329 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3331 if (convertToString(Record, 0, S))
3332 return error("Invalid record");
3333 TheModule->setDataLayout(S);
3336 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3338 if (convertToString(Record, 0, S))
3339 return error("Invalid record");
3340 TheModule->setModuleInlineAsm(S);
3343 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3344 // FIXME: Remove in 4.0.
3346 if (convertToString(Record, 0, S))
3347 return error("Invalid record");
3351 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3353 if (convertToString(Record, 0, S))
3354 return error("Invalid record");
3355 SectionTable.push_back(S);
3358 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3360 if (convertToString(Record, 0, S))
3361 return error("Invalid record");
3362 GCTable.push_back(S);
3365 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3366 if (Record.size() < 2)
3367 return error("Invalid record");
3368 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3369 unsigned ComdatNameSize = Record[1];
3370 std::string ComdatName;
3371 ComdatName.reserve(ComdatNameSize);
3372 for (unsigned i = 0; i != ComdatNameSize; ++i)
3373 ComdatName += (char)Record[2 + i];
3374 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3375 C->setSelectionKind(SK);
3376 ComdatList.push_back(C);
3379 // GLOBALVAR: [pointer type, isconst, initid,
3380 // linkage, alignment, section, visibility, threadlocal,
3381 // unnamed_addr, externally_initialized, dllstorageclass,
3383 case bitc::MODULE_CODE_GLOBALVAR: {
3384 if (Record.size() < 6)
3385 return error("Invalid record");
3386 Type *Ty = getTypeByID(Record[0]);
3388 return error("Invalid record");
3389 bool isConstant = Record[1] & 1;
3390 bool explicitType = Record[1] & 2;
3391 unsigned AddressSpace;
3393 AddressSpace = Record[1] >> 2;
3395 if (!Ty->isPointerTy())
3396 return error("Invalid type for value");
3397 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3398 Ty = cast<PointerType>(Ty)->getElementType();
3401 uint64_t RawLinkage = Record[3];
3402 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3404 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3406 std::string Section;
3408 if (Record[5]-1 >= SectionTable.size())
3409 return error("Invalid ID");
3410 Section = SectionTable[Record[5]-1];
3412 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3413 // Local linkage must have default visibility.
3414 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3415 // FIXME: Change to an error if non-default in 4.0.
3416 Visibility = getDecodedVisibility(Record[6]);
3418 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3419 if (Record.size() > 7)
3420 TLM = getDecodedThreadLocalMode(Record[7]);
3422 bool UnnamedAddr = false;
3423 if (Record.size() > 8)
3424 UnnamedAddr = Record[8];
3426 bool ExternallyInitialized = false;
3427 if (Record.size() > 9)
3428 ExternallyInitialized = Record[9];
3430 GlobalVariable *NewGV =
3431 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3432 TLM, AddressSpace, ExternallyInitialized);
3433 NewGV->setAlignment(Alignment);
3434 if (!Section.empty())
3435 NewGV->setSection(Section);
3436 NewGV->setVisibility(Visibility);
3437 NewGV->setUnnamedAddr(UnnamedAddr);
3439 if (Record.size() > 10)
3440 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3442 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3444 ValueList.push_back(NewGV);
3446 // Remember which value to use for the global initializer.
3447 if (unsigned InitID = Record[2])
3448 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3450 if (Record.size() > 11) {
3451 if (unsigned ComdatID = Record[11]) {
3452 if (ComdatID > ComdatList.size())
3453 return error("Invalid global variable comdat ID");
3454 NewGV->setComdat(ComdatList[ComdatID - 1]);
3456 } else if (hasImplicitComdat(RawLinkage)) {
3457 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3461 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3462 // alignment, section, visibility, gc, unnamed_addr,
3463 // prologuedata, dllstorageclass, comdat, prefixdata]
3464 case bitc::MODULE_CODE_FUNCTION: {
3465 if (Record.size() < 8)
3466 return error("Invalid record");
3467 Type *Ty = getTypeByID(Record[0]);
3469 return error("Invalid record");
3470 if (auto *PTy = dyn_cast<PointerType>(Ty))
3471 Ty = PTy->getElementType();
3472 auto *FTy = dyn_cast<FunctionType>(Ty);
3474 return error("Invalid type for value");
3475 auto CC = static_cast<CallingConv::ID>(Record[1]);
3476 if (CC & ~CallingConv::MaxID)
3477 return error("Invalid calling convention ID");
3479 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3482 Func->setCallingConv(CC);
3483 bool isProto = Record[2];
3484 uint64_t RawLinkage = Record[3];
3485 Func->setLinkage(getDecodedLinkage(RawLinkage));
3486 Func->setAttributes(getAttributes(Record[4]));
3489 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3491 Func->setAlignment(Alignment);
3493 if (Record[6]-1 >= SectionTable.size())
3494 return error("Invalid ID");
3495 Func->setSection(SectionTable[Record[6]-1]);
3497 // Local linkage must have default visibility.
3498 if (!Func->hasLocalLinkage())
3499 // FIXME: Change to an error if non-default in 4.0.
3500 Func->setVisibility(getDecodedVisibility(Record[7]));
3501 if (Record.size() > 8 && Record[8]) {
3502 if (Record[8]-1 >= GCTable.size())
3503 return error("Invalid ID");
3504 Func->setGC(GCTable[Record[8]-1].c_str());
3506 bool UnnamedAddr = false;
3507 if (Record.size() > 9)
3508 UnnamedAddr = Record[9];
3509 Func->setUnnamedAddr(UnnamedAddr);
3510 if (Record.size() > 10 && Record[10] != 0)
3511 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3513 if (Record.size() > 11)
3514 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3516 upgradeDLLImportExportLinkage(Func, RawLinkage);
3518 if (Record.size() > 12) {
3519 if (unsigned ComdatID = Record[12]) {
3520 if (ComdatID > ComdatList.size())
3521 return error("Invalid function comdat ID");
3522 Func->setComdat(ComdatList[ComdatID - 1]);
3524 } else if (hasImplicitComdat(RawLinkage)) {
3525 Func->setComdat(reinterpret_cast<Comdat *>(1));
3528 if (Record.size() > 13 && Record[13] != 0)
3529 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3531 if (Record.size() > 14 && Record[14] != 0)
3532 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3534 ValueList.push_back(Func);
3536 // If this is a function with a body, remember the prototype we are
3537 // creating now, so that we can match up the body with them later.
3539 Func->setIsMaterializable(true);
3540 FunctionsWithBodies.push_back(Func);
3541 DeferredFunctionInfo[Func] = 0;
3545 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3546 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3547 case bitc::MODULE_CODE_ALIAS:
3548 case bitc::MODULE_CODE_ALIAS_OLD: {
3549 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3550 if (Record.size() < (3 + (unsigned)NewRecord))
3551 return error("Invalid record");
3553 Type *Ty = getTypeByID(Record[OpNum++]);
3555 return error("Invalid record");
3559 auto *PTy = dyn_cast<PointerType>(Ty);
3561 return error("Invalid type for value");
3562 Ty = PTy->getElementType();
3563 AddrSpace = PTy->getAddressSpace();
3565 AddrSpace = Record[OpNum++];
3568 auto Val = Record[OpNum++];
3569 auto Linkage = Record[OpNum++];
3570 auto *NewGA = GlobalAlias::create(
3571 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3572 // Old bitcode files didn't have visibility field.
3573 // Local linkage must have default visibility.
3574 if (OpNum != Record.size()) {
3575 auto VisInd = OpNum++;
3576 if (!NewGA->hasLocalLinkage())
3577 // FIXME: Change to an error if non-default in 4.0.
3578 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3580 if (OpNum != Record.size())
3581 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3583 upgradeDLLImportExportLinkage(NewGA, Linkage);
3584 if (OpNum != Record.size())
3585 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3586 if (OpNum != Record.size())
3587 NewGA->setUnnamedAddr(Record[OpNum++]);
3588 ValueList.push_back(NewGA);
3589 AliasInits.push_back(std::make_pair(NewGA, Val));
3592 /// MODULE_CODE_PURGEVALS: [numvals]
3593 case bitc::MODULE_CODE_PURGEVALS:
3594 // Trim down the value list to the specified size.
3595 if (Record.size() < 1 || Record[0] > ValueList.size())
3596 return error("Invalid record");
3597 ValueList.shrinkTo(Record[0]);
3599 /// MODULE_CODE_VSTOFFSET: [offset]
3600 case bitc::MODULE_CODE_VSTOFFSET:
3601 if (Record.size() < 1)
3602 return error("Invalid record");
3603 VSTOffset = Record[0];
3610 /// Helper to read the header common to all bitcode files.
3611 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3612 // Sniff for the signature.
3613 if (Stream.Read(8) != 'B' ||
3614 Stream.Read(8) != 'C' ||
3615 Stream.Read(4) != 0x0 ||
3616 Stream.Read(4) != 0xC ||
3617 Stream.Read(4) != 0xE ||
3618 Stream.Read(4) != 0xD)
3624 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3625 Module *M, bool ShouldLazyLoadMetadata) {
3628 if (std::error_code EC = initStream(std::move(Streamer)))
3631 // Sniff for the signature.
3632 if (!hasValidBitcodeHeader(Stream))
3633 return error("Invalid bitcode signature");
3635 // We expect a number of well-defined blocks, though we don't necessarily
3636 // need to understand them all.
3638 if (Stream.AtEndOfStream()) {
3639 // We didn't really read a proper Module.
3640 return error("Malformed IR file");
3643 BitstreamEntry Entry =
3644 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3646 if (Entry.Kind != BitstreamEntry::SubBlock)
3647 return error("Malformed block");
3649 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3650 parseBitcodeVersion();
3654 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3655 return parseModule(0, ShouldLazyLoadMetadata);
3657 if (Stream.SkipBlock())
3658 return error("Invalid record");
3662 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3663 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3664 return error("Invalid record");
3666 SmallVector<uint64_t, 64> Record;
3669 // Read all the records for this module.
3671 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3673 switch (Entry.Kind) {
3674 case BitstreamEntry::SubBlock: // Handled for us already.
3675 case BitstreamEntry::Error:
3676 return error("Malformed block");
3677 case BitstreamEntry::EndBlock:
3679 case BitstreamEntry::Record:
3680 // The interesting case.
3685 switch (Stream.readRecord(Entry.ID, Record)) {
3686 default: break; // Default behavior, ignore unknown content.
3687 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3689 if (convertToString(Record, 0, S))
3690 return error("Invalid record");
3697 llvm_unreachable("Exit infinite loop");
3700 ErrorOr<std::string> BitcodeReader::parseTriple() {
3701 if (std::error_code EC = initStream(nullptr))
3704 // Sniff for the signature.
3705 if (!hasValidBitcodeHeader(Stream))
3706 return error("Invalid bitcode signature");
3708 // We expect a number of well-defined blocks, though we don't necessarily
3709 // need to understand them all.
3711 BitstreamEntry Entry = Stream.advance();
3713 switch (Entry.Kind) {
3714 case BitstreamEntry::Error:
3715 return error("Malformed block");
3716 case BitstreamEntry::EndBlock:
3717 return std::error_code();
3719 case BitstreamEntry::SubBlock:
3720 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3721 return parseModuleTriple();
3723 // Ignore other sub-blocks.
3724 if (Stream.SkipBlock())
3725 return error("Malformed block");
3728 case BitstreamEntry::Record:
3729 Stream.skipRecord(Entry.ID);
3735 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3736 if (std::error_code EC = initStream(nullptr))
3739 // Sniff for the signature.
3740 if (!hasValidBitcodeHeader(Stream))
3741 return error("Invalid bitcode signature");
3743 // We expect a number of well-defined blocks, though we don't necessarily
3744 // need to understand them all.
3746 BitstreamEntry Entry = Stream.advance();
3747 switch (Entry.Kind) {
3748 case BitstreamEntry::Error:
3749 return error("Malformed block");
3750 case BitstreamEntry::EndBlock:
3751 return std::error_code();
3753 case BitstreamEntry::SubBlock:
3754 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3755 if (std::error_code EC = parseBitcodeVersion())
3757 return ProducerIdentification;
3759 // Ignore other sub-blocks.
3760 if (Stream.SkipBlock())
3761 return error("Malformed block");
3763 case BitstreamEntry::Record:
3764 Stream.skipRecord(Entry.ID);
3770 /// Parse metadata attachments.
3771 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3772 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3773 return error("Invalid record");
3775 SmallVector<uint64_t, 64> Record;
3777 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3779 switch (Entry.Kind) {
3780 case BitstreamEntry::SubBlock: // Handled for us already.
3781 case BitstreamEntry::Error:
3782 return error("Malformed block");
3783 case BitstreamEntry::EndBlock:
3784 return std::error_code();
3785 case BitstreamEntry::Record:
3786 // The interesting case.
3790 // Read a metadata attachment record.
3792 switch (Stream.readRecord(Entry.ID, Record)) {
3793 default: // Default behavior: ignore.
3795 case bitc::METADATA_ATTACHMENT: {
3796 unsigned RecordLength = Record.size();
3798 return error("Invalid record");
3799 if (RecordLength % 2 == 0) {
3800 // A function attachment.
3801 for (unsigned I = 0; I != RecordLength; I += 2) {
3802 auto K = MDKindMap.find(Record[I]);
3803 if (K == MDKindMap.end())
3804 return error("Invalid ID");
3805 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3806 F.setMetadata(K->second, cast<MDNode>(MD));
3811 // An instruction attachment.
3812 Instruction *Inst = InstructionList[Record[0]];
3813 for (unsigned i = 1; i != RecordLength; i = i+2) {
3814 unsigned Kind = Record[i];
3815 DenseMap<unsigned, unsigned>::iterator I =
3816 MDKindMap.find(Kind);
3817 if (I == MDKindMap.end())
3818 return error("Invalid ID");
3819 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3820 if (isa<LocalAsMetadata>(Node))
3821 // Drop the attachment. This used to be legal, but there's no
3824 Inst->setMetadata(I->second, cast<MDNode>(Node));
3825 if (I->second == LLVMContext::MD_tbaa)
3826 InstsWithTBAATag.push_back(Inst);
3834 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3835 Type *ValType, Type *PtrType) {
3836 if (!isa<PointerType>(PtrType))
3837 return error(DH, "Load/Store operand is not a pointer type");
3838 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3840 if (ValType && ValType != ElemType)
3841 return error(DH, "Explicit load/store type does not match pointee type of "
3843 if (!PointerType::isLoadableOrStorableType(ElemType))
3844 return error(DH, "Cannot load/store from pointer");
3845 return std::error_code();
3848 /// Lazily parse the specified function body block.
3849 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3850 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3851 return error("Invalid record");
3853 InstructionList.clear();
3854 unsigned ModuleValueListSize = ValueList.size();
3855 unsigned ModuleMDValueListSize = MDValueList.size();
3857 // Add all the function arguments to the value table.
3858 for (Argument &I : F->args())
3859 ValueList.push_back(&I);
3861 unsigned NextValueNo = ValueList.size();
3862 BasicBlock *CurBB = nullptr;
3863 unsigned CurBBNo = 0;
3866 auto getLastInstruction = [&]() -> Instruction * {
3867 if (CurBB && !CurBB->empty())
3868 return &CurBB->back();
3869 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3870 !FunctionBBs[CurBBNo - 1]->empty())
3871 return &FunctionBBs[CurBBNo - 1]->back();
3875 std::vector<OperandBundleDef> OperandBundles;
3877 // Read all the records.
3878 SmallVector<uint64_t, 64> Record;
3880 BitstreamEntry Entry = Stream.advance();
3882 switch (Entry.Kind) {
3883 case BitstreamEntry::Error:
3884 return error("Malformed block");
3885 case BitstreamEntry::EndBlock:
3886 goto OutOfRecordLoop;
3888 case BitstreamEntry::SubBlock:
3890 default: // Skip unknown content.
3891 if (Stream.SkipBlock())
3892 return error("Invalid record");
3894 case bitc::CONSTANTS_BLOCK_ID:
3895 if (std::error_code EC = parseConstants())
3897 NextValueNo = ValueList.size();
3899 case bitc::VALUE_SYMTAB_BLOCK_ID:
3900 if (std::error_code EC = parseValueSymbolTable())
3903 case bitc::METADATA_ATTACHMENT_ID:
3904 if (std::error_code EC = parseMetadataAttachment(*F))
3907 case bitc::METADATA_BLOCK_ID:
3908 if (std::error_code EC = parseMetadata())
3911 case bitc::USELIST_BLOCK_ID:
3912 if (std::error_code EC = parseUseLists())
3918 case BitstreamEntry::Record:
3919 // The interesting case.
3925 Instruction *I = nullptr;
3926 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3928 default: // Default behavior: reject
3929 return error("Invalid value");
3930 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3931 if (Record.size() < 1 || Record[0] == 0)
3932 return error("Invalid record");
3933 // Create all the basic blocks for the function.
3934 FunctionBBs.resize(Record[0]);
3936 // See if anything took the address of blocks in this function.
3937 auto BBFRI = BasicBlockFwdRefs.find(F);
3938 if (BBFRI == BasicBlockFwdRefs.end()) {
3939 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3940 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3942 auto &BBRefs = BBFRI->second;
3943 // Check for invalid basic block references.
3944 if (BBRefs.size() > FunctionBBs.size())
3945 return error("Invalid ID");
3946 assert(!BBRefs.empty() && "Unexpected empty array");
3947 assert(!BBRefs.front() && "Invalid reference to entry block");
3948 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3950 if (I < RE && BBRefs[I]) {
3951 BBRefs[I]->insertInto(F);
3952 FunctionBBs[I] = BBRefs[I];
3954 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3957 // Erase from the table.
3958 BasicBlockFwdRefs.erase(BBFRI);
3961 CurBB = FunctionBBs[0];
3965 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3966 // This record indicates that the last instruction is at the same
3967 // location as the previous instruction with a location.
3968 I = getLastInstruction();
3971 return error("Invalid record");
3972 I->setDebugLoc(LastLoc);
3976 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3977 I = getLastInstruction();
3978 if (!I || Record.size() < 4)
3979 return error("Invalid record");
3981 unsigned Line = Record[0], Col = Record[1];
3982 unsigned ScopeID = Record[2], IAID = Record[3];
3984 MDNode *Scope = nullptr, *IA = nullptr;
3985 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3986 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3987 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3988 I->setDebugLoc(LastLoc);
3993 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3996 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3997 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3998 OpNum+1 > Record.size())
3999 return error("Invalid record");
4001 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4003 return error("Invalid record");
4004 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4005 InstructionList.push_back(I);
4006 if (OpNum < Record.size()) {
4007 if (Opc == Instruction::Add ||
4008 Opc == Instruction::Sub ||
4009 Opc == Instruction::Mul ||
4010 Opc == Instruction::Shl) {
4011 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4012 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4013 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4014 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4015 } else if (Opc == Instruction::SDiv ||
4016 Opc == Instruction::UDiv ||
4017 Opc == Instruction::LShr ||
4018 Opc == Instruction::AShr) {
4019 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4020 cast<BinaryOperator>(I)->setIsExact(true);
4021 } else if (isa<FPMathOperator>(I)) {
4022 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4024 I->setFastMathFlags(FMF);
4030 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4033 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4034 OpNum+2 != Record.size())
4035 return error("Invalid record");
4037 Type *ResTy = getTypeByID(Record[OpNum]);
4038 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4039 if (Opc == -1 || !ResTy)
4040 return error("Invalid record");
4041 Instruction *Temp = nullptr;
4042 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4044 InstructionList.push_back(Temp);
4045 CurBB->getInstList().push_back(Temp);
4048 auto CastOp = (Instruction::CastOps)Opc;
4049 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4050 return error("Invalid cast");
4051 I = CastInst::Create(CastOp, Op, ResTy);
4053 InstructionList.push_back(I);
4056 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4057 case bitc::FUNC_CODE_INST_GEP_OLD:
4058 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4064 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4065 InBounds = Record[OpNum++];
4066 Ty = getTypeByID(Record[OpNum++]);
4068 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4073 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4074 return error("Invalid record");
4077 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4080 cast<SequentialType>(BasePtr->getType()->getScalarType())
4083 "Explicit gep type does not match pointee type of pointer operand");
4085 SmallVector<Value*, 16> GEPIdx;
4086 while (OpNum != Record.size()) {
4088 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4089 return error("Invalid record");
4090 GEPIdx.push_back(Op);
4093 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4095 InstructionList.push_back(I);
4097 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4101 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4102 // EXTRACTVAL: [opty, opval, n x indices]
4105 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4106 return error("Invalid record");
4108 unsigned RecSize = Record.size();
4109 if (OpNum == RecSize)
4110 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4112 SmallVector<unsigned, 4> EXTRACTVALIdx;
4113 Type *CurTy = Agg->getType();
4114 for (; OpNum != RecSize; ++OpNum) {
4115 bool IsArray = CurTy->isArrayTy();
4116 bool IsStruct = CurTy->isStructTy();
4117 uint64_t Index = Record[OpNum];
4119 if (!IsStruct && !IsArray)
4120 return error("EXTRACTVAL: Invalid type");
4121 if ((unsigned)Index != Index)
4122 return error("Invalid value");
4123 if (IsStruct && Index >= CurTy->subtypes().size())
4124 return error("EXTRACTVAL: Invalid struct index");
4125 if (IsArray && Index >= CurTy->getArrayNumElements())
4126 return error("EXTRACTVAL: Invalid array index");
4127 EXTRACTVALIdx.push_back((unsigned)Index);
4130 CurTy = CurTy->subtypes()[Index];
4132 CurTy = CurTy->subtypes()[0];
4135 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4136 InstructionList.push_back(I);
4140 case bitc::FUNC_CODE_INST_INSERTVAL: {
4141 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4144 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4145 return error("Invalid record");
4147 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4148 return error("Invalid record");
4150 unsigned RecSize = Record.size();
4151 if (OpNum == RecSize)
4152 return error("INSERTVAL: Invalid instruction with 0 indices");
4154 SmallVector<unsigned, 4> INSERTVALIdx;
4155 Type *CurTy = Agg->getType();
4156 for (; OpNum != RecSize; ++OpNum) {
4157 bool IsArray = CurTy->isArrayTy();
4158 bool IsStruct = CurTy->isStructTy();
4159 uint64_t Index = Record[OpNum];
4161 if (!IsStruct && !IsArray)
4162 return error("INSERTVAL: Invalid type");
4163 if ((unsigned)Index != Index)
4164 return error("Invalid value");
4165 if (IsStruct && Index >= CurTy->subtypes().size())
4166 return error("INSERTVAL: Invalid struct index");
4167 if (IsArray && Index >= CurTy->getArrayNumElements())
4168 return error("INSERTVAL: Invalid array index");
4170 INSERTVALIdx.push_back((unsigned)Index);
4172 CurTy = CurTy->subtypes()[Index];
4174 CurTy = CurTy->subtypes()[0];
4177 if (CurTy != Val->getType())
4178 return error("Inserted value type doesn't match aggregate type");
4180 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4181 InstructionList.push_back(I);
4185 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4186 // obsolete form of select
4187 // handles select i1 ... in old bitcode
4189 Value *TrueVal, *FalseVal, *Cond;
4190 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4191 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4192 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4193 return error("Invalid record");
4195 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4196 InstructionList.push_back(I);
4200 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4201 // new form of select
4202 // handles select i1 or select [N x i1]
4204 Value *TrueVal, *FalseVal, *Cond;
4205 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4206 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4207 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4208 return error("Invalid record");
4210 // select condition can be either i1 or [N x i1]
4211 if (VectorType* vector_type =
4212 dyn_cast<VectorType>(Cond->getType())) {
4214 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4215 return error("Invalid type for value");
4218 if (Cond->getType() != Type::getInt1Ty(Context))
4219 return error("Invalid type for value");
4222 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4223 InstructionList.push_back(I);
4227 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4230 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4231 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4232 return error("Invalid record");
4233 if (!Vec->getType()->isVectorTy())
4234 return error("Invalid type for value");
4235 I = ExtractElementInst::Create(Vec, Idx);
4236 InstructionList.push_back(I);
4240 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4242 Value *Vec, *Elt, *Idx;
4243 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4244 return error("Invalid record");
4245 if (!Vec->getType()->isVectorTy())
4246 return error("Invalid type for value");
4247 if (popValue(Record, OpNum, NextValueNo,
4248 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4249 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4250 return error("Invalid record");
4251 I = InsertElementInst::Create(Vec, Elt, Idx);
4252 InstructionList.push_back(I);
4256 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4258 Value *Vec1, *Vec2, *Mask;
4259 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4260 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4261 return error("Invalid record");
4263 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4264 return error("Invalid record");
4265 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4266 return error("Invalid type for value");
4267 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4268 InstructionList.push_back(I);
4272 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4273 // Old form of ICmp/FCmp returning bool
4274 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4275 // both legal on vectors but had different behaviour.
4276 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4277 // FCmp/ICmp returning bool or vector of bool
4281 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4282 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4283 return error("Invalid record");
4285 unsigned PredVal = Record[OpNum];
4286 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4288 if (IsFP && Record.size() > OpNum+1)
4289 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4291 if (OpNum+1 != Record.size())
4292 return error("Invalid record");
4294 if (LHS->getType()->isFPOrFPVectorTy())
4295 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4297 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4300 I->setFastMathFlags(FMF);
4301 InstructionList.push_back(I);
4305 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4307 unsigned Size = Record.size();
4309 I = ReturnInst::Create(Context);
4310 InstructionList.push_back(I);
4315 Value *Op = nullptr;
4316 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4317 return error("Invalid record");
4318 if (OpNum != Record.size())
4319 return error("Invalid record");
4321 I = ReturnInst::Create(Context, Op);
4322 InstructionList.push_back(I);
4325 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4326 if (Record.size() != 1 && Record.size() != 3)
4327 return error("Invalid record");
4328 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4330 return error("Invalid record");
4332 if (Record.size() == 1) {
4333 I = BranchInst::Create(TrueDest);
4334 InstructionList.push_back(I);
4337 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4338 Value *Cond = getValue(Record, 2, NextValueNo,
4339 Type::getInt1Ty(Context));
4340 if (!FalseDest || !Cond)
4341 return error("Invalid record");
4342 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4343 InstructionList.push_back(I);
4347 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4348 if (Record.size() != 1 && Record.size() != 2)
4349 return error("Invalid record");
4351 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4352 Type::getTokenTy(Context), OC_CleanupPad);
4354 return error("Invalid record");
4355 BasicBlock *UnwindDest = nullptr;
4356 if (Record.size() == 2) {
4357 UnwindDest = getBasicBlock(Record[Idx++]);
4359 return error("Invalid record");
4362 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4364 InstructionList.push_back(I);
4367 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4368 if (Record.size() != 2)
4369 return error("Invalid record");
4371 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4372 Type::getTokenTy(Context), OC_CatchPad);
4374 return error("Invalid record");
4375 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4377 return error("Invalid record");
4379 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4380 InstructionList.push_back(I);
4383 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4384 if (Record.size() < 3)
4385 return error("Invalid record");
4387 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4389 return error("Invalid record");
4390 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4392 return error("Invalid record");
4393 unsigned NumArgOperands = Record[Idx++];
4394 SmallVector<Value *, 2> Args;
4395 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4397 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4398 return error("Invalid record");
4399 Args.push_back(Val);
4401 if (Record.size() != Idx)
4402 return error("Invalid record");
4404 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4405 InstructionList.push_back(I);
4408 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4409 if (Record.size() < 1)
4410 return error("Invalid record");
4412 bool HasUnwindDest = !!Record[Idx++];
4413 BasicBlock *UnwindDest = nullptr;
4414 if (HasUnwindDest) {
4415 if (Idx == Record.size())
4416 return error("Invalid record");
4417 UnwindDest = getBasicBlock(Record[Idx++]);
4419 return error("Invalid record");
4421 unsigned NumArgOperands = Record[Idx++];
4422 SmallVector<Value *, 2> Args;
4423 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4425 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4426 return error("Invalid record");
4427 Args.push_back(Val);
4429 if (Record.size() != Idx)
4430 return error("Invalid record");
4432 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4433 InstructionList.push_back(I);
4436 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4437 if (Record.size() < 1)
4438 return error("Invalid record");
4440 unsigned NumArgOperands = Record[Idx++];
4441 SmallVector<Value *, 2> Args;
4442 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4444 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4445 return error("Invalid record");
4446 Args.push_back(Val);
4448 if (Record.size() != Idx)
4449 return error("Invalid record");
4451 I = CleanupPadInst::Create(Context, Args);
4452 InstructionList.push_back(I);
4455 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4456 if (Record.size() > 1)
4457 return error("Invalid record");
4458 BasicBlock *BB = nullptr;
4459 if (Record.size() == 1) {
4460 BB = getBasicBlock(Record[0]);
4462 return error("Invalid record");
4464 I = CatchEndPadInst::Create(Context, BB);
4465 InstructionList.push_back(I);
4468 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4469 if (Record.size() != 1 && Record.size() != 2)
4470 return error("Invalid record");
4472 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4473 Type::getTokenTy(Context), OC_CleanupPad);
4475 return error("Invalid record");
4477 BasicBlock *BB = nullptr;
4478 if (Record.size() == 2) {
4479 BB = getBasicBlock(Record[Idx++]);
4481 return error("Invalid record");
4483 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4484 InstructionList.push_back(I);
4487 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4489 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4490 // "New" SwitchInst format with case ranges. The changes to write this
4491 // format were reverted but we still recognize bitcode that uses it.
4492 // Hopefully someday we will have support for case ranges and can use
4493 // this format again.
4495 Type *OpTy = getTypeByID(Record[1]);
4496 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4498 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4499 BasicBlock *Default = getBasicBlock(Record[3]);
4500 if (!OpTy || !Cond || !Default)
4501 return error("Invalid record");
4503 unsigned NumCases = Record[4];
4505 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4506 InstructionList.push_back(SI);
4508 unsigned CurIdx = 5;
4509 for (unsigned i = 0; i != NumCases; ++i) {
4510 SmallVector<ConstantInt*, 1> CaseVals;
4511 unsigned NumItems = Record[CurIdx++];
4512 for (unsigned ci = 0; ci != NumItems; ++ci) {
4513 bool isSingleNumber = Record[CurIdx++];
4516 unsigned ActiveWords = 1;
4517 if (ValueBitWidth > 64)
4518 ActiveWords = Record[CurIdx++];
4519 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4521 CurIdx += ActiveWords;
4523 if (!isSingleNumber) {
4525 if (ValueBitWidth > 64)
4526 ActiveWords = Record[CurIdx++];
4527 APInt High = readWideAPInt(
4528 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4529 CurIdx += ActiveWords;
4531 // FIXME: It is not clear whether values in the range should be
4532 // compared as signed or unsigned values. The partially
4533 // implemented changes that used this format in the past used
4534 // unsigned comparisons.
4535 for ( ; Low.ule(High); ++Low)
4536 CaseVals.push_back(ConstantInt::get(Context, Low));
4538 CaseVals.push_back(ConstantInt::get(Context, Low));
4540 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4541 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4542 cve = CaseVals.end(); cvi != cve; ++cvi)
4543 SI->addCase(*cvi, DestBB);
4549 // Old SwitchInst format without case ranges.
4551 if (Record.size() < 3 || (Record.size() & 1) == 0)
4552 return error("Invalid record");
4553 Type *OpTy = getTypeByID(Record[0]);
4554 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4555 BasicBlock *Default = getBasicBlock(Record[2]);
4556 if (!OpTy || !Cond || !Default)
4557 return error("Invalid record");
4558 unsigned NumCases = (Record.size()-3)/2;
4559 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4560 InstructionList.push_back(SI);
4561 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4562 ConstantInt *CaseVal =
4563 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4564 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4565 if (!CaseVal || !DestBB) {
4567 return error("Invalid record");
4569 SI->addCase(CaseVal, DestBB);
4574 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4575 if (Record.size() < 2)
4576 return error("Invalid record");
4577 Type *OpTy = getTypeByID(Record[0]);
4578 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4579 if (!OpTy || !Address)
4580 return error("Invalid record");
4581 unsigned NumDests = Record.size()-2;
4582 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4583 InstructionList.push_back(IBI);
4584 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4585 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4586 IBI->addDestination(DestBB);
4589 return error("Invalid record");
4596 case bitc::FUNC_CODE_INST_INVOKE: {
4597 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4598 if (Record.size() < 4)
4599 return error("Invalid record");
4601 AttributeSet PAL = getAttributes(Record[OpNum++]);
4602 unsigned CCInfo = Record[OpNum++];
4603 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4604 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4606 FunctionType *FTy = nullptr;
4607 if (CCInfo >> 13 & 1 &&
4608 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4609 return error("Explicit invoke type is not a function type");
4612 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4613 return error("Invalid record");
4615 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4617 return error("Callee is not a pointer");
4619 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4621 return error("Callee is not of pointer to function type");
4622 } else if (CalleeTy->getElementType() != FTy)
4623 return error("Explicit invoke type does not match pointee type of "
4625 if (Record.size() < FTy->getNumParams() + OpNum)
4626 return error("Insufficient operands to call");
4628 SmallVector<Value*, 16> Ops;
4629 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4630 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4631 FTy->getParamType(i)));
4633 return error("Invalid record");
4636 if (!FTy->isVarArg()) {
4637 if (Record.size() != OpNum)
4638 return error("Invalid record");
4640 // Read type/value pairs for varargs params.
4641 while (OpNum != Record.size()) {
4643 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4644 return error("Invalid record");
4649 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4650 OperandBundles.clear();
4651 InstructionList.push_back(I);
4652 cast<InvokeInst>(I)->setCallingConv(
4653 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4654 cast<InvokeInst>(I)->setAttributes(PAL);
4657 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4659 Value *Val = nullptr;
4660 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4661 return error("Invalid record");
4662 I = ResumeInst::Create(Val);
4663 InstructionList.push_back(I);
4666 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4667 I = new UnreachableInst(Context);
4668 InstructionList.push_back(I);
4670 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4671 if (Record.size() < 1 || ((Record.size()-1)&1))
4672 return error("Invalid record");
4673 Type *Ty = getTypeByID(Record[0]);
4675 return error("Invalid record");
4677 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4678 InstructionList.push_back(PN);
4680 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4682 // With the new function encoding, it is possible that operands have
4683 // negative IDs (for forward references). Use a signed VBR
4684 // representation to keep the encoding small.
4686 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4688 V = getValue(Record, 1+i, NextValueNo, Ty);
4689 BasicBlock *BB = getBasicBlock(Record[2+i]);
4691 return error("Invalid record");
4692 PN->addIncoming(V, BB);
4698 case bitc::FUNC_CODE_INST_LANDINGPAD:
4699 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4700 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4702 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4703 if (Record.size() < 3)
4704 return error("Invalid record");
4706 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4707 if (Record.size() < 4)
4708 return error("Invalid record");
4710 Type *Ty = getTypeByID(Record[Idx++]);
4712 return error("Invalid record");
4713 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4714 Value *PersFn = nullptr;
4715 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4716 return error("Invalid record");
4718 if (!F->hasPersonalityFn())
4719 F->setPersonalityFn(cast<Constant>(PersFn));
4720 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4721 return error("Personality function mismatch");
4724 bool IsCleanup = !!Record[Idx++];
4725 unsigned NumClauses = Record[Idx++];
4726 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4727 LP->setCleanup(IsCleanup);
4728 for (unsigned J = 0; J != NumClauses; ++J) {
4729 LandingPadInst::ClauseType CT =
4730 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4733 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4735 return error("Invalid record");
4738 assert((CT != LandingPadInst::Catch ||
4739 !isa<ArrayType>(Val->getType())) &&
4740 "Catch clause has a invalid type!");
4741 assert((CT != LandingPadInst::Filter ||
4742 isa<ArrayType>(Val->getType())) &&
4743 "Filter clause has invalid type!");
4744 LP->addClause(cast<Constant>(Val));
4748 InstructionList.push_back(I);
4752 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4753 if (Record.size() != 4)
4754 return error("Invalid record");
4755 uint64_t AlignRecord = Record[3];
4756 const uint64_t InAllocaMask = uint64_t(1) << 5;
4757 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4758 // Reserve bit 7 for SwiftError flag.
4759 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4760 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4761 bool InAlloca = AlignRecord & InAllocaMask;
4762 Type *Ty = getTypeByID(Record[0]);
4763 if ((AlignRecord & ExplicitTypeMask) == 0) {
4764 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4766 return error("Old-style alloca with a non-pointer type");
4767 Ty = PTy->getElementType();
4769 Type *OpTy = getTypeByID(Record[1]);
4770 Value *Size = getFnValueByID(Record[2], OpTy);
4772 if (std::error_code EC =
4773 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4777 return error("Invalid record");
4778 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4779 AI->setUsedWithInAlloca(InAlloca);
4781 InstructionList.push_back(I);
4784 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4787 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4788 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4789 return error("Invalid record");
4792 if (OpNum + 3 == Record.size())
4793 Ty = getTypeByID(Record[OpNum++]);
4794 if (std::error_code EC =
4795 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4798 Ty = cast<PointerType>(Op->getType())->getElementType();
4801 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4803 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4805 InstructionList.push_back(I);
4808 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4809 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4812 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4813 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4814 return error("Invalid record");
4817 if (OpNum + 5 == Record.size())
4818 Ty = getTypeByID(Record[OpNum++]);
4819 if (std::error_code EC =
4820 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4823 Ty = cast<PointerType>(Op->getType())->getElementType();
4825 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4826 if (Ordering == NotAtomic || Ordering == Release ||
4827 Ordering == AcquireRelease)
4828 return error("Invalid record");
4829 if (Ordering != NotAtomic && Record[OpNum] == 0)
4830 return error("Invalid record");
4831 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4834 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4836 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4838 InstructionList.push_back(I);
4841 case bitc::FUNC_CODE_INST_STORE:
4842 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4845 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4846 (BitCode == bitc::FUNC_CODE_INST_STORE
4847 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4848 : popValue(Record, OpNum, NextValueNo,
4849 cast<PointerType>(Ptr->getType())->getElementType(),
4851 OpNum + 2 != Record.size())
4852 return error("Invalid record");
4854 if (std::error_code EC = typeCheckLoadStoreInst(
4855 DiagnosticHandler, Val->getType(), Ptr->getType()))
4858 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4860 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4861 InstructionList.push_back(I);
4864 case bitc::FUNC_CODE_INST_STOREATOMIC:
4865 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4866 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4869 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4870 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4871 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4872 : popValue(Record, OpNum, NextValueNo,
4873 cast<PointerType>(Ptr->getType())->getElementType(),
4875 OpNum + 4 != Record.size())
4876 return error("Invalid record");
4878 if (std::error_code EC = typeCheckLoadStoreInst(
4879 DiagnosticHandler, Val->getType(), Ptr->getType()))
4881 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4882 if (Ordering == NotAtomic || Ordering == Acquire ||
4883 Ordering == AcquireRelease)
4884 return error("Invalid record");
4885 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4886 if (Ordering != NotAtomic && Record[OpNum] == 0)
4887 return error("Invalid record");
4890 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4892 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4893 InstructionList.push_back(I);
4896 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4897 case bitc::FUNC_CODE_INST_CMPXCHG: {
4898 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4899 // failureordering?, isweak?]
4901 Value *Ptr, *Cmp, *New;
4902 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4903 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4904 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4905 : popValue(Record, OpNum, NextValueNo,
4906 cast<PointerType>(Ptr->getType())->getElementType(),
4908 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4909 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4910 return error("Invalid record");
4911 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4912 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4913 return error("Invalid record");
4914 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4916 if (std::error_code EC = typeCheckLoadStoreInst(
4917 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4919 AtomicOrdering FailureOrdering;
4920 if (Record.size() < 7)
4922 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4924 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4926 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4928 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4930 if (Record.size() < 8) {
4931 // Before weak cmpxchgs existed, the instruction simply returned the
4932 // value loaded from memory, so bitcode files from that era will be
4933 // expecting the first component of a modern cmpxchg.
4934 CurBB->getInstList().push_back(I);
4935 I = ExtractValueInst::Create(I, 0);
4937 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4940 InstructionList.push_back(I);
4943 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4944 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4947 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4948 popValue(Record, OpNum, NextValueNo,
4949 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4950 OpNum+4 != Record.size())
4951 return error("Invalid record");
4952 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4953 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4954 Operation > AtomicRMWInst::LAST_BINOP)
4955 return error("Invalid record");
4956 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4957 if (Ordering == NotAtomic || Ordering == Unordered)
4958 return error("Invalid record");
4959 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4960 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4961 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4962 InstructionList.push_back(I);
4965 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4966 if (2 != Record.size())
4967 return error("Invalid record");
4968 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4969 if (Ordering == NotAtomic || Ordering == Unordered ||
4970 Ordering == Monotonic)
4971 return error("Invalid record");
4972 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4973 I = new FenceInst(Context, Ordering, SynchScope);
4974 InstructionList.push_back(I);
4977 case bitc::FUNC_CODE_INST_CALL: {
4978 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4979 if (Record.size() < 3)
4980 return error("Invalid record");
4983 AttributeSet PAL = getAttributes(Record[OpNum++]);
4984 unsigned CCInfo = Record[OpNum++];
4986 FunctionType *FTy = nullptr;
4987 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4988 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4989 return error("Explicit call type is not a function type");
4992 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4993 return error("Invalid record");
4995 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4997 return error("Callee is not a pointer type");
4999 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5001 return error("Callee is not of pointer to function type");
5002 } else if (OpTy->getElementType() != FTy)
5003 return error("Explicit call type does not match pointee type of "
5005 if (Record.size() < FTy->getNumParams() + OpNum)
5006 return error("Insufficient operands to call");
5008 SmallVector<Value*, 16> Args;
5009 // Read the fixed params.
5010 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5011 if (FTy->getParamType(i)->isLabelTy())
5012 Args.push_back(getBasicBlock(Record[OpNum]));
5014 Args.push_back(getValue(Record, OpNum, NextValueNo,
5015 FTy->getParamType(i)));
5017 return error("Invalid record");
5020 // Read type/value pairs for varargs params.
5021 if (!FTy->isVarArg()) {
5022 if (OpNum != Record.size())
5023 return error("Invalid record");
5025 while (OpNum != Record.size()) {
5027 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5028 return error("Invalid record");
5033 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5034 OperandBundles.clear();
5035 InstructionList.push_back(I);
5036 cast<CallInst>(I)->setCallingConv(
5037 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5038 CallInst::TailCallKind TCK = CallInst::TCK_None;
5039 if (CCInfo & 1 << bitc::CALL_TAIL)
5040 TCK = CallInst::TCK_Tail;
5041 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5042 TCK = CallInst::TCK_MustTail;
5043 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5044 TCK = CallInst::TCK_NoTail;
5045 cast<CallInst>(I)->setTailCallKind(TCK);
5046 cast<CallInst>(I)->setAttributes(PAL);
5049 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5050 if (Record.size() < 3)
5051 return error("Invalid record");
5052 Type *OpTy = getTypeByID(Record[0]);
5053 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5054 Type *ResTy = getTypeByID(Record[2]);
5055 if (!OpTy || !Op || !ResTy)
5056 return error("Invalid record");
5057 I = new VAArgInst(Op, ResTy);
5058 InstructionList.push_back(I);
5062 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5063 // A call or an invoke can be optionally prefixed with some variable
5064 // number of operand bundle blocks. These blocks are read into
5065 // OperandBundles and consumed at the next call or invoke instruction.
5067 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5068 return error("Invalid record");
5070 OperandBundles.emplace_back();
5071 OperandBundles.back().Tag = BundleTags[Record[0]];
5073 std::vector<Value *> &Inputs = OperandBundles.back().Inputs;
5076 while (OpNum != Record.size()) {
5078 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5079 return error("Invalid record");
5080 Inputs.push_back(Op);
5087 // Add instruction to end of current BB. If there is no current BB, reject
5091 return error("Invalid instruction with no BB");
5093 if (!OperandBundles.empty()) {
5095 return error("Operand bundles found with no consumer");
5097 CurBB->getInstList().push_back(I);
5099 // If this was a terminator instruction, move to the next block.
5100 if (isa<TerminatorInst>(I)) {
5102 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5105 // Non-void values get registered in the value table for future use.
5106 if (I && !I->getType()->isVoidTy())
5107 if (ValueList.assignValue(I, NextValueNo++))
5108 return error("Invalid forward reference");
5113 if (!OperandBundles.empty())
5114 return error("Operand bundles found with no consumer");
5116 // Check the function list for unresolved values.
5117 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5118 if (!A->getParent()) {
5119 // We found at least one unresolved value. Nuke them all to avoid leaks.
5120 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5121 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5122 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5126 return error("Never resolved value found in function");
5130 // FIXME: Check for unresolved forward-declared metadata references
5131 // and clean up leaks.
5133 // Trim the value list down to the size it was before we parsed this function.
5134 ValueList.shrinkTo(ModuleValueListSize);
5135 MDValueList.shrinkTo(ModuleMDValueListSize);
5136 std::vector<BasicBlock*>().swap(FunctionBBs);
5137 return std::error_code();
5140 /// Find the function body in the bitcode stream
5141 std::error_code BitcodeReader::findFunctionInStream(
5143 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5144 while (DeferredFunctionInfoIterator->second == 0) {
5145 // This is the fallback handling for the old format bitcode that
5146 // didn't contain the function index in the VST, or when we have
5147 // an anonymous function which would not have a VST entry.
5148 // Assert that we have one of those two cases.
5149 assert(VSTOffset == 0 || !F->hasName());
5150 // Parse the next body in the stream and set its position in the
5151 // DeferredFunctionInfo map.
5152 if (std::error_code EC = rememberAndSkipFunctionBodies())
5155 return std::error_code();
5158 //===----------------------------------------------------------------------===//
5159 // GVMaterializer implementation
5160 //===----------------------------------------------------------------------===//
5162 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5164 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5165 if (std::error_code EC = materializeMetadata())
5168 Function *F = dyn_cast<Function>(GV);
5169 // If it's not a function or is already material, ignore the request.
5170 if (!F || !F->isMaterializable())
5171 return std::error_code();
5173 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5174 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5175 // If its position is recorded as 0, its body is somewhere in the stream
5176 // but we haven't seen it yet.
5177 if (DFII->second == 0)
5178 if (std::error_code EC = findFunctionInStream(F, DFII))
5181 // Move the bit stream to the saved position of the deferred function body.
5182 Stream.JumpToBit(DFII->second);
5184 if (std::error_code EC = parseFunctionBody(F))
5186 F->setIsMaterializable(false);
5191 // Upgrade any old intrinsic calls in the function.
5192 for (auto &I : UpgradedIntrinsics) {
5193 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5196 if (CallInst *CI = dyn_cast<CallInst>(U))
5197 UpgradeIntrinsicCall(CI, I.second);
5201 // Finish fn->subprogram upgrade for materialized functions.
5202 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5203 F->setSubprogram(SP);
5205 // Bring in any functions that this function forward-referenced via
5207 return materializeForwardReferencedFunctions();
5210 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5211 const Function *F = dyn_cast<Function>(GV);
5212 if (!F || F->isDeclaration())
5215 // Dematerializing F would leave dangling references that wouldn't be
5216 // reconnected on re-materialization.
5217 if (BlockAddressesTaken.count(F))
5220 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5223 void BitcodeReader::dematerialize(GlobalValue *GV) {
5224 Function *F = dyn_cast<Function>(GV);
5225 // If this function isn't dematerializable, this is a noop.
5226 if (!F || !isDematerializable(F))
5229 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5231 // Just forget the function body, we can remat it later.
5232 F->dropAllReferences();
5233 F->setIsMaterializable(true);
5236 std::error_code BitcodeReader::materializeModule(Module *M) {
5237 assert(M == TheModule &&
5238 "Can only Materialize the Module this BitcodeReader is attached to.");
5240 if (std::error_code EC = materializeMetadata())
5243 // Promise to materialize all forward references.
5244 WillMaterializeAllForwardRefs = true;
5246 // Iterate over the module, deserializing any functions that are still on
5248 for (Function &F : *TheModule) {
5249 if (std::error_code EC = materialize(&F))
5252 // At this point, if there are any function bodies, parse the rest of
5253 // the bits in the module past the last function block we have recorded
5254 // through either lazy scanning or the VST.
5255 if (LastFunctionBlockBit || NextUnreadBit)
5256 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5259 // Check that all block address forward references got resolved (as we
5261 if (!BasicBlockFwdRefs.empty())
5262 return error("Never resolved function from blockaddress");
5264 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5265 // delete the old functions to clean up. We can't do this unless the entire
5266 // module is materialized because there could always be another function body
5267 // with calls to the old function.
5268 for (auto &I : UpgradedIntrinsics) {
5269 for (auto *U : I.first->users()) {
5270 if (CallInst *CI = dyn_cast<CallInst>(U))
5271 UpgradeIntrinsicCall(CI, I.second);
5273 if (!I.first->use_empty())
5274 I.first->replaceAllUsesWith(I.second);
5275 I.first->eraseFromParent();
5277 UpgradedIntrinsics.clear();
5279 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5280 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5282 UpgradeDebugInfo(*M);
5283 return std::error_code();
5286 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5287 return IdentifiedStructTypes;
5291 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5293 return initLazyStream(std::move(Streamer));
5294 return initStreamFromBuffer();
5297 std::error_code BitcodeReader::initStreamFromBuffer() {
5298 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5299 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5301 if (Buffer->getBufferSize() & 3)
5302 return error("Invalid bitcode signature");
5304 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5305 // The magic number is 0x0B17C0DE stored in little endian.
5306 if (isBitcodeWrapper(BufPtr, BufEnd))
5307 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5308 return error("Invalid bitcode wrapper header");
5310 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5311 Stream.init(&*StreamFile);
5313 return std::error_code();
5317 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5318 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5321 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5322 StreamingMemoryObject &Bytes = *OwnedBytes;
5323 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5324 Stream.init(&*StreamFile);
5326 unsigned char buf[16];
5327 if (Bytes.readBytes(buf, 16, 0) != 16)
5328 return error("Invalid bitcode signature");
5330 if (!isBitcode(buf, buf + 16))
5331 return error("Invalid bitcode signature");
5333 if (isBitcodeWrapper(buf, buf + 4)) {
5334 const unsigned char *bitcodeStart = buf;
5335 const unsigned char *bitcodeEnd = buf + 16;
5336 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5337 Bytes.dropLeadingBytes(bitcodeStart - buf);
5338 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5340 return std::error_code();
5343 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5344 const Twine &Message) {
5345 return ::error(DiagnosticHandler, make_error_code(E), Message);
5348 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5349 return ::error(DiagnosticHandler,
5350 make_error_code(BitcodeError::CorruptedBitcode), Message);
5353 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5354 return ::error(DiagnosticHandler, make_error_code(E));
5357 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5358 MemoryBuffer *Buffer, LLVMContext &Context,
5359 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5360 bool CheckFuncSummaryPresenceOnly)
5361 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5362 Buffer(Buffer), IsLazy(IsLazy),
5363 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5365 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5366 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler,
5367 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5368 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5369 Buffer(nullptr), IsLazy(IsLazy),
5370 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5372 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5374 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5376 // Specialized value symbol table parser used when reading function index
5377 // blocks where we don't actually create global values.
5378 // At the end of this routine the function index is populated with a map
5379 // from function name to FunctionInfo. The function info contains
5380 // the function block's bitcode offset as well as the offset into the
5381 // function summary section.
5382 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5383 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5384 return error("Invalid record");
5386 SmallVector<uint64_t, 64> Record;
5388 // Read all the records for this value table.
5389 SmallString<128> ValueName;
5391 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5393 switch (Entry.Kind) {
5394 case BitstreamEntry::SubBlock: // Handled for us already.
5395 case BitstreamEntry::Error:
5396 return error("Malformed block");
5397 case BitstreamEntry::EndBlock:
5398 return std::error_code();
5399 case BitstreamEntry::Record:
5400 // The interesting case.
5406 switch (Stream.readRecord(Entry.ID, Record)) {
5407 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5409 case bitc::VST_CODE_FNENTRY: {
5410 // VST_FNENTRY: [valueid, offset, namechar x N]
5411 if (convertToString(Record, 2, ValueName))
5412 return error("Invalid record");
5413 unsigned ValueID = Record[0];
5414 uint64_t FuncOffset = Record[1];
5415 std::unique_ptr<FunctionInfo> FuncInfo =
5416 llvm::make_unique<FunctionInfo>(FuncOffset);
5417 if (foundFuncSummary() && !IsLazy) {
5418 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5419 SummaryMap.find(ValueID);
5420 assert(SMI != SummaryMap.end() && "Summary info not found");
5421 FuncInfo->setFunctionSummary(std::move(SMI->second));
5423 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5428 case bitc::VST_CODE_COMBINED_FNENTRY: {
5429 // VST_FNENTRY: [offset, namechar x N]
5430 if (convertToString(Record, 1, ValueName))
5431 return error("Invalid record");
5432 uint64_t FuncSummaryOffset = Record[0];
5433 std::unique_ptr<FunctionInfo> FuncInfo =
5434 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5435 if (foundFuncSummary() && !IsLazy) {
5436 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5437 SummaryMap.find(FuncSummaryOffset);
5438 assert(SMI != SummaryMap.end() && "Summary info not found");
5439 FuncInfo->setFunctionSummary(std::move(SMI->second));
5441 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5450 // Parse just the blocks needed for function index building out of the module.
5451 // At the end of this routine the function Index is populated with a map
5452 // from function name to FunctionInfo. The function info contains
5453 // either the parsed function summary information (when parsing summaries
5454 // eagerly), or just to the function summary record's offset
5455 // if parsing lazily (IsLazy).
5456 std::error_code FunctionIndexBitcodeReader::parseModule() {
5457 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5458 return error("Invalid record");
5460 // Read the function index for this module.
5462 BitstreamEntry Entry = Stream.advance();
5464 switch (Entry.Kind) {
5465 case BitstreamEntry::Error:
5466 return error("Malformed block");
5467 case BitstreamEntry::EndBlock:
5468 return std::error_code();
5470 case BitstreamEntry::SubBlock:
5471 if (CheckFuncSummaryPresenceOnly) {
5472 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5473 SeenFuncSummary = true;
5474 if (Stream.SkipBlock())
5475 return error("Invalid record");
5476 // No need to parse the rest since we found the summary.
5477 return std::error_code();
5480 default: // Skip unknown content.
5481 if (Stream.SkipBlock())
5482 return error("Invalid record");
5484 case bitc::BLOCKINFO_BLOCK_ID:
5485 // Need to parse these to get abbrev ids (e.g. for VST)
5486 if (Stream.ReadBlockInfoBlock())
5487 return error("Malformed block");
5489 case bitc::VALUE_SYMTAB_BLOCK_ID:
5490 if (std::error_code EC = parseValueSymbolTable())
5493 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5494 SeenFuncSummary = true;
5496 // Lazy parsing of summary info, skip it.
5497 if (Stream.SkipBlock())
5498 return error("Invalid record");
5499 } else if (std::error_code EC = parseEntireSummary())
5502 case bitc::MODULE_STRTAB_BLOCK_ID:
5503 if (std::error_code EC = parseModuleStringTable())
5509 case BitstreamEntry::Record:
5510 Stream.skipRecord(Entry.ID);
5516 // Eagerly parse the entire function summary block (i.e. for all functions
5517 // in the index). This populates the FunctionSummary objects in
5519 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5520 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5521 return error("Invalid record");
5523 SmallVector<uint64_t, 64> Record;
5526 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5528 switch (Entry.Kind) {
5529 case BitstreamEntry::SubBlock: // Handled for us already.
5530 case BitstreamEntry::Error:
5531 return error("Malformed block");
5532 case BitstreamEntry::EndBlock:
5533 return std::error_code();
5534 case BitstreamEntry::Record:
5535 // The interesting case.
5539 // Read a record. The record format depends on whether this
5540 // is a per-module index or a combined index file. In the per-module
5541 // case the records contain the associated value's ID for correlation
5542 // with VST entries. In the combined index the correlation is done
5543 // via the bitcode offset of the summary records (which were saved
5544 // in the combined index VST entries). The records also contain
5545 // information used for ThinLTO renaming and importing.
5547 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5548 switch (Stream.readRecord(Entry.ID, Record)) {
5549 default: // Default behavior: ignore.
5551 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5552 case bitc::FS_CODE_PERMODULE_ENTRY: {
5553 unsigned ValueID = Record[0];
5554 bool IsLocal = Record[1];
5555 unsigned InstCount = Record[2];
5556 std::unique_ptr<FunctionSummary> FS =
5557 llvm::make_unique<FunctionSummary>(InstCount);
5558 FS->setLocalFunction(IsLocal);
5559 // The module path string ref set in the summary must be owned by the
5560 // index's module string table. Since we don't have a module path
5561 // string table section in the per-module index, we create a single
5562 // module path string table entry with an empty (0) ID to take
5565 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5566 SummaryMap[ValueID] = std::move(FS);
5568 // FS_COMBINED_ENTRY: [modid, instcount]
5569 case bitc::FS_CODE_COMBINED_ENTRY: {
5570 uint64_t ModuleId = Record[0];
5571 unsigned InstCount = Record[1];
5572 std::unique_ptr<FunctionSummary> FS =
5573 llvm::make_unique<FunctionSummary>(InstCount);
5574 FS->setModulePath(ModuleIdMap[ModuleId]);
5575 SummaryMap[CurRecordBit] = std::move(FS);
5579 llvm_unreachable("Exit infinite loop");
5582 // Parse the module string table block into the Index.
5583 // This populates the ModulePathStringTable map in the index.
5584 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5585 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5586 return error("Invalid record");
5588 SmallVector<uint64_t, 64> Record;
5590 SmallString<128> ModulePath;
5592 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5594 switch (Entry.Kind) {
5595 case BitstreamEntry::SubBlock: // Handled for us already.
5596 case BitstreamEntry::Error:
5597 return error("Malformed block");
5598 case BitstreamEntry::EndBlock:
5599 return std::error_code();
5600 case BitstreamEntry::Record:
5601 // The interesting case.
5606 switch (Stream.readRecord(Entry.ID, Record)) {
5607 default: // Default behavior: ignore.
5609 case bitc::MST_CODE_ENTRY: {
5610 // MST_ENTRY: [modid, namechar x N]
5611 if (convertToString(Record, 1, ModulePath))
5612 return error("Invalid record");
5613 uint64_t ModuleId = Record[0];
5614 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5615 ModuleIdMap[ModuleId] = ModulePathInMap;
5621 llvm_unreachable("Exit infinite loop");
5624 // Parse the function info index from the bitcode streamer into the given index.
5625 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5626 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5629 if (std::error_code EC = initStream(std::move(Streamer)))
5632 // Sniff for the signature.
5633 if (!hasValidBitcodeHeader(Stream))
5634 return error("Invalid bitcode signature");
5636 // We expect a number of well-defined blocks, though we don't necessarily
5637 // need to understand them all.
5639 if (Stream.AtEndOfStream()) {
5640 // We didn't really read a proper Module block.
5641 return error("Malformed block");
5644 BitstreamEntry Entry =
5645 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5647 if (Entry.Kind != BitstreamEntry::SubBlock)
5648 return error("Malformed block");
5650 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5651 // building the function summary index.
5652 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5653 return parseModule();
5655 if (Stream.SkipBlock())
5656 return error("Invalid record");
5660 // Parse the function information at the given offset in the buffer into
5661 // the index. Used to support lazy parsing of function summaries from the
5662 // combined index during importing.
5663 // TODO: This function is not yet complete as it won't have a consumer
5664 // until ThinLTO function importing is added.
5665 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5666 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5667 size_t FunctionSummaryOffset) {
5670 if (std::error_code EC = initStream(std::move(Streamer)))
5673 // Sniff for the signature.
5674 if (!hasValidBitcodeHeader(Stream))
5675 return error("Invalid bitcode signature");
5677 Stream.JumpToBit(FunctionSummaryOffset);
5679 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5681 switch (Entry.Kind) {
5683 return error("Malformed block");
5684 case BitstreamEntry::Record:
5685 // The expected case.
5689 // TODO: Read a record. This interface will be completed when ThinLTO
5690 // importing is added so that it can be tested.
5691 SmallVector<uint64_t, 64> Record;
5692 switch (Stream.readRecord(Entry.ID, Record)) {
5693 case bitc::FS_CODE_COMBINED_ENTRY:
5695 return error("Invalid record");
5698 return std::error_code();
5702 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5704 return initLazyStream(std::move(Streamer));
5705 return initStreamFromBuffer();
5708 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5709 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5710 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5712 if (Buffer->getBufferSize() & 3)
5713 return error("Invalid bitcode signature");
5715 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5716 // The magic number is 0x0B17C0DE stored in little endian.
5717 if (isBitcodeWrapper(BufPtr, BufEnd))
5718 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5719 return error("Invalid bitcode wrapper header");
5721 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5722 Stream.init(&*StreamFile);
5724 return std::error_code();
5727 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5728 std::unique_ptr<DataStreamer> Streamer) {
5729 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5732 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5733 StreamingMemoryObject &Bytes = *OwnedBytes;
5734 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5735 Stream.init(&*StreamFile);
5737 unsigned char buf[16];
5738 if (Bytes.readBytes(buf, 16, 0) != 16)
5739 return error("Invalid bitcode signature");
5741 if (!isBitcode(buf, buf + 16))
5742 return error("Invalid bitcode signature");
5744 if (isBitcodeWrapper(buf, buf + 4)) {
5745 const unsigned char *bitcodeStart = buf;
5746 const unsigned char *bitcodeEnd = buf + 16;
5747 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5748 Bytes.dropLeadingBytes(bitcodeStart - buf);
5749 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5751 return std::error_code();
5755 class BitcodeErrorCategoryType : public std::error_category {
5756 const char *name() const LLVM_NOEXCEPT override {
5757 return "llvm.bitcode";
5759 std::string message(int IE) const override {
5760 BitcodeError E = static_cast<BitcodeError>(IE);
5762 case BitcodeError::InvalidBitcodeSignature:
5763 return "Invalid bitcode signature";
5764 case BitcodeError::CorruptedBitcode:
5765 return "Corrupted bitcode";
5767 llvm_unreachable("Unknown error type!");
5772 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5774 const std::error_category &llvm::BitcodeErrorCategory() {
5775 return *ErrorCategory;
5778 //===----------------------------------------------------------------------===//
5779 // External interface
5780 //===----------------------------------------------------------------------===//
5782 static ErrorOr<std::unique_ptr<Module>>
5783 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5784 BitcodeReader *R, LLVMContext &Context,
5785 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5786 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5787 M->setMaterializer(R);
5789 auto cleanupOnError = [&](std::error_code EC) {
5790 R->releaseBuffer(); // Never take ownership on error.
5794 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5795 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5796 ShouldLazyLoadMetadata))
5797 return cleanupOnError(EC);
5799 if (MaterializeAll) {
5800 // Read in the entire module, and destroy the BitcodeReader.
5801 if (std::error_code EC = M->materializeAllPermanently())
5802 return cleanupOnError(EC);
5804 // Resolve forward references from blockaddresses.
5805 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5806 return cleanupOnError(EC);
5808 return std::move(M);
5811 /// \brief Get a lazy one-at-time loading module from bitcode.
5813 /// This isn't always used in a lazy context. In particular, it's also used by
5814 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5815 /// in forward-referenced functions from block address references.
5817 /// \param[in] MaterializeAll Set to \c true if we should materialize
5819 static ErrorOr<std::unique_ptr<Module>>
5820 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5821 LLVMContext &Context, bool MaterializeAll,
5822 DiagnosticHandlerFunction DiagnosticHandler,
5823 bool ShouldLazyLoadMetadata = false) {
5825 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5827 ErrorOr<std::unique_ptr<Module>> Ret =
5828 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5829 MaterializeAll, ShouldLazyLoadMetadata);
5833 Buffer.release(); // The BitcodeReader owns it now.
5837 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5838 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5839 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5840 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5841 DiagnosticHandler, ShouldLazyLoadMetadata);
5844 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5845 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5846 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5847 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5848 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5850 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5854 ErrorOr<std::unique_ptr<Module>>
5855 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5856 DiagnosticHandlerFunction DiagnosticHandler) {
5857 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5858 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5860 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5861 // written. We must defer until the Module has been fully materialized.
5865 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5866 DiagnosticHandlerFunction DiagnosticHandler) {
5867 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5868 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5870 ErrorOr<std::string> Triple = R->parseTriple();
5871 if (Triple.getError())
5873 return Triple.get();
5877 llvm::getBitcodeProducerString(MemoryBufferRef Buffer, LLVMContext &Context,
5878 DiagnosticHandlerFunction DiagnosticHandler) {
5879 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5880 BitcodeReader R(Buf.release(), Context, DiagnosticHandler);
5881 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5882 if (ProducerString.getError())
5884 return ProducerString.get();
5887 // Parse the specified bitcode buffer, returning the function info index.
5888 // If IsLazy is false, parse the entire function summary into
5889 // the index. Otherwise skip the function summary section, and only create
5890 // an index object with a map from function name to function summary offset.
5891 // The index is used to perform lazy function summary reading later.
5892 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5893 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer, LLVMContext &Context,
5894 DiagnosticHandlerFunction DiagnosticHandler,
5895 const Module *ExportingModule, bool IsLazy) {
5896 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5897 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, IsLazy);
5899 std::unique_ptr<FunctionInfoIndex> Index =
5900 llvm::make_unique<FunctionInfoIndex>(ExportingModule);
5902 auto cleanupOnError = [&](std::error_code EC) {
5903 R.releaseBuffer(); // Never take ownership on error.
5907 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5908 return cleanupOnError(EC);
5910 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5911 return std::move(Index);
5914 // Check if the given bitcode buffer contains a function summary block.
5915 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5916 DiagnosticHandlerFunction DiagnosticHandler) {
5917 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5918 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, false,
5921 auto cleanupOnError = [&](std::error_code EC) {
5922 R.releaseBuffer(); // Never take ownership on error.
5926 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5927 return cleanupOnError(EC);
5929 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5930 return R.foundFuncSummary();
5933 // This method supports lazy reading of function summary data from the combined
5934 // index during ThinLTO function importing. When reading the combined index
5935 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5936 // Then this method is called for each function considered for importing,
5937 // to parse the summary information for the given function name into
5940 llvm::readFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5941 DiagnosticHandlerFunction DiagnosticHandler,
5942 StringRef FunctionName,
5943 std::unique_ptr<FunctionInfoIndex> Index) {
5944 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5945 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler);
5947 auto cleanupOnError = [&](std::error_code EC) {
5948 R.releaseBuffer(); // Never take ownership on error.
5952 // Lookup the given function name in the FunctionMap, which may
5953 // contain a list of function infos in the case of a COMDAT. Walk through
5954 // and parse each function summary info at the function summary offset
5955 // recorded when parsing the value symbol table.
5956 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5957 size_t FunctionSummaryOffset = FI->bitcodeIndex();
5958 if (std::error_code EC =
5959 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5960 return cleanupOnError(EC);
5963 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5964 return std::error_code();