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/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/Bitcode/BitstreamReader.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/Bitcode/ReaderWriter.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/DebugInfoMetadata.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/DiagnosticPrinter.h"
24 #include "llvm/IR/GVMaterializer.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ModuleSummaryIndex.h"
30 #include "llvm/IR/OperandTraits.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/DataStream.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/raw_ostream.h"
45 static cl::opt<bool> PrintSummaryGUIDs(
46 "print-summary-global-ids", cl::init(false), cl::Hidden,
48 "Print the global id for each value when reading the module summary"));
52 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
55 class BitcodeReaderValueList {
56 std::vector<WeakVH> ValuePtrs;
58 /// As we resolve forward-referenced constants, we add information about them
59 /// to this vector. This allows us to resolve them in bulk instead of
60 /// resolving each reference at a time. See the code in
61 /// ResolveConstantForwardRefs for more information about this.
63 /// The key of this vector is the placeholder constant, the value is the slot
64 /// number that holds the resolved value.
65 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
66 ResolveConstantsTy ResolveConstants;
69 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
70 ~BitcodeReaderValueList() {
71 assert(ResolveConstants.empty() && "Constants not resolved?");
74 // vector compatibility methods
75 unsigned size() const { return ValuePtrs.size(); }
76 void resize(unsigned N) { ValuePtrs.resize(N); }
77 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
80 assert(ResolveConstants.empty() && "Constants not resolved?");
84 Value *operator[](unsigned i) const {
85 assert(i < ValuePtrs.size());
89 Value *back() const { return ValuePtrs.back(); }
90 void pop_back() { ValuePtrs.pop_back(); }
91 bool empty() const { return ValuePtrs.empty(); }
92 void shrinkTo(unsigned N) {
93 assert(N <= size() && "Invalid shrinkTo request!");
97 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
98 Value *getValueFwdRef(unsigned Idx, Type *Ty);
100 void assignValue(Value *V, unsigned Idx);
102 /// Once all constants are read, this method bulk resolves any forward
104 void resolveConstantForwardRefs();
107 class BitcodeReaderMetadataList {
113 /// Array of metadata references.
115 /// Don't use std::vector here. Some versions of libc++ copy (instead of
116 /// move) on resize, and TrackingMDRef is very expensive to copy.
117 SmallVector<TrackingMDRef, 1> MetadataPtrs;
119 /// Structures for resolving old type refs.
121 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
122 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
123 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
124 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
127 LLVMContext &Context;
129 BitcodeReaderMetadataList(LLVMContext &C)
130 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
132 // vector compatibility methods
133 unsigned size() const { return MetadataPtrs.size(); }
134 void resize(unsigned N) { MetadataPtrs.resize(N); }
135 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
136 void clear() { MetadataPtrs.clear(); }
137 Metadata *back() const { return MetadataPtrs.back(); }
138 void pop_back() { MetadataPtrs.pop_back(); }
139 bool empty() const { return MetadataPtrs.empty(); }
141 Metadata *operator[](unsigned i) const {
142 assert(i < MetadataPtrs.size());
143 return MetadataPtrs[i];
146 Metadata *lookup(unsigned I) const {
147 if (I < MetadataPtrs.size())
148 return MetadataPtrs[I];
152 void shrinkTo(unsigned N) {
153 assert(N <= size() && "Invalid shrinkTo request!");
154 assert(!AnyFwdRefs && "Unexpected forward refs");
155 MetadataPtrs.resize(N);
158 /// Return the given metadata, creating a replaceable forward reference if
160 Metadata *getMetadataFwdRef(unsigned Idx);
162 /// Return the the given metadata only if it is fully resolved.
164 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
165 /// would give \c false.
166 Metadata *getMetadataIfResolved(unsigned Idx);
168 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
169 void assignValue(Metadata *MD, unsigned Idx);
170 void tryToResolveCycles();
171 bool hasFwdRefs() const { return AnyFwdRefs; }
173 /// Upgrade a type that had an MDString reference.
174 void addTypeRef(MDString &UUID, DICompositeType &CT);
176 /// Upgrade a type that had an MDString reference.
177 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
179 /// Upgrade a type ref array that may have MDString references.
180 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
183 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
186 class BitcodeReader : public GVMaterializer {
187 LLVMContext &Context;
188 Module *TheModule = nullptr;
189 std::unique_ptr<MemoryBuffer> Buffer;
190 std::unique_ptr<BitstreamReader> StreamFile;
191 BitstreamCursor Stream;
192 // Next offset to start scanning for lazy parsing of function bodies.
193 uint64_t NextUnreadBit = 0;
194 // Last function offset found in the VST.
195 uint64_t LastFunctionBlockBit = 0;
196 bool SeenValueSymbolTable = false;
197 uint64_t VSTOffset = 0;
198 // Contains an arbitrary and optional string identifying the bitcode producer
199 std::string ProducerIdentification;
201 std::vector<Type*> TypeList;
202 BitcodeReaderValueList ValueList;
203 BitcodeReaderMetadataList MetadataList;
204 std::vector<Comdat *> ComdatList;
205 SmallVector<Instruction *, 64> InstructionList;
207 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
208 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
209 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
210 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
211 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
213 SmallVector<Instruction*, 64> InstsWithTBAATag;
215 bool HasSeenOldLoopTags = false;
217 /// The set of attributes by index. Index zero in the file is for null, and
218 /// is thus not represented here. As such all indices are off by one.
219 std::vector<AttributeSet> MAttributes;
221 /// The set of attribute groups.
222 std::map<unsigned, AttributeSet> MAttributeGroups;
224 /// While parsing a function body, this is a list of the basic blocks for the
226 std::vector<BasicBlock*> FunctionBBs;
228 // When reading the module header, this list is populated with functions that
229 // have bodies later in the file.
230 std::vector<Function*> FunctionsWithBodies;
232 // When intrinsic functions are encountered which require upgrading they are
233 // stored here with their replacement function.
234 typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
235 UpdatedIntrinsicMap UpgradedIntrinsics;
236 // Intrinsics which were remangled because of types rename
237 UpdatedIntrinsicMap RemangledIntrinsics;
239 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
240 DenseMap<unsigned, unsigned> MDKindMap;
242 // Several operations happen after the module header has been read, but
243 // before function bodies are processed. This keeps track of whether
244 // we've done this yet.
245 bool SeenFirstFunctionBody = false;
247 /// When function bodies are initially scanned, this map contains info about
248 /// where to find deferred function body in the stream.
249 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
251 /// When Metadata block is initially scanned when parsing the module, we may
252 /// choose to defer parsing of the metadata. This vector contains info about
253 /// which Metadata blocks are deferred.
254 std::vector<uint64_t> DeferredMetadataInfo;
256 /// These are basic blocks forward-referenced by block addresses. They are
257 /// inserted lazily into functions when they're loaded. The basic block ID is
258 /// its index into the vector.
259 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
260 std::deque<Function *> BasicBlockFwdRefQueue;
262 /// Indicates that we are using a new encoding for instruction operands where
263 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
264 /// instruction number, for a more compact encoding. Some instruction
265 /// operands are not relative to the instruction ID: basic block numbers, and
266 /// types. Once the old style function blocks have been phased out, we would
267 /// not need this flag.
268 bool UseRelativeIDs = false;
270 /// True if all functions will be materialized, negating the need to process
271 /// (e.g.) blockaddress forward references.
272 bool WillMaterializeAllForwardRefs = false;
274 /// True if any Metadata block has been materialized.
275 bool IsMetadataMaterialized = false;
277 bool StripDebugInfo = false;
279 /// Functions that need to be matched with subprograms when upgrading old
281 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
283 std::vector<std::string> BundleTags;
286 std::error_code error(BitcodeError E, const Twine &Message);
287 std::error_code error(const Twine &Message);
289 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
290 BitcodeReader(LLVMContext &Context);
291 ~BitcodeReader() override { freeState(); }
293 std::error_code materializeForwardReferencedFunctions();
297 void releaseBuffer();
299 std::error_code materialize(GlobalValue *GV) override;
300 std::error_code materializeModule() override;
301 std::vector<StructType *> getIdentifiedStructTypes() const override;
303 /// \brief Main interface to parsing a bitcode buffer.
304 /// \returns true if an error occurred.
305 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
307 bool ShouldLazyLoadMetadata = false);
309 /// \brief Cheap mechanism to just extract module triple
310 /// \returns true if an error occurred.
311 ErrorOr<std::string> parseTriple();
313 /// Cheap mechanism to just extract the identification block out of bitcode.
314 ErrorOr<std::string> parseIdentificationBlock();
316 /// Peak at the module content and return true if any ObjC category or class
318 ErrorOr<bool> hasObjCCategory();
320 static uint64_t decodeSignRotatedValue(uint64_t V);
322 /// Materialize any deferred Metadata block.
323 std::error_code materializeMetadata() override;
325 void setStripDebugInfo() override;
328 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
329 // ProducerIdentification data member, and do some basic enforcement on the
330 // "epoch" encoded in the bitcode.
331 std::error_code parseBitcodeVersion();
333 std::vector<StructType *> IdentifiedStructTypes;
334 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
335 StructType *createIdentifiedStructType(LLVMContext &Context);
337 Type *getTypeByID(unsigned ID);
338 Value *getFnValueByID(unsigned ID, Type *Ty) {
339 if (Ty && Ty->isMetadataTy())
340 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
341 return ValueList.getValueFwdRef(ID, Ty);
343 Metadata *getFnMetadataByID(unsigned ID) {
344 return MetadataList.getMetadataFwdRef(ID);
346 BasicBlock *getBasicBlock(unsigned ID) const {
347 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
348 return FunctionBBs[ID];
350 AttributeSet getAttributes(unsigned i) const {
351 if (i-1 < MAttributes.size())
352 return MAttributes[i-1];
353 return AttributeSet();
356 /// Read a value/type pair out of the specified record from slot 'Slot'.
357 /// Increment Slot past the number of slots used in the record. Return true on
359 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
360 unsigned InstNum, Value *&ResVal) {
361 if (Slot == Record.size()) return true;
362 unsigned ValNo = (unsigned)Record[Slot++];
363 // Adjust the ValNo, if it was encoded relative to the InstNum.
365 ValNo = InstNum - ValNo;
366 if (ValNo < InstNum) {
367 // If this is not a forward reference, just return the value we already
369 ResVal = getFnValueByID(ValNo, nullptr);
370 return ResVal == nullptr;
372 if (Slot == Record.size())
375 unsigned TypeNo = (unsigned)Record[Slot++];
376 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
377 return ResVal == nullptr;
380 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
381 /// past the number of slots used by the value in the record. Return true if
382 /// there is an error.
383 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
384 unsigned InstNum, Type *Ty, Value *&ResVal) {
385 if (getValue(Record, Slot, InstNum, Ty, ResVal))
387 // All values currently take a single record slot.
392 /// Like popValue, but does not increment the Slot number.
393 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
394 unsigned InstNum, Type *Ty, Value *&ResVal) {
395 ResVal = getValue(Record, Slot, InstNum, Ty);
396 return ResVal == nullptr;
399 /// Version of getValue that returns ResVal directly, or 0 if there is an
401 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
402 unsigned InstNum, Type *Ty) {
403 if (Slot == Record.size()) return nullptr;
404 unsigned ValNo = (unsigned)Record[Slot];
405 // Adjust the ValNo, if it was encoded relative to the InstNum.
407 ValNo = InstNum - ValNo;
408 return getFnValueByID(ValNo, Ty);
411 /// Like getValue, but decodes signed VBRs.
412 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
413 unsigned InstNum, Type *Ty) {
414 if (Slot == Record.size()) return nullptr;
415 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
416 // Adjust the ValNo, if it was encoded relative to the InstNum.
418 ValNo = InstNum - ValNo;
419 return getFnValueByID(ValNo, Ty);
422 /// Converts alignment exponent (i.e. power of two (or zero)) to the
423 /// corresponding alignment to use. If alignment is too large, returns
424 /// a corresponding error code.
425 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
426 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
427 std::error_code parseModule(uint64_t ResumeBit,
428 bool ShouldLazyLoadMetadata = false);
429 std::error_code parseAttributeBlock();
430 std::error_code parseAttributeGroupBlock();
431 std::error_code parseTypeTable();
432 std::error_code parseTypeTableBody();
433 std::error_code parseOperandBundleTags();
435 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
436 unsigned NameIndex, Triple &TT);
437 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
438 std::error_code parseConstants();
439 std::error_code rememberAndSkipFunctionBodies();
440 std::error_code rememberAndSkipFunctionBody();
441 /// Save the positions of the Metadata blocks and skip parsing the blocks.
442 std::error_code rememberAndSkipMetadata();
443 std::error_code parseFunctionBody(Function *F);
444 std::error_code globalCleanup();
445 std::error_code resolveGlobalAndIndirectSymbolInits();
446 std::error_code parseMetadata(bool ModuleLevel = false);
447 std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
449 unsigned &NextMetadataNo);
450 std::error_code parseMetadataKinds();
451 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
453 parseGlobalObjectAttachment(GlobalObject &GO,
454 ArrayRef<uint64_t> Record);
455 std::error_code parseMetadataAttachment(Function &F);
456 ErrorOr<std::string> parseModuleTriple();
457 ErrorOr<bool> hasObjCCategoryInModule();
458 std::error_code parseUseLists();
459 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
460 std::error_code initStreamFromBuffer();
461 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
462 std::error_code findFunctionInStream(
464 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
467 /// Class to manage reading and parsing function summary index bitcode
469 class ModuleSummaryIndexBitcodeReader {
470 DiagnosticHandlerFunction DiagnosticHandler;
472 /// Eventually points to the module index built during parsing.
473 ModuleSummaryIndex *TheIndex = nullptr;
475 std::unique_ptr<MemoryBuffer> Buffer;
476 std::unique_ptr<BitstreamReader> StreamFile;
477 BitstreamCursor Stream;
479 /// Used to indicate whether caller only wants to check for the presence
480 /// of the global value summary bitcode section. All blocks are skipped,
481 /// but the SeenGlobalValSummary boolean is set.
482 bool CheckGlobalValSummaryPresenceOnly = false;
484 /// Indicates whether we have encountered a global value summary section
485 /// yet during parsing, used when checking if file contains global value
487 bool SeenGlobalValSummary = false;
489 /// Indicates whether we have already parsed the VST, used for error checking.
490 bool SeenValueSymbolTable = false;
492 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
493 /// Used to enable on-demand parsing of the VST.
494 uint64_t VSTOffset = 0;
496 // Map to save ValueId to GUID association that was recorded in the
497 // ValueSymbolTable. It is used after the VST is parsed to convert
498 // call graph edges read from the function summary from referencing
499 // callees by their ValueId to using the GUID instead, which is how
500 // they are recorded in the summary index being built.
501 // We save a second GUID which is the same as the first one, but ignoring the
502 // linkage, i.e. for value other than local linkage they are identical.
503 DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
504 ValueIdToCallGraphGUIDMap;
506 /// Map populated during module path string table parsing, from the
507 /// module ID to a string reference owned by the index's module
508 /// path string table, used to correlate with combined index
510 DenseMap<uint64_t, StringRef> ModuleIdMap;
512 /// Original source file name recorded in a bitcode record.
513 std::string SourceFileName;
516 std::error_code error(const Twine &Message);
518 ModuleSummaryIndexBitcodeReader(
519 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
520 bool CheckGlobalValSummaryPresenceOnly = false);
521 ~ModuleSummaryIndexBitcodeReader() { freeState(); }
525 void releaseBuffer();
527 /// Check if the parser has encountered a summary section.
528 bool foundGlobalValSummary() { return SeenGlobalValSummary; }
530 /// \brief Main interface to parsing a bitcode buffer.
531 /// \returns true if an error occurred.
532 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
533 ModuleSummaryIndex *I);
536 std::error_code parseModule();
537 std::error_code parseValueSymbolTable(
539 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
540 std::error_code parseEntireSummary();
541 std::error_code parseModuleStringTable();
542 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
543 std::error_code initStreamFromBuffer();
544 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
545 std::pair<GlobalValue::GUID, GlobalValue::GUID>
546 getGUIDFromValueId(unsigned ValueId);
548 } // end anonymous namespace
550 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
551 DiagnosticSeverity Severity,
553 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
555 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
557 static std::error_code error(const DiagnosticHandlerFunction &DiagnosticHandler,
558 std::error_code EC, const Twine &Message) {
559 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
560 DiagnosticHandler(DI);
564 static std::error_code error(LLVMContext &Context, std::error_code EC,
565 const Twine &Message) {
566 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
570 static std::error_code error(LLVMContext &Context, const Twine &Message) {
571 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
575 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
576 if (!ProducerIdentification.empty()) {
577 return ::error(Context, make_error_code(E),
578 Message + " (Producer: '" + ProducerIdentification +
579 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
581 return ::error(Context, make_error_code(E), Message);
584 std::error_code BitcodeReader::error(const Twine &Message) {
585 if (!ProducerIdentification.empty()) {
586 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
587 Message + " (Producer: '" + ProducerIdentification +
588 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
590 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
594 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
595 : Context(Context), Buffer(Buffer), ValueList(Context),
596 MetadataList(Context) {}
598 BitcodeReader::BitcodeReader(LLVMContext &Context)
599 : Context(Context), Buffer(nullptr), ValueList(Context),
600 MetadataList(Context) {}
602 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
603 if (WillMaterializeAllForwardRefs)
604 return std::error_code();
606 // Prevent recursion.
607 WillMaterializeAllForwardRefs = true;
609 while (!BasicBlockFwdRefQueue.empty()) {
610 Function *F = BasicBlockFwdRefQueue.front();
611 BasicBlockFwdRefQueue.pop_front();
612 assert(F && "Expected valid function");
613 if (!BasicBlockFwdRefs.count(F))
614 // Already materialized.
617 // Check for a function that isn't materializable to prevent an infinite
618 // loop. When parsing a blockaddress stored in a global variable, there
619 // isn't a trivial way to check if a function will have a body without a
620 // linear search through FunctionsWithBodies, so just check it here.
621 if (!F->isMaterializable())
622 return error("Never resolved function from blockaddress");
624 // Try to materialize F.
625 if (std::error_code EC = materialize(F))
628 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
631 WillMaterializeAllForwardRefs = false;
632 return std::error_code();
635 void BitcodeReader::freeState() {
637 std::vector<Type*>().swap(TypeList);
639 MetadataList.clear();
640 std::vector<Comdat *>().swap(ComdatList);
642 std::vector<AttributeSet>().swap(MAttributes);
643 std::vector<BasicBlock*>().swap(FunctionBBs);
644 std::vector<Function*>().swap(FunctionsWithBodies);
645 DeferredFunctionInfo.clear();
646 DeferredMetadataInfo.clear();
649 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
650 BasicBlockFwdRefQueue.clear();
653 //===----------------------------------------------------------------------===//
654 // Helper functions to implement forward reference resolution, etc.
655 //===----------------------------------------------------------------------===//
657 /// Convert a string from a record into an std::string, return true on failure.
658 template <typename StrTy>
659 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
661 if (Idx > Record.size())
664 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
665 Result += (char)Record[i];
669 static bool hasImplicitComdat(size_t Val) {
673 case 1: // Old WeakAnyLinkage
674 case 4: // Old LinkOnceAnyLinkage
675 case 10: // Old WeakODRLinkage
676 case 11: // Old LinkOnceODRLinkage
681 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
683 default: // Map unknown/new linkages to external
685 return GlobalValue::ExternalLinkage;
687 return GlobalValue::AppendingLinkage;
689 return GlobalValue::InternalLinkage;
691 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
693 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
695 return GlobalValue::ExternalWeakLinkage;
697 return GlobalValue::CommonLinkage;
699 return GlobalValue::PrivateLinkage;
701 return GlobalValue::AvailableExternallyLinkage;
703 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
705 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
707 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
708 case 1: // Old value with implicit comdat.
710 return GlobalValue::WeakAnyLinkage;
711 case 10: // Old value with implicit comdat.
713 return GlobalValue::WeakODRLinkage;
714 case 4: // Old value with implicit comdat.
716 return GlobalValue::LinkOnceAnyLinkage;
717 case 11: // Old value with implicit comdat.
719 return GlobalValue::LinkOnceODRLinkage;
723 // Decode the flags for GlobalValue in the summary
724 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
726 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
727 // like getDecodedLinkage() above. Any future change to the linkage enum and
728 // to getDecodedLinkage() will need to be taken into account here as above.
729 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
730 RawFlags = RawFlags >> 4;
731 auto HasSection = RawFlags & 0x1; // bool
732 return GlobalValueSummary::GVFlags(Linkage, HasSection);
735 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
737 default: // Map unknown visibilities to default.
738 case 0: return GlobalValue::DefaultVisibility;
739 case 1: return GlobalValue::HiddenVisibility;
740 case 2: return GlobalValue::ProtectedVisibility;
744 static GlobalValue::DLLStorageClassTypes
745 getDecodedDLLStorageClass(unsigned Val) {
747 default: // Map unknown values to default.
748 case 0: return GlobalValue::DefaultStorageClass;
749 case 1: return GlobalValue::DLLImportStorageClass;
750 case 2: return GlobalValue::DLLExportStorageClass;
754 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
756 case 0: return GlobalVariable::NotThreadLocal;
757 default: // Map unknown non-zero value to general dynamic.
758 case 1: return GlobalVariable::GeneralDynamicTLSModel;
759 case 2: return GlobalVariable::LocalDynamicTLSModel;
760 case 3: return GlobalVariable::InitialExecTLSModel;
761 case 4: return GlobalVariable::LocalExecTLSModel;
765 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
767 default: // Map unknown to UnnamedAddr::None.
768 case 0: return GlobalVariable::UnnamedAddr::None;
769 case 1: return GlobalVariable::UnnamedAddr::Global;
770 case 2: return GlobalVariable::UnnamedAddr::Local;
774 static int getDecodedCastOpcode(unsigned Val) {
777 case bitc::CAST_TRUNC : return Instruction::Trunc;
778 case bitc::CAST_ZEXT : return Instruction::ZExt;
779 case bitc::CAST_SEXT : return Instruction::SExt;
780 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
781 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
782 case bitc::CAST_UITOFP : return Instruction::UIToFP;
783 case bitc::CAST_SITOFP : return Instruction::SIToFP;
784 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
785 case bitc::CAST_FPEXT : return Instruction::FPExt;
786 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
787 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
788 case bitc::CAST_BITCAST : return Instruction::BitCast;
789 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
793 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
794 bool IsFP = Ty->isFPOrFPVectorTy();
795 // BinOps are only valid for int/fp or vector of int/fp types
796 if (!IsFP && !Ty->isIntOrIntVectorTy())
802 case bitc::BINOP_ADD:
803 return IsFP ? Instruction::FAdd : Instruction::Add;
804 case bitc::BINOP_SUB:
805 return IsFP ? Instruction::FSub : Instruction::Sub;
806 case bitc::BINOP_MUL:
807 return IsFP ? Instruction::FMul : Instruction::Mul;
808 case bitc::BINOP_UDIV:
809 return IsFP ? -1 : Instruction::UDiv;
810 case bitc::BINOP_SDIV:
811 return IsFP ? Instruction::FDiv : Instruction::SDiv;
812 case bitc::BINOP_UREM:
813 return IsFP ? -1 : Instruction::URem;
814 case bitc::BINOP_SREM:
815 return IsFP ? Instruction::FRem : Instruction::SRem;
816 case bitc::BINOP_SHL:
817 return IsFP ? -1 : Instruction::Shl;
818 case bitc::BINOP_LSHR:
819 return IsFP ? -1 : Instruction::LShr;
820 case bitc::BINOP_ASHR:
821 return IsFP ? -1 : Instruction::AShr;
822 case bitc::BINOP_AND:
823 return IsFP ? -1 : Instruction::And;
825 return IsFP ? -1 : Instruction::Or;
826 case bitc::BINOP_XOR:
827 return IsFP ? -1 : Instruction::Xor;
831 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
833 default: return AtomicRMWInst::BAD_BINOP;
834 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
835 case bitc::RMW_ADD: return AtomicRMWInst::Add;
836 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
837 case bitc::RMW_AND: return AtomicRMWInst::And;
838 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
839 case bitc::RMW_OR: return AtomicRMWInst::Or;
840 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
841 case bitc::RMW_MAX: return AtomicRMWInst::Max;
842 case bitc::RMW_MIN: return AtomicRMWInst::Min;
843 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
844 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
848 static AtomicOrdering getDecodedOrdering(unsigned Val) {
850 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
851 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
852 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
853 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
854 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
855 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
856 default: // Map unknown orderings to sequentially-consistent.
857 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
861 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
863 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
864 default: // Map unknown scopes to cross-thread.
865 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
869 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
871 default: // Map unknown selection kinds to any.
872 case bitc::COMDAT_SELECTION_KIND_ANY:
874 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
875 return Comdat::ExactMatch;
876 case bitc::COMDAT_SELECTION_KIND_LARGEST:
877 return Comdat::Largest;
878 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
879 return Comdat::NoDuplicates;
880 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
881 return Comdat::SameSize;
885 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
887 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
888 FMF.setUnsafeAlgebra();
889 if (0 != (Val & FastMathFlags::NoNaNs))
891 if (0 != (Val & FastMathFlags::NoInfs))
893 if (0 != (Val & FastMathFlags::NoSignedZeros))
894 FMF.setNoSignedZeros();
895 if (0 != (Val & FastMathFlags::AllowReciprocal))
896 FMF.setAllowReciprocal();
900 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
902 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
903 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
909 /// \brief A class for maintaining the slot number definition
910 /// as a placeholder for the actual definition for forward constants defs.
911 class ConstantPlaceHolder : public ConstantExpr {
912 void operator=(const ConstantPlaceHolder &) = delete;
915 // allocate space for exactly one operand
916 void *operator new(size_t s) { return User::operator new(s, 1); }
917 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
918 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
919 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
922 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
923 static bool classof(const Value *V) {
924 return isa<ConstantExpr>(V) &&
925 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
928 /// Provide fast operand accessors
929 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
931 } // end anonymous namespace
933 // FIXME: can we inherit this from ConstantExpr?
935 struct OperandTraits<ConstantPlaceHolder> :
936 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
938 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
939 } // end namespace llvm
941 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
950 WeakVH &OldV = ValuePtrs[Idx];
956 // Handle constants and non-constants (e.g. instrs) differently for
958 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
959 ResolveConstants.push_back(std::make_pair(PHC, Idx));
962 // If there was a forward reference to this value, replace it.
963 Value *PrevVal = OldV;
964 OldV->replaceAllUsesWith(V);
969 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
974 if (Value *V = ValuePtrs[Idx]) {
975 if (Ty != V->getType())
976 report_fatal_error("Type mismatch in constant table!");
977 return cast<Constant>(V);
980 // Create and return a placeholder, which will later be RAUW'd.
981 Constant *C = new ConstantPlaceHolder(Ty, Context);
986 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
987 // Bail out for a clearly invalid value. This would make us call resize(0)
994 if (Value *V = ValuePtrs[Idx]) {
995 // If the types don't match, it's invalid.
996 if (Ty && Ty != V->getType())
1001 // No type specified, must be invalid reference.
1002 if (!Ty) return nullptr;
1004 // Create and return a placeholder, which will later be RAUW'd.
1005 Value *V = new Argument(Ty);
1010 /// Once all constants are read, this method bulk resolves any forward
1011 /// references. The idea behind this is that we sometimes get constants (such
1012 /// as large arrays) which reference *many* forward ref constants. Replacing
1013 /// each of these causes a lot of thrashing when building/reuniquing the
1014 /// constant. Instead of doing this, we look at all the uses and rewrite all
1015 /// the place holders at once for any constant that uses a placeholder.
1016 void BitcodeReaderValueList::resolveConstantForwardRefs() {
1017 // Sort the values by-pointer so that they are efficient to look up with a
1019 std::sort(ResolveConstants.begin(), ResolveConstants.end());
1021 SmallVector<Constant*, 64> NewOps;
1023 while (!ResolveConstants.empty()) {
1024 Value *RealVal = operator[](ResolveConstants.back().second);
1025 Constant *Placeholder = ResolveConstants.back().first;
1026 ResolveConstants.pop_back();
1028 // Loop over all users of the placeholder, updating them to reference the
1029 // new value. If they reference more than one placeholder, update them all
1031 while (!Placeholder->use_empty()) {
1032 auto UI = Placeholder->user_begin();
1035 // If the using object isn't uniqued, just update the operands. This
1036 // handles instructions and initializers for global variables.
1037 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1038 UI.getUse().set(RealVal);
1042 // Otherwise, we have a constant that uses the placeholder. Replace that
1043 // constant with a new constant that has *all* placeholder uses updated.
1044 Constant *UserC = cast<Constant>(U);
1045 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1048 if (!isa<ConstantPlaceHolder>(*I)) {
1049 // Not a placeholder reference.
1051 } else if (*I == Placeholder) {
1052 // Common case is that it just references this one placeholder.
1055 // Otherwise, look up the placeholder in ResolveConstants.
1056 ResolveConstantsTy::iterator It =
1057 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1058 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1060 assert(It != ResolveConstants.end() && It->first == *I);
1061 NewOp = operator[](It->second);
1064 NewOps.push_back(cast<Constant>(NewOp));
1067 // Make the new constant.
1069 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1070 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1071 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1072 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1073 } else if (isa<ConstantVector>(UserC)) {
1074 NewC = ConstantVector::get(NewOps);
1076 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1077 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1080 UserC->replaceAllUsesWith(NewC);
1081 UserC->destroyConstant();
1085 // Update all ValueHandles, they should be the only users at this point.
1086 Placeholder->replaceAllUsesWith(RealVal);
1091 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
1092 if (Idx == size()) {
1100 TrackingMDRef &OldMD = MetadataPtrs[Idx];
1106 // If there was a forward reference to this value, replace it.
1107 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1108 PrevMD->replaceAllUsesWith(MD);
1112 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
1116 if (Metadata *MD = MetadataPtrs[Idx])
1119 // Track forward refs to be resolved later.
1121 MinFwdRef = std::min(MinFwdRef, Idx);
1122 MaxFwdRef = std::max(MaxFwdRef, Idx);
1125 MinFwdRef = MaxFwdRef = Idx;
1129 // Create and return a placeholder, which will later be RAUW'd.
1130 Metadata *MD = MDNode::getTemporary(Context, None).release();
1131 MetadataPtrs[Idx].reset(MD);
1135 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
1136 Metadata *MD = lookup(Idx);
1137 if (auto *N = dyn_cast_or_null<MDNode>(MD))
1138 if (!N->isResolved())
1143 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
1144 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
1147 void BitcodeReaderMetadataList::tryToResolveCycles() {
1149 // Still forward references... can't resolve cycles.
1152 bool DidReplaceTypeRefs = false;
1154 // Give up on finding a full definition for any forward decls that remain.
1155 for (const auto &Ref : OldTypeRefs.FwdDecls)
1156 OldTypeRefs.Final.insert(Ref);
1157 OldTypeRefs.FwdDecls.clear();
1159 // Upgrade from old type ref arrays. In strange cases, this could add to
1160 // OldTypeRefs.Unknown.
1161 for (const auto &Array : OldTypeRefs.Arrays) {
1162 DidReplaceTypeRefs = true;
1163 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
1165 OldTypeRefs.Arrays.clear();
1167 // Replace old string-based type refs with the resolved node, if possible.
1168 // If we haven't seen the node, leave it to the verifier to complain about
1169 // the invalid string reference.
1170 for (const auto &Ref : OldTypeRefs.Unknown) {
1171 DidReplaceTypeRefs = true;
1172 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
1173 Ref.second->replaceAllUsesWith(CT);
1175 Ref.second->replaceAllUsesWith(Ref.first);
1177 OldTypeRefs.Unknown.clear();
1179 // Make sure all the upgraded types are resolved.
1180 if (DidReplaceTypeRefs) {
1183 MaxFwdRef = MetadataPtrs.size() - 1;
1190 // Resolve any cycles.
1191 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1192 auto &MD = MetadataPtrs[I];
1193 auto *N = dyn_cast_or_null<MDNode>(MD);
1197 assert(!N->isTemporary() && "Unexpected forward reference");
1201 // Make sure we return early again until there's another forward ref.
1205 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
1206 DICompositeType &CT) {
1207 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
1208 if (CT.isForwardDecl())
1209 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
1211 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
1214 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
1215 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
1216 if (LLVM_LIKELY(!UUID))
1219 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
1222 auto &Ref = OldTypeRefs.Unknown[UUID];
1224 Ref = MDNode::getTemporary(Context, None);
1228 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
1229 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1230 if (!Tuple || Tuple->isDistinct())
1233 // Look through the array immediately if possible.
1234 if (!Tuple->isTemporary())
1235 return resolveTypeRefArray(Tuple);
1237 // Create and return a placeholder to use for now. Eventually
1238 // resolveTypeRefArrays() will be resolve this forward reference.
1239 OldTypeRefs.Arrays.emplace_back(
1240 std::piecewise_construct, std::forward_as_tuple(Tuple),
1241 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
1242 return OldTypeRefs.Arrays.back().second.get();
1245 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
1246 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1247 if (!Tuple || Tuple->isDistinct())
1250 // Look through the DITypeRefArray, upgrading each DITypeRef.
1251 SmallVector<Metadata *, 32> Ops;
1252 Ops.reserve(Tuple->getNumOperands());
1253 for (Metadata *MD : Tuple->operands())
1254 Ops.push_back(upgradeTypeRef(MD));
1256 return MDTuple::get(Context, Ops);
1259 Type *BitcodeReader::getTypeByID(unsigned ID) {
1260 // The type table size is always specified correctly.
1261 if (ID >= TypeList.size())
1264 if (Type *Ty = TypeList[ID])
1267 // If we have a forward reference, the only possible case is when it is to a
1268 // named struct. Just create a placeholder for now.
1269 return TypeList[ID] = createIdentifiedStructType(Context);
1272 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1274 auto *Ret = StructType::create(Context, Name);
1275 IdentifiedStructTypes.push_back(Ret);
1279 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1280 auto *Ret = StructType::create(Context);
1281 IdentifiedStructTypes.push_back(Ret);
1285 //===----------------------------------------------------------------------===//
1286 // Functions for parsing blocks from the bitcode file
1287 //===----------------------------------------------------------------------===//
1290 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1291 /// been decoded from the given integer. This function must stay in sync with
1292 /// 'encodeLLVMAttributesForBitcode'.
1293 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1294 uint64_t EncodedAttrs) {
1295 // FIXME: Remove in 4.0.
1297 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1298 // the bits above 31 down by 11 bits.
1299 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1300 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1301 "Alignment must be a power of two.");
1304 B.addAlignmentAttr(Alignment);
1305 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1306 (EncodedAttrs & 0xffff));
1309 std::error_code BitcodeReader::parseAttributeBlock() {
1310 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1311 return error("Invalid record");
1313 if (!MAttributes.empty())
1314 return error("Invalid multiple blocks");
1316 SmallVector<uint64_t, 64> Record;
1318 SmallVector<AttributeSet, 8> Attrs;
1320 // Read all the records.
1322 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1324 switch (Entry.Kind) {
1325 case BitstreamEntry::SubBlock: // Handled for us already.
1326 case BitstreamEntry::Error:
1327 return error("Malformed block");
1328 case BitstreamEntry::EndBlock:
1329 return std::error_code();
1330 case BitstreamEntry::Record:
1331 // The interesting case.
1337 switch (Stream.readRecord(Entry.ID, Record)) {
1338 default: // Default behavior: ignore.
1340 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1341 // FIXME: Remove in 4.0.
1342 if (Record.size() & 1)
1343 return error("Invalid record");
1345 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1347 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1348 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1351 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1355 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1356 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1357 Attrs.push_back(MAttributeGroups[Record[i]]);
1359 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1367 // Returns Attribute::None on unrecognized codes.
1368 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1371 return Attribute::None;
1372 case bitc::ATTR_KIND_ALIGNMENT:
1373 return Attribute::Alignment;
1374 case bitc::ATTR_KIND_ALWAYS_INLINE:
1375 return Attribute::AlwaysInline;
1376 case bitc::ATTR_KIND_ARGMEMONLY:
1377 return Attribute::ArgMemOnly;
1378 case bitc::ATTR_KIND_BUILTIN:
1379 return Attribute::Builtin;
1380 case bitc::ATTR_KIND_BY_VAL:
1381 return Attribute::ByVal;
1382 case bitc::ATTR_KIND_IN_ALLOCA:
1383 return Attribute::InAlloca;
1384 case bitc::ATTR_KIND_COLD:
1385 return Attribute::Cold;
1386 case bitc::ATTR_KIND_CONVERGENT:
1387 return Attribute::Convergent;
1388 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1389 return Attribute::InaccessibleMemOnly;
1390 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1391 return Attribute::InaccessibleMemOrArgMemOnly;
1392 case bitc::ATTR_KIND_INLINE_HINT:
1393 return Attribute::InlineHint;
1394 case bitc::ATTR_KIND_IN_REG:
1395 return Attribute::InReg;
1396 case bitc::ATTR_KIND_JUMP_TABLE:
1397 return Attribute::JumpTable;
1398 case bitc::ATTR_KIND_MIN_SIZE:
1399 return Attribute::MinSize;
1400 case bitc::ATTR_KIND_NAKED:
1401 return Attribute::Naked;
1402 case bitc::ATTR_KIND_NEST:
1403 return Attribute::Nest;
1404 case bitc::ATTR_KIND_NO_ALIAS:
1405 return Attribute::NoAlias;
1406 case bitc::ATTR_KIND_NO_BUILTIN:
1407 return Attribute::NoBuiltin;
1408 case bitc::ATTR_KIND_NO_CAPTURE:
1409 return Attribute::NoCapture;
1410 case bitc::ATTR_KIND_NO_DUPLICATE:
1411 return Attribute::NoDuplicate;
1412 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1413 return Attribute::NoImplicitFloat;
1414 case bitc::ATTR_KIND_NO_INLINE:
1415 return Attribute::NoInline;
1416 case bitc::ATTR_KIND_NO_RECURSE:
1417 return Attribute::NoRecurse;
1418 case bitc::ATTR_KIND_NON_LAZY_BIND:
1419 return Attribute::NonLazyBind;
1420 case bitc::ATTR_KIND_NON_NULL:
1421 return Attribute::NonNull;
1422 case bitc::ATTR_KIND_DEREFERENCEABLE:
1423 return Attribute::Dereferenceable;
1424 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1425 return Attribute::DereferenceableOrNull;
1426 case bitc::ATTR_KIND_ALLOC_SIZE:
1427 return Attribute::AllocSize;
1428 case bitc::ATTR_KIND_NO_RED_ZONE:
1429 return Attribute::NoRedZone;
1430 case bitc::ATTR_KIND_NO_RETURN:
1431 return Attribute::NoReturn;
1432 case bitc::ATTR_KIND_NO_UNWIND:
1433 return Attribute::NoUnwind;
1434 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1435 return Attribute::OptimizeForSize;
1436 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1437 return Attribute::OptimizeNone;
1438 case bitc::ATTR_KIND_READ_NONE:
1439 return Attribute::ReadNone;
1440 case bitc::ATTR_KIND_READ_ONLY:
1441 return Attribute::ReadOnly;
1442 case bitc::ATTR_KIND_RETURNED:
1443 return Attribute::Returned;
1444 case bitc::ATTR_KIND_RETURNS_TWICE:
1445 return Attribute::ReturnsTwice;
1446 case bitc::ATTR_KIND_S_EXT:
1447 return Attribute::SExt;
1448 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1449 return Attribute::StackAlignment;
1450 case bitc::ATTR_KIND_STACK_PROTECT:
1451 return Attribute::StackProtect;
1452 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1453 return Attribute::StackProtectReq;
1454 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1455 return Attribute::StackProtectStrong;
1456 case bitc::ATTR_KIND_SAFESTACK:
1457 return Attribute::SafeStack;
1458 case bitc::ATTR_KIND_STRUCT_RET:
1459 return Attribute::StructRet;
1460 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1461 return Attribute::SanitizeAddress;
1462 case bitc::ATTR_KIND_SANITIZE_THREAD:
1463 return Attribute::SanitizeThread;
1464 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1465 return Attribute::SanitizeMemory;
1466 case bitc::ATTR_KIND_SWIFT_ERROR:
1467 return Attribute::SwiftError;
1468 case bitc::ATTR_KIND_SWIFT_SELF:
1469 return Attribute::SwiftSelf;
1470 case bitc::ATTR_KIND_UW_TABLE:
1471 return Attribute::UWTable;
1472 case bitc::ATTR_KIND_WRITEONLY:
1473 return Attribute::WriteOnly;
1474 case bitc::ATTR_KIND_Z_EXT:
1475 return Attribute::ZExt;
1479 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1480 unsigned &Alignment) {
1481 // Note: Alignment in bitcode files is incremented by 1, so that zero
1482 // can be used for default alignment.
1483 if (Exponent > Value::MaxAlignmentExponent + 1)
1484 return error("Invalid alignment value");
1485 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1486 return std::error_code();
1489 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1490 Attribute::AttrKind *Kind) {
1491 *Kind = getAttrFromCode(Code);
1492 if (*Kind == Attribute::None)
1493 return error(BitcodeError::CorruptedBitcode,
1494 "Unknown attribute kind (" + Twine(Code) + ")");
1495 return std::error_code();
1498 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1499 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1500 return error("Invalid record");
1502 if (!MAttributeGroups.empty())
1503 return error("Invalid multiple blocks");
1505 SmallVector<uint64_t, 64> Record;
1507 // Read all the records.
1509 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1511 switch (Entry.Kind) {
1512 case BitstreamEntry::SubBlock: // Handled for us already.
1513 case BitstreamEntry::Error:
1514 return error("Malformed block");
1515 case BitstreamEntry::EndBlock:
1516 return std::error_code();
1517 case BitstreamEntry::Record:
1518 // The interesting case.
1524 switch (Stream.readRecord(Entry.ID, Record)) {
1525 default: // Default behavior: ignore.
1527 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1528 if (Record.size() < 3)
1529 return error("Invalid record");
1531 uint64_t GrpID = Record[0];
1532 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1535 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1536 if (Record[i] == 0) { // Enum attribute
1537 Attribute::AttrKind Kind;
1538 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1541 B.addAttribute(Kind);
1542 } else if (Record[i] == 1) { // Integer attribute
1543 Attribute::AttrKind Kind;
1544 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1546 if (Kind == Attribute::Alignment)
1547 B.addAlignmentAttr(Record[++i]);
1548 else if (Kind == Attribute::StackAlignment)
1549 B.addStackAlignmentAttr(Record[++i]);
1550 else if (Kind == Attribute::Dereferenceable)
1551 B.addDereferenceableAttr(Record[++i]);
1552 else if (Kind == Attribute::DereferenceableOrNull)
1553 B.addDereferenceableOrNullAttr(Record[++i]);
1554 else if (Kind == Attribute::AllocSize)
1555 B.addAllocSizeAttrFromRawRepr(Record[++i]);
1556 } else { // String attribute
1557 assert((Record[i] == 3 || Record[i] == 4) &&
1558 "Invalid attribute group entry");
1559 bool HasValue = (Record[i++] == 4);
1560 SmallString<64> KindStr;
1561 SmallString<64> ValStr;
1563 while (Record[i] != 0 && i != e)
1564 KindStr += Record[i++];
1565 assert(Record[i] == 0 && "Kind string not null terminated");
1568 // Has a value associated with it.
1569 ++i; // Skip the '0' that terminates the "kind" string.
1570 while (Record[i] != 0 && i != e)
1571 ValStr += Record[i++];
1572 assert(Record[i] == 0 && "Value string not null terminated");
1575 B.addAttribute(KindStr.str(), ValStr.str());
1579 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1586 std::error_code BitcodeReader::parseTypeTable() {
1587 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1588 return error("Invalid record");
1590 return parseTypeTableBody();
1593 std::error_code BitcodeReader::parseTypeTableBody() {
1594 if (!TypeList.empty())
1595 return error("Invalid multiple blocks");
1597 SmallVector<uint64_t, 64> Record;
1598 unsigned NumRecords = 0;
1600 SmallString<64> TypeName;
1602 // Read all the records for this type table.
1604 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1606 switch (Entry.Kind) {
1607 case BitstreamEntry::SubBlock: // Handled for us already.
1608 case BitstreamEntry::Error:
1609 return error("Malformed block");
1610 case BitstreamEntry::EndBlock:
1611 if (NumRecords != TypeList.size())
1612 return error("Malformed block");
1613 return std::error_code();
1614 case BitstreamEntry::Record:
1615 // The interesting case.
1621 Type *ResultTy = nullptr;
1622 switch (Stream.readRecord(Entry.ID, Record)) {
1624 return error("Invalid value");
1625 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1626 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1627 // type list. This allows us to reserve space.
1628 if (Record.size() < 1)
1629 return error("Invalid record");
1630 TypeList.resize(Record[0]);
1632 case bitc::TYPE_CODE_VOID: // VOID
1633 ResultTy = Type::getVoidTy(Context);
1635 case bitc::TYPE_CODE_HALF: // HALF
1636 ResultTy = Type::getHalfTy(Context);
1638 case bitc::TYPE_CODE_FLOAT: // FLOAT
1639 ResultTy = Type::getFloatTy(Context);
1641 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1642 ResultTy = Type::getDoubleTy(Context);
1644 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1645 ResultTy = Type::getX86_FP80Ty(Context);
1647 case bitc::TYPE_CODE_FP128: // FP128
1648 ResultTy = Type::getFP128Ty(Context);
1650 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1651 ResultTy = Type::getPPC_FP128Ty(Context);
1653 case bitc::TYPE_CODE_LABEL: // LABEL
1654 ResultTy = Type::getLabelTy(Context);
1656 case bitc::TYPE_CODE_METADATA: // METADATA
1657 ResultTy = Type::getMetadataTy(Context);
1659 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1660 ResultTy = Type::getX86_MMXTy(Context);
1662 case bitc::TYPE_CODE_TOKEN: // TOKEN
1663 ResultTy = Type::getTokenTy(Context);
1665 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1666 if (Record.size() < 1)
1667 return error("Invalid record");
1669 uint64_t NumBits = Record[0];
1670 if (NumBits < IntegerType::MIN_INT_BITS ||
1671 NumBits > IntegerType::MAX_INT_BITS)
1672 return error("Bitwidth for integer type out of range");
1673 ResultTy = IntegerType::get(Context, NumBits);
1676 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1677 // [pointee type, address space]
1678 if (Record.size() < 1)
1679 return error("Invalid record");
1680 unsigned AddressSpace = 0;
1681 if (Record.size() == 2)
1682 AddressSpace = Record[1];
1683 ResultTy = getTypeByID(Record[0]);
1685 !PointerType::isValidElementType(ResultTy))
1686 return error("Invalid type");
1687 ResultTy = PointerType::get(ResultTy, AddressSpace);
1690 case bitc::TYPE_CODE_FUNCTION_OLD: {
1691 // FIXME: attrid is dead, remove it in LLVM 4.0
1692 // FUNCTION: [vararg, attrid, retty, paramty x N]
1693 if (Record.size() < 3)
1694 return error("Invalid record");
1695 SmallVector<Type*, 8> ArgTys;
1696 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1697 if (Type *T = getTypeByID(Record[i]))
1698 ArgTys.push_back(T);
1703 ResultTy = getTypeByID(Record[2]);
1704 if (!ResultTy || ArgTys.size() < Record.size()-3)
1705 return error("Invalid type");
1707 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1710 case bitc::TYPE_CODE_FUNCTION: {
1711 // FUNCTION: [vararg, retty, paramty x N]
1712 if (Record.size() < 2)
1713 return error("Invalid record");
1714 SmallVector<Type*, 8> ArgTys;
1715 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1716 if (Type *T = getTypeByID(Record[i])) {
1717 if (!FunctionType::isValidArgumentType(T))
1718 return error("Invalid function argument type");
1719 ArgTys.push_back(T);
1725 ResultTy = getTypeByID(Record[1]);
1726 if (!ResultTy || ArgTys.size() < Record.size()-2)
1727 return error("Invalid type");
1729 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1732 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1733 if (Record.size() < 1)
1734 return error("Invalid record");
1735 SmallVector<Type*, 8> EltTys;
1736 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1737 if (Type *T = getTypeByID(Record[i]))
1738 EltTys.push_back(T);
1742 if (EltTys.size() != Record.size()-1)
1743 return error("Invalid type");
1744 ResultTy = StructType::get(Context, EltTys, Record[0]);
1747 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1748 if (convertToString(Record, 0, TypeName))
1749 return error("Invalid record");
1752 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1753 if (Record.size() < 1)
1754 return error("Invalid record");
1756 if (NumRecords >= TypeList.size())
1757 return error("Invalid TYPE table");
1759 // Check to see if this was forward referenced, if so fill in the temp.
1760 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1762 Res->setName(TypeName);
1763 TypeList[NumRecords] = nullptr;
1764 } else // Otherwise, create a new struct.
1765 Res = createIdentifiedStructType(Context, TypeName);
1768 SmallVector<Type*, 8> EltTys;
1769 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1770 if (Type *T = getTypeByID(Record[i]))
1771 EltTys.push_back(T);
1775 if (EltTys.size() != Record.size()-1)
1776 return error("Invalid record");
1777 Res->setBody(EltTys, Record[0]);
1781 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1782 if (Record.size() != 1)
1783 return error("Invalid record");
1785 if (NumRecords >= TypeList.size())
1786 return error("Invalid TYPE table");
1788 // Check to see if this was forward referenced, if so fill in the temp.
1789 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1791 Res->setName(TypeName);
1792 TypeList[NumRecords] = nullptr;
1793 } else // Otherwise, create a new struct with no body.
1794 Res = createIdentifiedStructType(Context, TypeName);
1799 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1800 if (Record.size() < 2)
1801 return error("Invalid record");
1802 ResultTy = getTypeByID(Record[1]);
1803 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1804 return error("Invalid type");
1805 ResultTy = ArrayType::get(ResultTy, Record[0]);
1807 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1808 if (Record.size() < 2)
1809 return error("Invalid record");
1811 return error("Invalid vector length");
1812 ResultTy = getTypeByID(Record[1]);
1813 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1814 return error("Invalid type");
1815 ResultTy = VectorType::get(ResultTy, Record[0]);
1819 if (NumRecords >= TypeList.size())
1820 return error("Invalid TYPE table");
1821 if (TypeList[NumRecords])
1823 "Invalid TYPE table: Only named structs can be forward referenced");
1824 assert(ResultTy && "Didn't read a type?");
1825 TypeList[NumRecords++] = ResultTy;
1829 std::error_code BitcodeReader::parseOperandBundleTags() {
1830 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1831 return error("Invalid record");
1833 if (!BundleTags.empty())
1834 return error("Invalid multiple blocks");
1836 SmallVector<uint64_t, 64> Record;
1839 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1841 switch (Entry.Kind) {
1842 case BitstreamEntry::SubBlock: // Handled for us already.
1843 case BitstreamEntry::Error:
1844 return error("Malformed block");
1845 case BitstreamEntry::EndBlock:
1846 return std::error_code();
1847 case BitstreamEntry::Record:
1848 // The interesting case.
1852 // Tags are implicitly mapped to integers by their order.
1854 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1855 return error("Invalid record");
1857 // OPERAND_BUNDLE_TAG: [strchr x N]
1858 BundleTags.emplace_back();
1859 if (convertToString(Record, 0, BundleTags.back()))
1860 return error("Invalid record");
1865 /// Associate a value with its name from the given index in the provided record.
1866 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1867 unsigned NameIndex, Triple &TT) {
1868 SmallString<128> ValueName;
1869 if (convertToString(Record, NameIndex, ValueName))
1870 return error("Invalid record");
1871 unsigned ValueID = Record[0];
1872 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1873 return error("Invalid record");
1874 Value *V = ValueList[ValueID];
1876 StringRef NameStr(ValueName.data(), ValueName.size());
1877 if (NameStr.find_first_of(0) != StringRef::npos)
1878 return error("Invalid value name");
1879 V->setName(NameStr);
1880 auto *GO = dyn_cast<GlobalObject>(V);
1882 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1883 if (TT.isOSBinFormatMachO())
1884 GO->setComdat(nullptr);
1886 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1892 /// Helper to note and return the current location, and jump to the given
1894 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1895 BitstreamCursor &Stream) {
1896 // Save the current parsing location so we can jump back at the end
1898 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1899 Stream.JumpToBit(Offset * 32);
1901 // Do some checking if we are in debug mode.
1902 BitstreamEntry Entry = Stream.advance();
1903 assert(Entry.Kind == BitstreamEntry::SubBlock);
1904 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1906 // In NDEBUG mode ignore the output so we don't get an unused variable
1913 /// Parse the value symbol table at either the current parsing location or
1914 /// at the given bit offset if provided.
1915 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1916 uint64_t CurrentBit;
1917 // Pass in the Offset to distinguish between calling for the module-level
1918 // VST (where we want to jump to the VST offset) and the function-level
1919 // VST (where we don't).
1921 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
1923 // Compute the delta between the bitcode indices in the VST (the word offset
1924 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1925 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1926 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1927 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1928 // just before entering the VST subblock because: 1) the EnterSubBlock
1929 // changes the AbbrevID width; 2) the VST block is nested within the same
1930 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1931 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1932 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1933 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1934 unsigned FuncBitcodeOffsetDelta =
1935 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1937 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1938 return error("Invalid record");
1940 SmallVector<uint64_t, 64> Record;
1942 Triple TT(TheModule->getTargetTriple());
1944 // Read all the records for this value table.
1945 SmallString<128> ValueName;
1947 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1949 switch (Entry.Kind) {
1950 case BitstreamEntry::SubBlock: // Handled for us already.
1951 case BitstreamEntry::Error:
1952 return error("Malformed block");
1953 case BitstreamEntry::EndBlock:
1955 Stream.JumpToBit(CurrentBit);
1956 return std::error_code();
1957 case BitstreamEntry::Record:
1958 // The interesting case.
1964 switch (Stream.readRecord(Entry.ID, Record)) {
1965 default: // Default behavior: unknown type.
1967 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
1968 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1969 if (std::error_code EC = ValOrErr.getError())
1974 case bitc::VST_CODE_FNENTRY: {
1975 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
1976 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1977 if (std::error_code EC = ValOrErr.getError())
1979 Value *V = ValOrErr.get();
1981 auto *GO = dyn_cast<GlobalObject>(V);
1983 // If this is an alias, need to get the actual Function object
1984 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1985 auto *GA = dyn_cast<GlobalAlias>(V);
1987 GO = GA->getBaseObject();
1991 uint64_t FuncWordOffset = Record[1];
1992 Function *F = dyn_cast<Function>(GO);
1994 uint64_t FuncBitOffset = FuncWordOffset * 32;
1995 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1996 // Set the LastFunctionBlockBit to point to the last function block.
1997 // Later when parsing is resumed after function materialization,
1998 // we can simply skip that last function block.
1999 if (FuncBitOffset > LastFunctionBlockBit)
2000 LastFunctionBlockBit = FuncBitOffset;
2003 case bitc::VST_CODE_BBENTRY: {
2004 if (convertToString(Record, 1, ValueName))
2005 return error("Invalid record");
2006 BasicBlock *BB = getBasicBlock(Record[0]);
2008 return error("Invalid record");
2010 BB->setName(StringRef(ValueName.data(), ValueName.size()));
2018 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2020 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
2021 if (Record.size() < 2)
2022 return error("Invalid record");
2024 unsigned Kind = Record[0];
2025 SmallString<8> Name(Record.begin() + 1, Record.end());
2027 unsigned NewKind = TheModule->getMDKindID(Name.str());
2028 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2029 return error("Conflicting METADATA_KIND records");
2030 return std::error_code();
2033 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
2035 std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
2037 unsigned &NextMetadataNo) {
2038 // All the MDStrings in the block are emitted together in a single
2039 // record. The strings are concatenated and stored in a blob along with
2041 if (Record.size() != 2)
2042 return error("Invalid record: metadata strings layout");
2044 unsigned NumStrings = Record[0];
2045 unsigned StringsOffset = Record[1];
2047 return error("Invalid record: metadata strings with no strings");
2048 if (StringsOffset > Blob.size())
2049 return error("Invalid record: metadata strings corrupt offset");
2051 StringRef Lengths = Blob.slice(0, StringsOffset);
2052 SimpleBitstreamCursor R(*StreamFile);
2053 R.jumpToPointer(Lengths.begin());
2055 // Ensure that Blob doesn't get invalidated, even if this is reading from
2056 // a StreamingMemoryObject with corrupt data.
2057 R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
2059 StringRef Strings = Blob.drop_front(StringsOffset);
2061 if (R.AtEndOfStream())
2062 return error("Invalid record: metadata strings bad length");
2064 unsigned Size = R.ReadVBR(6);
2065 if (Strings.size() < Size)
2066 return error("Invalid record: metadata strings truncated chars");
2068 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
2070 Strings = Strings.drop_front(Size);
2071 } while (--NumStrings);
2073 return std::error_code();
2077 class PlaceholderQueue {
2078 // Placeholders would thrash around when moved, so store in a std::deque
2079 // instead of some sort of vector.
2080 std::deque<DistinctMDOperandPlaceholder> PHs;
2083 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
2084 void flush(BitcodeReaderMetadataList &MetadataList);
2088 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
2089 PHs.emplace_back(ID);
2093 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
2094 while (!PHs.empty()) {
2095 PHs.front().replaceUseWith(
2096 MetadataList.getMetadataFwdRef(PHs.front().getID()));
2101 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
2102 /// module level metadata.
2103 std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
2104 assert((ModuleLevel || DeferredMetadataInfo.empty()) &&
2105 "Must read all module-level metadata before function-level");
2107 IsMetadataMaterialized = true;
2108 unsigned NextMetadataNo = MetadataList.size();
2110 if (!ModuleLevel && MetadataList.hasFwdRefs())
2111 return error("Invalid metadata: fwd refs into function blocks");
2113 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
2114 return error("Invalid record");
2116 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
2117 SmallVector<uint64_t, 64> Record;
2119 PlaceholderQueue Placeholders;
2121 auto getMD = [&](unsigned ID) -> Metadata * {
2123 return MetadataList.getMetadataFwdRef(ID);
2124 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
2126 return &Placeholders.getPlaceholderOp(ID);
2128 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
2130 return getMD(ID - 1);
2133 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
2135 return MetadataList.getMetadataFwdRef(ID - 1);
2138 auto getMDString = [&](unsigned ID) -> MDString *{
2139 // This requires that the ID is not really a forward reference. In
2140 // particular, the MDString must already have been resolved.
2141 return cast_or_null<MDString>(getMDOrNull(ID));
2144 // Support for old type refs.
2145 auto getDITypeRefOrNull = [&](unsigned ID) {
2146 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
2149 #define GET_OR_DISTINCT(CLASS, ARGS) \
2150 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
2152 // Read all the records.
2154 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2156 switch (Entry.Kind) {
2157 case BitstreamEntry::SubBlock: // Handled for us already.
2158 case BitstreamEntry::Error:
2159 return error("Malformed block");
2160 case BitstreamEntry::EndBlock:
2161 // Upgrade old-style CU <-> SP pointers to point from SP to CU.
2162 for (auto CU_SP : CUSubprograms)
2163 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
2164 for (auto &Op : SPs->operands())
2165 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
2166 SP->replaceOperandWith(7, CU_SP.first);
2168 MetadataList.tryToResolveCycles();
2169 Placeholders.flush(MetadataList);
2170 return std::error_code();
2171 case BitstreamEntry::Record:
2172 // The interesting case.
2179 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
2182 default: // Default behavior: ignore.
2184 case bitc::METADATA_NAME: {
2185 // Read name of the named metadata.
2186 SmallString<8> Name(Record.begin(), Record.end());
2188 Code = Stream.ReadCode();
2190 unsigned NextBitCode = Stream.readRecord(Code, Record);
2191 if (NextBitCode != bitc::METADATA_NAMED_NODE)
2192 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
2194 // Read named metadata elements.
2195 unsigned Size = Record.size();
2196 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
2197 for (unsigned i = 0; i != Size; ++i) {
2198 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
2200 return error("Invalid record");
2201 NMD->addOperand(MD);
2205 case bitc::METADATA_OLD_FN_NODE: {
2206 // FIXME: Remove in 4.0.
2207 // This is a LocalAsMetadata record, the only type of function-local
2209 if (Record.size() % 2 == 1)
2210 return error("Invalid record");
2212 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2213 // to be legal, but there's no upgrade path.
2214 auto dropRecord = [&] {
2215 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
2217 if (Record.size() != 2) {
2222 Type *Ty = getTypeByID(Record[0]);
2223 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2228 MetadataList.assignValue(
2229 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2233 case bitc::METADATA_OLD_NODE: {
2234 // FIXME: Remove in 4.0.
2235 if (Record.size() % 2 == 1)
2236 return error("Invalid record");
2238 unsigned Size = Record.size();
2239 SmallVector<Metadata *, 8> Elts;
2240 for (unsigned i = 0; i != Size; i += 2) {
2241 Type *Ty = getTypeByID(Record[i]);
2243 return error("Invalid record");
2244 if (Ty->isMetadataTy())
2245 Elts.push_back(getMD(Record[i + 1]));
2246 else if (!Ty->isVoidTy()) {
2248 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2249 assert(isa<ConstantAsMetadata>(MD) &&
2250 "Expected non-function-local metadata");
2253 Elts.push_back(nullptr);
2255 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
2258 case bitc::METADATA_VALUE: {
2259 if (Record.size() != 2)
2260 return error("Invalid record");
2262 Type *Ty = getTypeByID(Record[0]);
2263 if (Ty->isMetadataTy() || Ty->isVoidTy())
2264 return error("Invalid record");
2266 MetadataList.assignValue(
2267 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2271 case bitc::METADATA_DISTINCT_NODE:
2274 case bitc::METADATA_NODE: {
2275 SmallVector<Metadata *, 8> Elts;
2276 Elts.reserve(Record.size());
2277 for (unsigned ID : Record)
2278 Elts.push_back(getMDOrNull(ID));
2279 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2280 : MDNode::get(Context, Elts),
2284 case bitc::METADATA_LOCATION: {
2285 if (Record.size() != 5)
2286 return error("Invalid record");
2288 IsDistinct = Record[0];
2289 unsigned Line = Record[1];
2290 unsigned Column = Record[2];
2291 Metadata *Scope = getMD(Record[3]);
2292 Metadata *InlinedAt = getMDOrNull(Record[4]);
2293 MetadataList.assignValue(
2294 GET_OR_DISTINCT(DILocation,
2295 (Context, Line, Column, Scope, InlinedAt)),
2299 case bitc::METADATA_GENERIC_DEBUG: {
2300 if (Record.size() < 4)
2301 return error("Invalid record");
2303 IsDistinct = Record[0];
2304 unsigned Tag = Record[1];
2305 unsigned Version = Record[2];
2307 if (Tag >= 1u << 16 || Version != 0)
2308 return error("Invalid record");
2310 auto *Header = getMDString(Record[3]);
2311 SmallVector<Metadata *, 8> DwarfOps;
2312 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2313 DwarfOps.push_back(getMDOrNull(Record[I]));
2314 MetadataList.assignValue(
2315 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
2319 case bitc::METADATA_SUBRANGE: {
2320 if (Record.size() != 3)
2321 return error("Invalid record");
2323 IsDistinct = Record[0];
2324 MetadataList.assignValue(
2325 GET_OR_DISTINCT(DISubrange,
2326 (Context, Record[1], unrotateSign(Record[2]))),
2330 case bitc::METADATA_ENUMERATOR: {
2331 if (Record.size() != 3)
2332 return error("Invalid record");
2334 IsDistinct = Record[0];
2335 MetadataList.assignValue(
2336 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
2337 getMDString(Record[2]))),
2341 case bitc::METADATA_BASIC_TYPE: {
2342 if (Record.size() != 6)
2343 return error("Invalid record");
2345 IsDistinct = Record[0];
2346 MetadataList.assignValue(
2347 GET_OR_DISTINCT(DIBasicType,
2348 (Context, Record[1], getMDString(Record[2]),
2349 Record[3], Record[4], Record[5])),
2353 case bitc::METADATA_DERIVED_TYPE: {
2354 if (Record.size() != 12)
2355 return error("Invalid record");
2357 IsDistinct = Record[0];
2358 MetadataList.assignValue(
2361 (Context, Record[1], getMDString(Record[2]),
2362 getMDOrNull(Record[3]), Record[4], getDITypeRefOrNull(Record[5]),
2363 getDITypeRefOrNull(Record[6]), Record[7], Record[8], Record[9],
2364 Record[10], getDITypeRefOrNull(Record[11]))),
2368 case bitc::METADATA_COMPOSITE_TYPE: {
2369 if (Record.size() != 16)
2370 return error("Invalid record");
2372 // If we have a UUID and this is not a forward declaration, lookup the
2374 IsDistinct = Record[0] & 0x1;
2375 bool IsNotUsedInTypeRef = Record[0] >= 2;
2376 unsigned Tag = Record[1];
2377 MDString *Name = getMDString(Record[2]);
2378 Metadata *File = getMDOrNull(Record[3]);
2379 unsigned Line = Record[4];
2380 Metadata *Scope = getDITypeRefOrNull(Record[5]);
2381 Metadata *BaseType = getDITypeRefOrNull(Record[6]);
2382 uint64_t SizeInBits = Record[7];
2383 uint64_t AlignInBits = Record[8];
2384 uint64_t OffsetInBits = Record[9];
2385 unsigned Flags = Record[10];
2386 Metadata *Elements = getMDOrNull(Record[11]);
2387 unsigned RuntimeLang = Record[12];
2388 Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
2389 Metadata *TemplateParams = getMDOrNull(Record[14]);
2390 auto *Identifier = getMDString(Record[15]);
2391 DICompositeType *CT = nullptr;
2393 CT = DICompositeType::buildODRType(
2394 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
2395 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
2396 VTableHolder, TemplateParams);
2398 // Create a node if we didn't get a lazy ODR type.
2400 CT = GET_OR_DISTINCT(DICompositeType,
2401 (Context, Tag, Name, File, Line, Scope, BaseType,
2402 SizeInBits, AlignInBits, OffsetInBits, Flags,
2403 Elements, RuntimeLang, VTableHolder,
2404 TemplateParams, Identifier));
2405 if (!IsNotUsedInTypeRef && Identifier)
2406 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
2408 MetadataList.assignValue(CT, NextMetadataNo++);
2411 case bitc::METADATA_SUBROUTINE_TYPE: {
2412 if (Record.size() < 3 || Record.size() > 4)
2413 return error("Invalid record");
2414 bool IsOldTypeRefArray = Record[0] < 2;
2415 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
2417 IsDistinct = Record[0] & 0x1;
2418 Metadata *Types = getMDOrNull(Record[2]);
2419 if (LLVM_UNLIKELY(IsOldTypeRefArray))
2420 Types = MetadataList.upgradeTypeRefArray(Types);
2422 MetadataList.assignValue(
2423 GET_OR_DISTINCT(DISubroutineType, (Context, Record[1], CC, Types)),
2428 case bitc::METADATA_MODULE: {
2429 if (Record.size() != 6)
2430 return error("Invalid record");
2432 IsDistinct = Record[0];
2433 MetadataList.assignValue(
2434 GET_OR_DISTINCT(DIModule,
2435 (Context, getMDOrNull(Record[1]),
2436 getMDString(Record[2]), getMDString(Record[3]),
2437 getMDString(Record[4]), getMDString(Record[5]))),
2442 case bitc::METADATA_FILE: {
2443 if (Record.size() != 3)
2444 return error("Invalid record");
2446 IsDistinct = Record[0];
2447 MetadataList.assignValue(
2448 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
2449 getMDString(Record[2]))),
2453 case bitc::METADATA_COMPILE_UNIT: {
2454 if (Record.size() < 14 || Record.size() > 16)
2455 return error("Invalid record");
2457 // Ignore Record[0], which indicates whether this compile unit is
2458 // distinct. It's always distinct.
2460 auto *CU = DICompileUnit::getDistinct(
2461 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
2462 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
2463 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2464 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2465 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2466 Record.size() <= 14 ? 0 : Record[14]);
2468 MetadataList.assignValue(CU, NextMetadataNo++);
2470 // Move the Upgrade the list of subprograms.
2471 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
2472 CUSubprograms.push_back({CU, SPs});
2475 case bitc::METADATA_SUBPROGRAM: {
2476 if (Record.size() < 18 || Record.size() > 20)
2477 return error("Invalid record");
2480 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
2481 // Version 1 has a Function as Record[15].
2482 // Version 2 has removed Record[15].
2483 // Version 3 has the Unit as Record[15].
2484 // Version 4 added thisAdjustment.
2485 bool HasUnit = Record[0] >= 2;
2486 if (HasUnit && Record.size() < 19)
2487 return error("Invalid record");
2488 Metadata *CUorFn = getMDOrNull(Record[15]);
2489 unsigned Offset = Record.size() >= 19 ? 1 : 0;
2490 bool HasFn = Offset && !HasUnit;
2491 bool HasThisAdj = Record.size() >= 20;
2492 DISubprogram *SP = GET_OR_DISTINCT(
2493 DISubprogram, (Context,
2494 getDITypeRefOrNull(Record[1]), // scope
2495 getMDString(Record[2]), // name
2496 getMDString(Record[3]), // linkageName
2497 getMDOrNull(Record[4]), // file
2499 getMDOrNull(Record[6]), // type
2500 Record[7], // isLocal
2501 Record[8], // isDefinition
2502 Record[9], // scopeLine
2503 getDITypeRefOrNull(Record[10]), // containingType
2504 Record[11], // virtuality
2505 Record[12], // virtualIndex
2506 HasThisAdj ? Record[19] : 0, // thisAdjustment
2507 Record[13], // flags
2508 Record[14], // isOptimized
2509 HasUnit ? CUorFn : nullptr, // unit
2510 getMDOrNull(Record[15 + Offset]), // templateParams
2511 getMDOrNull(Record[16 + Offset]), // declaration
2512 getMDOrNull(Record[17 + Offset]) // variables
2514 MetadataList.assignValue(SP, NextMetadataNo++);
2516 // Upgrade sp->function mapping to function->sp mapping.
2518 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
2519 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2520 if (F->isMaterializable())
2521 // Defer until materialized; unmaterialized functions may not have
2523 FunctionsWithSPs[F] = SP;
2524 else if (!F->empty())
2525 F->setSubprogram(SP);
2530 case bitc::METADATA_LEXICAL_BLOCK: {
2531 if (Record.size() != 5)
2532 return error("Invalid record");
2534 IsDistinct = Record[0];
2535 MetadataList.assignValue(
2536 GET_OR_DISTINCT(DILexicalBlock,
2537 (Context, getMDOrNull(Record[1]),
2538 getMDOrNull(Record[2]), Record[3], Record[4])),
2542 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2543 if (Record.size() != 4)
2544 return error("Invalid record");
2546 IsDistinct = Record[0];
2547 MetadataList.assignValue(
2548 GET_OR_DISTINCT(DILexicalBlockFile,
2549 (Context, getMDOrNull(Record[1]),
2550 getMDOrNull(Record[2]), Record[3])),
2554 case bitc::METADATA_NAMESPACE: {
2555 if (Record.size() != 5)
2556 return error("Invalid record");
2558 IsDistinct = Record[0];
2559 MetadataList.assignValue(
2560 GET_OR_DISTINCT(DINamespace, (Context, getMDOrNull(Record[1]),
2561 getMDOrNull(Record[2]),
2562 getMDString(Record[3]), Record[4])),
2566 case bitc::METADATA_MACRO: {
2567 if (Record.size() != 5)
2568 return error("Invalid record");
2570 IsDistinct = Record[0];
2571 MetadataList.assignValue(
2572 GET_OR_DISTINCT(DIMacro,
2573 (Context, Record[1], Record[2],
2574 getMDString(Record[3]), getMDString(Record[4]))),
2578 case bitc::METADATA_MACRO_FILE: {
2579 if (Record.size() != 5)
2580 return error("Invalid record");
2582 IsDistinct = Record[0];
2583 MetadataList.assignValue(
2584 GET_OR_DISTINCT(DIMacroFile,
2585 (Context, Record[1], Record[2],
2586 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2590 case bitc::METADATA_TEMPLATE_TYPE: {
2591 if (Record.size() != 3)
2592 return error("Invalid record");
2594 IsDistinct = Record[0];
2595 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2596 (Context, getMDString(Record[1]),
2597 getDITypeRefOrNull(Record[2]))),
2601 case bitc::METADATA_TEMPLATE_VALUE: {
2602 if (Record.size() != 5)
2603 return error("Invalid record");
2605 IsDistinct = Record[0];
2606 MetadataList.assignValue(
2607 GET_OR_DISTINCT(DITemplateValueParameter,
2608 (Context, Record[1], getMDString(Record[2]),
2609 getDITypeRefOrNull(Record[3]),
2610 getMDOrNull(Record[4]))),
2614 case bitc::METADATA_GLOBAL_VAR: {
2615 if (Record.size() != 11)
2616 return error("Invalid record");
2618 IsDistinct = Record[0];
2619 MetadataList.assignValue(
2620 GET_OR_DISTINCT(DIGlobalVariable,
2621 (Context, getMDOrNull(Record[1]),
2622 getMDString(Record[2]), getMDString(Record[3]),
2623 getMDOrNull(Record[4]), Record[5],
2624 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2625 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2629 case bitc::METADATA_LOCAL_VAR: {
2630 // 10th field is for the obseleted 'inlinedAt:' field.
2631 if (Record.size() < 8 || Record.size() > 10)
2632 return error("Invalid record");
2634 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2635 // DW_TAG_arg_variable.
2636 IsDistinct = Record[0];
2637 bool HasTag = Record.size() > 8;
2638 MetadataList.assignValue(
2639 GET_OR_DISTINCT(DILocalVariable,
2640 (Context, getMDOrNull(Record[1 + HasTag]),
2641 getMDString(Record[2 + HasTag]),
2642 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2643 getDITypeRefOrNull(Record[5 + HasTag]),
2644 Record[6 + HasTag], Record[7 + HasTag])),
2648 case bitc::METADATA_EXPRESSION: {
2649 if (Record.size() < 1)
2650 return error("Invalid record");
2652 IsDistinct = Record[0];
2653 MetadataList.assignValue(
2654 GET_OR_DISTINCT(DIExpression,
2655 (Context, makeArrayRef(Record).slice(1))),
2659 case bitc::METADATA_OBJC_PROPERTY: {
2660 if (Record.size() != 8)
2661 return error("Invalid record");
2663 IsDistinct = Record[0];
2664 MetadataList.assignValue(
2665 GET_OR_DISTINCT(DIObjCProperty,
2666 (Context, getMDString(Record[1]),
2667 getMDOrNull(Record[2]), Record[3],
2668 getMDString(Record[4]), getMDString(Record[5]),
2669 Record[6], getDITypeRefOrNull(Record[7]))),
2673 case bitc::METADATA_IMPORTED_ENTITY: {
2674 if (Record.size() != 6)
2675 return error("Invalid record");
2677 IsDistinct = Record[0];
2678 MetadataList.assignValue(
2679 GET_OR_DISTINCT(DIImportedEntity,
2680 (Context, Record[1], getMDOrNull(Record[2]),
2681 getDITypeRefOrNull(Record[3]), Record[4],
2682 getMDString(Record[5]))),
2686 case bitc::METADATA_STRING_OLD: {
2687 std::string String(Record.begin(), Record.end());
2689 // Test for upgrading !llvm.loop.
2690 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2692 Metadata *MD = MDString::get(Context, String);
2693 MetadataList.assignValue(MD, NextMetadataNo++);
2696 case bitc::METADATA_STRINGS:
2697 if (std::error_code EC =
2698 parseMetadataStrings(Record, Blob, NextMetadataNo))
2701 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2702 if (Record.size() % 2 == 0)
2703 return error("Invalid record");
2704 unsigned ValueID = Record[0];
2705 if (ValueID >= ValueList.size())
2706 return error("Invalid record");
2707 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2708 parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1));
2711 case bitc::METADATA_KIND: {
2712 // Support older bitcode files that had METADATA_KIND records in a
2713 // block with METADATA_BLOCK_ID.
2714 if (std::error_code EC = parseMetadataKindRecord(Record))
2720 #undef GET_OR_DISTINCT
2723 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2724 std::error_code BitcodeReader::parseMetadataKinds() {
2725 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2726 return error("Invalid record");
2728 SmallVector<uint64_t, 64> Record;
2730 // Read all the records.
2732 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2734 switch (Entry.Kind) {
2735 case BitstreamEntry::SubBlock: // Handled for us already.
2736 case BitstreamEntry::Error:
2737 return error("Malformed block");
2738 case BitstreamEntry::EndBlock:
2739 return std::error_code();
2740 case BitstreamEntry::Record:
2741 // The interesting case.
2747 unsigned Code = Stream.readRecord(Entry.ID, Record);
2749 default: // Default behavior: ignore.
2751 case bitc::METADATA_KIND: {
2752 if (std::error_code EC = parseMetadataKindRecord(Record))
2760 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2762 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2767 // There is no such thing as -0 with integers. "-0" really means MININT.
2771 /// Resolve all of the initializers for global values and aliases that we can.
2772 std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2773 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2774 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2775 IndirectSymbolInitWorklist;
2776 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2777 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2778 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2780 GlobalInitWorklist.swap(GlobalInits);
2781 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2782 FunctionPrefixWorklist.swap(FunctionPrefixes);
2783 FunctionPrologueWorklist.swap(FunctionPrologues);
2784 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2786 while (!GlobalInitWorklist.empty()) {
2787 unsigned ValID = GlobalInitWorklist.back().second;
2788 if (ValID >= ValueList.size()) {
2789 // Not ready to resolve this yet, it requires something later in the file.
2790 GlobalInits.push_back(GlobalInitWorklist.back());
2792 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2793 GlobalInitWorklist.back().first->setInitializer(C);
2795 return error("Expected a constant");
2797 GlobalInitWorklist.pop_back();
2800 while (!IndirectSymbolInitWorklist.empty()) {
2801 unsigned ValID = IndirectSymbolInitWorklist.back().second;
2802 if (ValID >= ValueList.size()) {
2803 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2805 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2807 return error("Expected a constant");
2808 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2809 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2810 return error("Alias and aliasee types don't match");
2811 GIS->setIndirectSymbol(C);
2813 IndirectSymbolInitWorklist.pop_back();
2816 while (!FunctionPrefixWorklist.empty()) {
2817 unsigned ValID = FunctionPrefixWorklist.back().second;
2818 if (ValID >= ValueList.size()) {
2819 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2821 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2822 FunctionPrefixWorklist.back().first->setPrefixData(C);
2824 return error("Expected a constant");
2826 FunctionPrefixWorklist.pop_back();
2829 while (!FunctionPrologueWorklist.empty()) {
2830 unsigned ValID = FunctionPrologueWorklist.back().second;
2831 if (ValID >= ValueList.size()) {
2832 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2834 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2835 FunctionPrologueWorklist.back().first->setPrologueData(C);
2837 return error("Expected a constant");
2839 FunctionPrologueWorklist.pop_back();
2842 while (!FunctionPersonalityFnWorklist.empty()) {
2843 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2844 if (ValID >= ValueList.size()) {
2845 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2847 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2848 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2850 return error("Expected a constant");
2852 FunctionPersonalityFnWorklist.pop_back();
2855 return std::error_code();
2858 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2859 SmallVector<uint64_t, 8> Words(Vals.size());
2860 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2861 BitcodeReader::decodeSignRotatedValue);
2863 return APInt(TypeBits, Words);
2866 std::error_code BitcodeReader::parseConstants() {
2867 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2868 return error("Invalid record");
2870 SmallVector<uint64_t, 64> Record;
2872 // Read all the records for this value table.
2873 Type *CurTy = Type::getInt32Ty(Context);
2874 unsigned NextCstNo = ValueList.size();
2876 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2878 switch (Entry.Kind) {
2879 case BitstreamEntry::SubBlock: // Handled for us already.
2880 case BitstreamEntry::Error:
2881 return error("Malformed block");
2882 case BitstreamEntry::EndBlock:
2883 if (NextCstNo != ValueList.size())
2884 return error("Invalid constant reference");
2886 // Once all the constants have been read, go through and resolve forward
2888 ValueList.resolveConstantForwardRefs();
2889 return std::error_code();
2890 case BitstreamEntry::Record:
2891 // The interesting case.
2897 Type *VoidType = Type::getVoidTy(Context);
2899 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2901 default: // Default behavior: unknown constant
2902 case bitc::CST_CODE_UNDEF: // UNDEF
2903 V = UndefValue::get(CurTy);
2905 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2907 return error("Invalid record");
2908 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2909 return error("Invalid record");
2910 if (TypeList[Record[0]] == VoidType)
2911 return error("Invalid constant type");
2912 CurTy = TypeList[Record[0]];
2913 continue; // Skip the ValueList manipulation.
2914 case bitc::CST_CODE_NULL: // NULL
2915 V = Constant::getNullValue(CurTy);
2917 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2918 if (!CurTy->isIntegerTy() || Record.empty())
2919 return error("Invalid record");
2920 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2922 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2923 if (!CurTy->isIntegerTy() || Record.empty())
2924 return error("Invalid record");
2927 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2928 V = ConstantInt::get(Context, VInt);
2932 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2934 return error("Invalid record");
2935 if (CurTy->isHalfTy())
2936 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2937 APInt(16, (uint16_t)Record[0])));
2938 else if (CurTy->isFloatTy())
2939 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2940 APInt(32, (uint32_t)Record[0])));
2941 else if (CurTy->isDoubleTy())
2942 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2943 APInt(64, Record[0])));
2944 else if (CurTy->isX86_FP80Ty()) {
2945 // Bits are not stored the same way as a normal i80 APInt, compensate.
2946 uint64_t Rearrange[2];
2947 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2948 Rearrange[1] = Record[0] >> 48;
2949 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2950 APInt(80, Rearrange)));
2951 } else if (CurTy->isFP128Ty())
2952 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2953 APInt(128, Record)));
2954 else if (CurTy->isPPC_FP128Ty())
2955 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2956 APInt(128, Record)));
2958 V = UndefValue::get(CurTy);
2962 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2964 return error("Invalid record");
2966 unsigned Size = Record.size();
2967 SmallVector<Constant*, 16> Elts;
2969 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2970 for (unsigned i = 0; i != Size; ++i)
2971 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2972 STy->getElementType(i)));
2973 V = ConstantStruct::get(STy, Elts);
2974 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2975 Type *EltTy = ATy->getElementType();
2976 for (unsigned i = 0; i != Size; ++i)
2977 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2978 V = ConstantArray::get(ATy, Elts);
2979 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2980 Type *EltTy = VTy->getElementType();
2981 for (unsigned i = 0; i != Size; ++i)
2982 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2983 V = ConstantVector::get(Elts);
2985 V = UndefValue::get(CurTy);
2989 case bitc::CST_CODE_STRING: // STRING: [values]
2990 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2992 return error("Invalid record");
2994 SmallString<16> Elts(Record.begin(), Record.end());
2995 V = ConstantDataArray::getString(Context, Elts,
2996 BitCode == bitc::CST_CODE_CSTRING);
2999 case bitc::CST_CODE_DATA: {// DATA: [n x value]
3001 return error("Invalid record");
3003 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
3004 if (EltTy->isIntegerTy(8)) {
3005 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3006 if (isa<VectorType>(CurTy))
3007 V = ConstantDataVector::get(Context, Elts);
3009 V = ConstantDataArray::get(Context, Elts);
3010 } else if (EltTy->isIntegerTy(16)) {
3011 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3012 if (isa<VectorType>(CurTy))
3013 V = ConstantDataVector::get(Context, Elts);
3015 V = ConstantDataArray::get(Context, Elts);
3016 } else if (EltTy->isIntegerTy(32)) {
3017 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3018 if (isa<VectorType>(CurTy))
3019 V = ConstantDataVector::get(Context, Elts);
3021 V = ConstantDataArray::get(Context, Elts);
3022 } else if (EltTy->isIntegerTy(64)) {
3023 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3024 if (isa<VectorType>(CurTy))
3025 V = ConstantDataVector::get(Context, Elts);
3027 V = ConstantDataArray::get(Context, Elts);
3028 } else if (EltTy->isHalfTy()) {
3029 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3030 if (isa<VectorType>(CurTy))
3031 V = ConstantDataVector::getFP(Context, Elts);
3033 V = ConstantDataArray::getFP(Context, Elts);
3034 } else if (EltTy->isFloatTy()) {
3035 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3036 if (isa<VectorType>(CurTy))
3037 V = ConstantDataVector::getFP(Context, Elts);
3039 V = ConstantDataArray::getFP(Context, Elts);
3040 } else if (EltTy->isDoubleTy()) {
3041 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3042 if (isa<VectorType>(CurTy))
3043 V = ConstantDataVector::getFP(Context, Elts);
3045 V = ConstantDataArray::getFP(Context, Elts);
3047 return error("Invalid type for value");
3051 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
3052 if (Record.size() < 3)
3053 return error("Invalid record");
3054 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3056 V = UndefValue::get(CurTy); // Unknown binop.
3058 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
3059 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
3061 if (Record.size() >= 4) {
3062 if (Opc == Instruction::Add ||
3063 Opc == Instruction::Sub ||
3064 Opc == Instruction::Mul ||
3065 Opc == Instruction::Shl) {
3066 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3067 Flags |= OverflowingBinaryOperator::NoSignedWrap;
3068 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3069 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3070 } else if (Opc == Instruction::SDiv ||
3071 Opc == Instruction::UDiv ||
3072 Opc == Instruction::LShr ||
3073 Opc == Instruction::AShr) {
3074 if (Record[3] & (1 << bitc::PEO_EXACT))
3075 Flags |= SDivOperator::IsExact;
3078 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
3082 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
3083 if (Record.size() < 3)
3084 return error("Invalid record");
3085 int Opc = getDecodedCastOpcode(Record[0]);
3087 V = UndefValue::get(CurTy); // Unknown cast.
3089 Type *OpTy = getTypeByID(Record[1]);
3091 return error("Invalid record");
3092 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
3093 V = UpgradeBitCastExpr(Opc, Op, CurTy);
3094 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
3098 case bitc::CST_CODE_CE_INBOUNDS_GEP:
3099 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
3101 Type *PointeeType = nullptr;
3102 if (Record.size() % 2)
3103 PointeeType = getTypeByID(Record[OpNum++]);
3104 SmallVector<Constant*, 16> Elts;
3105 while (OpNum != Record.size()) {
3106 Type *ElTy = getTypeByID(Record[OpNum++]);
3108 return error("Invalid record");
3109 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
3114 cast<SequentialType>(Elts[0]->getType()->getScalarType())
3116 return error("Explicit gep operator type does not match pointee type "
3117 "of pointer operand");
3119 if (Elts.size() < 1)
3120 return error("Invalid gep with no operands");
3122 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3123 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
3125 bitc::CST_CODE_CE_INBOUNDS_GEP);
3128 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
3129 if (Record.size() < 3)
3130 return error("Invalid record");
3132 Type *SelectorTy = Type::getInt1Ty(Context);
3134 // The selector might be an i1 or an <n x i1>
3135 // Get the type from the ValueList before getting a forward ref.
3136 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
3137 if (Value *V = ValueList[Record[0]])
3138 if (SelectorTy != V->getType())
3139 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
3141 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
3143 ValueList.getConstantFwdRef(Record[1],CurTy),
3144 ValueList.getConstantFwdRef(Record[2],CurTy));
3147 case bitc::CST_CODE_CE_EXTRACTELT
3148 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3149 if (Record.size() < 3)
3150 return error("Invalid record");
3152 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3154 return error("Invalid record");
3155 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3156 Constant *Op1 = nullptr;
3157 if (Record.size() == 4) {
3158 Type *IdxTy = getTypeByID(Record[2]);
3160 return error("Invalid record");
3161 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3162 } else // TODO: Remove with llvm 4.0
3163 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3165 return error("Invalid record");
3166 V = ConstantExpr::getExtractElement(Op0, Op1);
3169 case bitc::CST_CODE_CE_INSERTELT
3170 : { // CE_INSERTELT: [opval, opval, opty, opval]
3171 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3172 if (Record.size() < 3 || !OpTy)
3173 return error("Invalid record");
3174 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3175 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
3176 OpTy->getElementType());
3177 Constant *Op2 = nullptr;
3178 if (Record.size() == 4) {
3179 Type *IdxTy = getTypeByID(Record[2]);
3181 return error("Invalid record");
3182 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3183 } else // TODO: Remove with llvm 4.0
3184 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3186 return error("Invalid record");
3187 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
3190 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3191 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3192 if (Record.size() < 3 || !OpTy)
3193 return error("Invalid record");
3194 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3195 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
3196 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
3197 OpTy->getNumElements());
3198 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
3199 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
3202 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3203 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3205 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3206 if (Record.size() < 4 || !RTy || !OpTy)
3207 return error("Invalid record");
3208 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3209 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3210 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
3211 RTy->getNumElements());
3212 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
3213 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
3216 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
3217 if (Record.size() < 4)
3218 return error("Invalid record");
3219 Type *OpTy = getTypeByID(Record[0]);
3221 return error("Invalid record");
3222 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3223 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3225 if (OpTy->isFPOrFPVectorTy())
3226 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
3228 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
3231 // This maintains backward compatibility, pre-asm dialect keywords.
3232 // FIXME: Remove with the 4.0 release.
3233 case bitc::CST_CODE_INLINEASM_OLD: {
3234 if (Record.size() < 2)
3235 return error("Invalid record");
3236 std::string AsmStr, ConstrStr;
3237 bool HasSideEffects = Record[0] & 1;
3238 bool IsAlignStack = Record[0] >> 1;
3239 unsigned AsmStrSize = Record[1];
3240 if (2+AsmStrSize >= Record.size())
3241 return error("Invalid record");
3242 unsigned ConstStrSize = Record[2+AsmStrSize];
3243 if (3+AsmStrSize+ConstStrSize > Record.size())
3244 return error("Invalid record");
3246 for (unsigned i = 0; i != AsmStrSize; ++i)
3247 AsmStr += (char)Record[2+i];
3248 for (unsigned i = 0; i != ConstStrSize; ++i)
3249 ConstrStr += (char)Record[3+AsmStrSize+i];
3250 PointerType *PTy = cast<PointerType>(CurTy);
3251 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3252 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
3255 // This version adds support for the asm dialect keywords (e.g.,
3257 case bitc::CST_CODE_INLINEASM: {
3258 if (Record.size() < 2)
3259 return error("Invalid record");
3260 std::string AsmStr, ConstrStr;
3261 bool HasSideEffects = Record[0] & 1;
3262 bool IsAlignStack = (Record[0] >> 1) & 1;
3263 unsigned AsmDialect = Record[0] >> 2;
3264 unsigned AsmStrSize = Record[1];
3265 if (2+AsmStrSize >= Record.size())
3266 return error("Invalid record");
3267 unsigned ConstStrSize = Record[2+AsmStrSize];
3268 if (3+AsmStrSize+ConstStrSize > Record.size())
3269 return error("Invalid record");
3271 for (unsigned i = 0; i != AsmStrSize; ++i)
3272 AsmStr += (char)Record[2+i];
3273 for (unsigned i = 0; i != ConstStrSize; ++i)
3274 ConstrStr += (char)Record[3+AsmStrSize+i];
3275 PointerType *PTy = cast<PointerType>(CurTy);
3276 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3277 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3278 InlineAsm::AsmDialect(AsmDialect));
3281 case bitc::CST_CODE_BLOCKADDRESS:{
3282 if (Record.size() < 3)
3283 return error("Invalid record");
3284 Type *FnTy = getTypeByID(Record[0]);
3286 return error("Invalid record");
3288 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
3290 return error("Invalid record");
3292 // If the function is already parsed we can insert the block address right
3295 unsigned BBID = Record[2];
3297 // Invalid reference to entry block.
3298 return error("Invalid ID");
3300 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
3301 for (size_t I = 0, E = BBID; I != E; ++I) {
3303 return error("Invalid ID");
3308 // Otherwise insert a placeholder and remember it so it can be inserted
3309 // when the function is parsed.
3310 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3312 BasicBlockFwdRefQueue.push_back(Fn);
3313 if (FwdBBs.size() < BBID + 1)
3314 FwdBBs.resize(BBID + 1);
3316 FwdBBs[BBID] = BasicBlock::Create(Context);
3319 V = BlockAddress::get(Fn, BB);
3324 ValueList.assignValue(V, NextCstNo);
3329 std::error_code BitcodeReader::parseUseLists() {
3330 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3331 return error("Invalid record");
3333 // Read all the records.
3334 SmallVector<uint64_t, 64> Record;
3336 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3338 switch (Entry.Kind) {
3339 case BitstreamEntry::SubBlock: // Handled for us already.
3340 case BitstreamEntry::Error:
3341 return error("Malformed block");
3342 case BitstreamEntry::EndBlock:
3343 return std::error_code();
3344 case BitstreamEntry::Record:
3345 // The interesting case.
3349 // Read a use list record.
3352 switch (Stream.readRecord(Entry.ID, Record)) {
3353 default: // Default behavior: unknown type.
3355 case bitc::USELIST_CODE_BB:
3358 case bitc::USELIST_CODE_DEFAULT: {
3359 unsigned RecordLength = Record.size();
3360 if (RecordLength < 3)
3361 // Records should have at least an ID and two indexes.
3362 return error("Invalid record");
3363 unsigned ID = Record.back();
3368 assert(ID < FunctionBBs.size() && "Basic block not found");
3369 V = FunctionBBs[ID];
3372 unsigned NumUses = 0;
3373 SmallDenseMap<const Use *, unsigned, 16> Order;
3374 for (const Use &U : V->materialized_uses()) {
3375 if (++NumUses > Record.size())
3377 Order[&U] = Record[NumUses - 1];
3379 if (Order.size() != Record.size() || NumUses > Record.size())
3380 // Mismatches can happen if the functions are being materialized lazily
3381 // (out-of-order), or a value has been upgraded.
3384 V->sortUseList([&](const Use &L, const Use &R) {
3385 return Order.lookup(&L) < Order.lookup(&R);
3393 /// When we see the block for metadata, remember where it is and then skip it.
3394 /// This lets us lazily deserialize the metadata.
3395 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3396 // Save the current stream state.
3397 uint64_t CurBit = Stream.GetCurrentBitNo();
3398 DeferredMetadataInfo.push_back(CurBit);
3400 // Skip over the block for now.
3401 if (Stream.SkipBlock())
3402 return error("Invalid record");
3403 return std::error_code();
3406 std::error_code BitcodeReader::materializeMetadata() {
3407 for (uint64_t BitPos : DeferredMetadataInfo) {
3408 // Move the bit stream to the saved position.
3409 Stream.JumpToBit(BitPos);
3410 if (std::error_code EC = parseMetadata(true))
3413 DeferredMetadataInfo.clear();
3414 return std::error_code();
3417 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3419 /// When we see the block for a function body, remember where it is and then
3420 /// skip it. This lets us lazily deserialize the functions.
3421 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3422 // Get the function we are talking about.
3423 if (FunctionsWithBodies.empty())
3424 return error("Insufficient function protos");
3426 Function *Fn = FunctionsWithBodies.back();
3427 FunctionsWithBodies.pop_back();
3429 // Save the current stream state.
3430 uint64_t CurBit = Stream.GetCurrentBitNo();
3432 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3433 "Mismatch between VST and scanned function offsets");
3434 DeferredFunctionInfo[Fn] = CurBit;
3436 // Skip over the function block for now.
3437 if (Stream.SkipBlock())
3438 return error("Invalid record");
3439 return std::error_code();
3442 std::error_code BitcodeReader::globalCleanup() {
3443 // Patch the initializers for globals and aliases up.
3444 resolveGlobalAndIndirectSymbolInits();
3445 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3446 return error("Malformed global initializer set");
3448 // Look for intrinsic functions which need to be upgraded at some point
3449 for (Function &F : *TheModule) {
3451 if (UpgradeIntrinsicFunction(&F, NewFn))
3452 UpgradedIntrinsics[&F] = NewFn;
3453 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3454 // Some types could be renamed during loading if several modules are
3455 // loaded in the same LLVMContext (LTO scenario). In this case we should
3456 // remangle intrinsics names as well.
3457 RemangledIntrinsics[&F] = Remangled.getValue();
3460 // Look for global variables which need to be renamed.
3461 for (GlobalVariable &GV : TheModule->globals())
3462 UpgradeGlobalVariable(&GV);
3464 // Force deallocation of memory for these vectors to favor the client that
3465 // want lazy deserialization.
3466 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3467 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3468 IndirectSymbolInits);
3469 return std::error_code();
3472 /// Support for lazy parsing of function bodies. This is required if we
3473 /// either have an old bitcode file without a VST forward declaration record,
3474 /// or if we have an anonymous function being materialized, since anonymous
3475 /// functions do not have a name and are therefore not in the VST.
3476 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3477 Stream.JumpToBit(NextUnreadBit);
3479 if (Stream.AtEndOfStream())
3480 return error("Could not find function in stream");
3482 if (!SeenFirstFunctionBody)
3483 return error("Trying to materialize functions before seeing function blocks");
3485 // An old bitcode file with the symbol table at the end would have
3486 // finished the parse greedily.
3487 assert(SeenValueSymbolTable);
3489 SmallVector<uint64_t, 64> Record;
3492 BitstreamEntry Entry = Stream.advance();
3493 switch (Entry.Kind) {
3495 return error("Expect SubBlock");
3496 case BitstreamEntry::SubBlock:
3499 return error("Expect function block");
3500 case bitc::FUNCTION_BLOCK_ID:
3501 if (std::error_code EC = rememberAndSkipFunctionBody())
3503 NextUnreadBit = Stream.GetCurrentBitNo();
3504 return std::error_code();
3510 std::error_code BitcodeReader::parseBitcodeVersion() {
3511 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3512 return error("Invalid record");
3514 // Read all the records.
3515 SmallVector<uint64_t, 64> Record;
3517 BitstreamEntry Entry = Stream.advance();
3519 switch (Entry.Kind) {
3521 case BitstreamEntry::Error:
3522 return error("Malformed block");
3523 case BitstreamEntry::EndBlock:
3524 return std::error_code();
3525 case BitstreamEntry::Record:
3526 // The interesting case.
3532 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3534 default: // Default behavior: reject
3535 return error("Invalid value");
3536 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3538 convertToString(Record, 0, ProducerIdentification);
3541 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3542 unsigned epoch = (unsigned)Record[0];
3543 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3545 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3546 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3553 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3554 bool ShouldLazyLoadMetadata) {
3556 Stream.JumpToBit(ResumeBit);
3557 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3558 return error("Invalid record");
3560 SmallVector<uint64_t, 64> Record;
3561 std::vector<std::string> SectionTable;
3562 std::vector<std::string> GCTable;
3564 // Read all the records for this module.
3566 BitstreamEntry Entry = Stream.advance();
3568 switch (Entry.Kind) {
3569 case BitstreamEntry::Error:
3570 return error("Malformed block");
3571 case BitstreamEntry::EndBlock:
3572 return globalCleanup();
3574 case BitstreamEntry::SubBlock:
3576 default: // Skip unknown content.
3577 if (Stream.SkipBlock())
3578 return error("Invalid record");
3580 case bitc::BLOCKINFO_BLOCK_ID:
3581 if (Stream.ReadBlockInfoBlock())
3582 return error("Malformed block");
3584 case bitc::PARAMATTR_BLOCK_ID:
3585 if (std::error_code EC = parseAttributeBlock())
3588 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3589 if (std::error_code EC = parseAttributeGroupBlock())
3592 case bitc::TYPE_BLOCK_ID_NEW:
3593 if (std::error_code EC = parseTypeTable())
3596 case bitc::VALUE_SYMTAB_BLOCK_ID:
3597 if (!SeenValueSymbolTable) {
3598 // Either this is an old form VST without function index and an
3599 // associated VST forward declaration record (which would have caused
3600 // the VST to be jumped to and parsed before it was encountered
3601 // normally in the stream), or there were no function blocks to
3602 // trigger an earlier parsing of the VST.
3603 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3604 if (std::error_code EC = parseValueSymbolTable())
3606 SeenValueSymbolTable = true;
3608 // We must have had a VST forward declaration record, which caused
3609 // the parser to jump to and parse the VST earlier.
3610 assert(VSTOffset > 0);
3611 if (Stream.SkipBlock())
3612 return error("Invalid record");
3615 case bitc::CONSTANTS_BLOCK_ID:
3616 if (std::error_code EC = parseConstants())
3618 if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
3621 case bitc::METADATA_BLOCK_ID:
3622 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3623 if (std::error_code EC = rememberAndSkipMetadata())
3627 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3628 if (std::error_code EC = parseMetadata(true))
3631 case bitc::METADATA_KIND_BLOCK_ID:
3632 if (std::error_code EC = parseMetadataKinds())
3635 case bitc::FUNCTION_BLOCK_ID:
3636 // If this is the first function body we've seen, reverse the
3637 // FunctionsWithBodies list.
3638 if (!SeenFirstFunctionBody) {
3639 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3640 if (std::error_code EC = globalCleanup())
3642 SeenFirstFunctionBody = true;
3645 if (VSTOffset > 0) {
3646 // If we have a VST forward declaration record, make sure we
3647 // parse the VST now if we haven't already. It is needed to
3648 // set up the DeferredFunctionInfo vector for lazy reading.
3649 if (!SeenValueSymbolTable) {
3650 if (std::error_code EC =
3651 BitcodeReader::parseValueSymbolTable(VSTOffset))
3653 SeenValueSymbolTable = true;
3654 // Fall through so that we record the NextUnreadBit below.
3655 // This is necessary in case we have an anonymous function that
3656 // is later materialized. Since it will not have a VST entry we
3657 // need to fall back to the lazy parse to find its offset.
3659 // If we have a VST forward declaration record, but have already
3660 // parsed the VST (just above, when the first function body was
3661 // encountered here), then we are resuming the parse after
3662 // materializing functions. The ResumeBit points to the
3663 // start of the last function block recorded in the
3664 // DeferredFunctionInfo map. Skip it.
3665 if (Stream.SkipBlock())
3666 return error("Invalid record");
3671 // Support older bitcode files that did not have the function
3672 // index in the VST, nor a VST forward declaration record, as
3673 // well as anonymous functions that do not have VST entries.
3674 // Build the DeferredFunctionInfo vector on the fly.
3675 if (std::error_code EC = rememberAndSkipFunctionBody())
3678 // Suspend parsing when we reach the function bodies. Subsequent
3679 // materialization calls will resume it when necessary. If the bitcode
3680 // file is old, the symbol table will be at the end instead and will not
3681 // have been seen yet. In this case, just finish the parse now.
3682 if (SeenValueSymbolTable) {
3683 NextUnreadBit = Stream.GetCurrentBitNo();
3684 return std::error_code();
3687 case bitc::USELIST_BLOCK_ID:
3688 if (std::error_code EC = parseUseLists())
3691 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3692 if (std::error_code EC = parseOperandBundleTags())
3698 case BitstreamEntry::Record:
3699 // The interesting case.
3704 auto BitCode = Stream.readRecord(Entry.ID, Record);
3706 default: break; // Default behavior, ignore unknown content.
3707 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3708 if (Record.size() < 1)
3709 return error("Invalid record");
3710 // Only version #0 and #1 are supported so far.
3711 unsigned module_version = Record[0];
3712 switch (module_version) {
3714 return error("Invalid value");
3716 UseRelativeIDs = false;
3719 UseRelativeIDs = true;
3724 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3726 if (convertToString(Record, 0, S))
3727 return error("Invalid record");
3728 TheModule->setTargetTriple(S);
3731 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3733 if (convertToString(Record, 0, S))
3734 return error("Invalid record");
3735 TheModule->setDataLayout(S);
3738 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3740 if (convertToString(Record, 0, S))
3741 return error("Invalid record");
3742 TheModule->setModuleInlineAsm(S);
3745 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3746 // FIXME: Remove in 4.0.
3748 if (convertToString(Record, 0, S))
3749 return error("Invalid record");
3753 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3755 if (convertToString(Record, 0, S))
3756 return error("Invalid record");
3757 SectionTable.push_back(S);
3760 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3762 if (convertToString(Record, 0, S))
3763 return error("Invalid record");
3764 GCTable.push_back(S);
3767 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3768 if (Record.size() < 2)
3769 return error("Invalid record");
3770 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3771 unsigned ComdatNameSize = Record[1];
3772 std::string ComdatName;
3773 ComdatName.reserve(ComdatNameSize);
3774 for (unsigned i = 0; i != ComdatNameSize; ++i)
3775 ComdatName += (char)Record[2 + i];
3776 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3777 C->setSelectionKind(SK);
3778 ComdatList.push_back(C);
3781 // GLOBALVAR: [pointer type, isconst, initid,
3782 // linkage, alignment, section, visibility, threadlocal,
3783 // unnamed_addr, externally_initialized, dllstorageclass,
3785 case bitc::MODULE_CODE_GLOBALVAR: {
3786 if (Record.size() < 6)
3787 return error("Invalid record");
3788 Type *Ty = getTypeByID(Record[0]);
3790 return error("Invalid record");
3791 bool isConstant = Record[1] & 1;
3792 bool explicitType = Record[1] & 2;
3793 unsigned AddressSpace;
3795 AddressSpace = Record[1] >> 2;
3797 if (!Ty->isPointerTy())
3798 return error("Invalid type for value");
3799 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3800 Ty = cast<PointerType>(Ty)->getElementType();
3803 uint64_t RawLinkage = Record[3];
3804 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3806 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3808 std::string Section;
3810 if (Record[5]-1 >= SectionTable.size())
3811 return error("Invalid ID");
3812 Section = SectionTable[Record[5]-1];
3814 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3815 // Local linkage must have default visibility.
3816 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3817 // FIXME: Change to an error if non-default in 4.0.
3818 Visibility = getDecodedVisibility(Record[6]);
3820 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3821 if (Record.size() > 7)
3822 TLM = getDecodedThreadLocalMode(Record[7]);
3824 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3825 if (Record.size() > 8)
3826 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3828 bool ExternallyInitialized = false;
3829 if (Record.size() > 9)
3830 ExternallyInitialized = Record[9];
3832 GlobalVariable *NewGV =
3833 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3834 TLM, AddressSpace, ExternallyInitialized);
3835 NewGV->setAlignment(Alignment);
3836 if (!Section.empty())
3837 NewGV->setSection(Section);
3838 NewGV->setVisibility(Visibility);
3839 NewGV->setUnnamedAddr(UnnamedAddr);
3841 if (Record.size() > 10)
3842 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3844 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3846 ValueList.push_back(NewGV);
3848 // Remember which value to use for the global initializer.
3849 if (unsigned InitID = Record[2])
3850 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3852 if (Record.size() > 11) {
3853 if (unsigned ComdatID = Record[11]) {
3854 if (ComdatID > ComdatList.size())
3855 return error("Invalid global variable comdat ID");
3856 NewGV->setComdat(ComdatList[ComdatID - 1]);
3858 } else if (hasImplicitComdat(RawLinkage)) {
3859 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3864 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3865 // alignment, section, visibility, gc, unnamed_addr,
3866 // prologuedata, dllstorageclass, comdat, prefixdata]
3867 case bitc::MODULE_CODE_FUNCTION: {
3868 if (Record.size() < 8)
3869 return error("Invalid record");
3870 Type *Ty = getTypeByID(Record[0]);
3872 return error("Invalid record");
3873 if (auto *PTy = dyn_cast<PointerType>(Ty))
3874 Ty = PTy->getElementType();
3875 auto *FTy = dyn_cast<FunctionType>(Ty);
3877 return error("Invalid type for value");
3878 auto CC = static_cast<CallingConv::ID>(Record[1]);
3879 if (CC & ~CallingConv::MaxID)
3880 return error("Invalid calling convention ID");
3882 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3885 Func->setCallingConv(CC);
3886 bool isProto = Record[2];
3887 uint64_t RawLinkage = Record[3];
3888 Func->setLinkage(getDecodedLinkage(RawLinkage));
3889 Func->setAttributes(getAttributes(Record[4]));
3892 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3894 Func->setAlignment(Alignment);
3896 if (Record[6]-1 >= SectionTable.size())
3897 return error("Invalid ID");
3898 Func->setSection(SectionTable[Record[6]-1]);
3900 // Local linkage must have default visibility.
3901 if (!Func->hasLocalLinkage())
3902 // FIXME: Change to an error if non-default in 4.0.
3903 Func->setVisibility(getDecodedVisibility(Record[7]));
3904 if (Record.size() > 8 && Record[8]) {
3905 if (Record[8]-1 >= GCTable.size())
3906 return error("Invalid ID");
3907 Func->setGC(GCTable[Record[8] - 1]);
3909 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3910 if (Record.size() > 9)
3911 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3912 Func->setUnnamedAddr(UnnamedAddr);
3913 if (Record.size() > 10 && Record[10] != 0)
3914 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3916 if (Record.size() > 11)
3917 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3919 upgradeDLLImportExportLinkage(Func, RawLinkage);
3921 if (Record.size() > 12) {
3922 if (unsigned ComdatID = Record[12]) {
3923 if (ComdatID > ComdatList.size())
3924 return error("Invalid function comdat ID");
3925 Func->setComdat(ComdatList[ComdatID - 1]);
3927 } else if (hasImplicitComdat(RawLinkage)) {
3928 Func->setComdat(reinterpret_cast<Comdat *>(1));
3931 if (Record.size() > 13 && Record[13] != 0)
3932 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3934 if (Record.size() > 14 && Record[14] != 0)
3935 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3937 ValueList.push_back(Func);
3939 // If this is a function with a body, remember the prototype we are
3940 // creating now, so that we can match up the body with them later.
3942 Func->setIsMaterializable(true);
3943 FunctionsWithBodies.push_back(Func);
3944 DeferredFunctionInfo[Func] = 0;
3948 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3949 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3950 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3951 case bitc::MODULE_CODE_IFUNC:
3952 case bitc::MODULE_CODE_ALIAS:
3953 case bitc::MODULE_CODE_ALIAS_OLD: {
3954 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3955 if (Record.size() < (3 + (unsigned)NewRecord))
3956 return error("Invalid record");
3958 Type *Ty = getTypeByID(Record[OpNum++]);
3960 return error("Invalid record");
3964 auto *PTy = dyn_cast<PointerType>(Ty);
3966 return error("Invalid type for value");
3967 Ty = PTy->getElementType();
3968 AddrSpace = PTy->getAddressSpace();
3970 AddrSpace = Record[OpNum++];
3973 auto Val = Record[OpNum++];
3974 auto Linkage = Record[OpNum++];
3975 GlobalIndirectSymbol *NewGA;
3976 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3977 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3978 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3981 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3982 "", nullptr, TheModule);
3983 // Old bitcode files didn't have visibility field.
3984 // Local linkage must have default visibility.
3985 if (OpNum != Record.size()) {
3986 auto VisInd = OpNum++;
3987 if (!NewGA->hasLocalLinkage())
3988 // FIXME: Change to an error if non-default in 4.0.
3989 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3991 if (OpNum != Record.size())
3992 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3994 upgradeDLLImportExportLinkage(NewGA, Linkage);
3995 if (OpNum != Record.size())
3996 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3997 if (OpNum != Record.size())
3998 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3999 ValueList.push_back(NewGA);
4000 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4003 /// MODULE_CODE_PURGEVALS: [numvals]
4004 case bitc::MODULE_CODE_PURGEVALS:
4005 // Trim down the value list to the specified size.
4006 if (Record.size() < 1 || Record[0] > ValueList.size())
4007 return error("Invalid record");
4008 ValueList.shrinkTo(Record[0]);
4010 /// MODULE_CODE_VSTOFFSET: [offset]
4011 case bitc::MODULE_CODE_VSTOFFSET:
4012 if (Record.size() < 1)
4013 return error("Invalid record");
4014 VSTOffset = Record[0];
4016 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4017 case bitc::MODULE_CODE_SOURCE_FILENAME:
4018 SmallString<128> ValueName;
4019 if (convertToString(Record, 0, ValueName))
4020 return error("Invalid record");
4021 TheModule->setSourceFileName(ValueName);
4028 /// Helper to read the header common to all bitcode files.
4029 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
4030 // Sniff for the signature.
4031 if (Stream.Read(8) != 'B' ||
4032 Stream.Read(8) != 'C' ||
4033 Stream.Read(4) != 0x0 ||
4034 Stream.Read(4) != 0xC ||
4035 Stream.Read(4) != 0xE ||
4036 Stream.Read(4) != 0xD)
4042 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
4043 Module *M, bool ShouldLazyLoadMetadata) {
4046 if (std::error_code EC = initStream(std::move(Streamer)))
4049 // Sniff for the signature.
4050 if (!hasValidBitcodeHeader(Stream))
4051 return error("Invalid bitcode signature");
4053 // We expect a number of well-defined blocks, though we don't necessarily
4054 // need to understand them all.
4056 if (Stream.AtEndOfStream()) {
4057 // We didn't really read a proper Module.
4058 return error("Malformed IR file");
4061 BitstreamEntry Entry =
4062 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
4064 if (Entry.Kind != BitstreamEntry::SubBlock)
4065 return error("Malformed block");
4067 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4068 parseBitcodeVersion();
4072 if (Entry.ID == bitc::MODULE_BLOCK_ID)
4073 return parseModule(0, ShouldLazyLoadMetadata);
4075 if (Stream.SkipBlock())
4076 return error("Invalid record");
4080 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
4081 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4082 return error("Invalid record");
4084 SmallVector<uint64_t, 64> Record;
4087 // Read all the records for this module.
4089 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4091 switch (Entry.Kind) {
4092 case BitstreamEntry::SubBlock: // Handled for us already.
4093 case BitstreamEntry::Error:
4094 return error("Malformed block");
4095 case BitstreamEntry::EndBlock:
4097 case BitstreamEntry::Record:
4098 // The interesting case.
4103 switch (Stream.readRecord(Entry.ID, Record)) {
4104 default: break; // Default behavior, ignore unknown content.
4105 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
4107 if (convertToString(Record, 0, S))
4108 return error("Invalid record");
4115 llvm_unreachable("Exit infinite loop");
4118 ErrorOr<std::string> BitcodeReader::parseTriple() {
4119 if (std::error_code EC = initStream(nullptr))
4122 // Sniff for the signature.
4123 if (!hasValidBitcodeHeader(Stream))
4124 return error("Invalid bitcode signature");
4126 // We expect a number of well-defined blocks, though we don't necessarily
4127 // need to understand them all.
4129 BitstreamEntry Entry = Stream.advance();
4131 switch (Entry.Kind) {
4132 case BitstreamEntry::Error:
4133 return error("Malformed block");
4134 case BitstreamEntry::EndBlock:
4135 return std::error_code();
4137 case BitstreamEntry::SubBlock:
4138 if (Entry.ID == bitc::MODULE_BLOCK_ID)
4139 return parseModuleTriple();
4141 // Ignore other sub-blocks.
4142 if (Stream.SkipBlock())
4143 return error("Malformed block");
4146 case BitstreamEntry::Record:
4147 Stream.skipRecord(Entry.ID);
4153 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
4154 if (std::error_code EC = initStream(nullptr))
4157 // Sniff for the signature.
4158 if (!hasValidBitcodeHeader(Stream))
4159 return error("Invalid bitcode signature");
4161 // We expect a number of well-defined blocks, though we don't necessarily
4162 // need to understand them all.
4164 BitstreamEntry Entry = Stream.advance();
4165 switch (Entry.Kind) {
4166 case BitstreamEntry::Error:
4167 return error("Malformed block");
4168 case BitstreamEntry::EndBlock:
4169 return std::error_code();
4171 case BitstreamEntry::SubBlock:
4172 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4173 if (std::error_code EC = parseBitcodeVersion())
4175 return ProducerIdentification;
4177 // Ignore other sub-blocks.
4178 if (Stream.SkipBlock())
4179 return error("Malformed block");
4181 case BitstreamEntry::Record:
4182 Stream.skipRecord(Entry.ID);
4188 std::error_code BitcodeReader::parseGlobalObjectAttachment(
4189 GlobalObject &GO, ArrayRef<uint64_t> Record) {
4190 assert(Record.size() % 2 == 0);
4191 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
4192 auto K = MDKindMap.find(Record[I]);
4193 if (K == MDKindMap.end())
4194 return error("Invalid ID");
4195 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
4197 return error("Invalid metadata attachment");
4198 GO.addMetadata(K->second, *MD);
4200 return std::error_code();
4203 ErrorOr<bool> BitcodeReader::hasObjCCategory() {
4204 if (std::error_code EC = initStream(nullptr))
4207 // Sniff for the signature.
4208 if (!hasValidBitcodeHeader(Stream))
4209 return error("Invalid bitcode signature");
4211 // We expect a number of well-defined blocks, though we don't necessarily
4212 // need to understand them all.
4214 BitstreamEntry Entry = Stream.advance();
4216 switch (Entry.Kind) {
4217 case BitstreamEntry::Error:
4218 return error("Malformed block");
4219 case BitstreamEntry::EndBlock:
4220 return std::error_code();
4222 case BitstreamEntry::SubBlock:
4223 if (Entry.ID == bitc::MODULE_BLOCK_ID)
4224 return hasObjCCategoryInModule();
4226 // Ignore other sub-blocks.
4227 if (Stream.SkipBlock())
4228 return error("Malformed block");
4231 case BitstreamEntry::Record:
4232 Stream.skipRecord(Entry.ID);
4238 ErrorOr<bool> BitcodeReader::hasObjCCategoryInModule() {
4239 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4240 return error("Invalid record");
4242 SmallVector<uint64_t, 64> Record;
4243 // Read all the records for this module.
4245 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4247 switch (Entry.Kind) {
4248 case BitstreamEntry::SubBlock: // Handled for us already.
4249 case BitstreamEntry::Error:
4250 return error("Malformed block");
4251 case BitstreamEntry::EndBlock:
4253 case BitstreamEntry::Record:
4254 // The interesting case.
4259 switch (Stream.readRecord(Entry.ID, Record)) {
4261 break; // Default behavior, ignore unknown content.
4262 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4264 if (convertToString(Record, 0, S))
4265 return error("Invalid record");
4266 // Check for the i386 and other (x86_64, ARM) conventions
4267 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
4268 S.find("__OBJC,__category") != std::string::npos)
4275 llvm_unreachable("Exit infinite loop");
4278 /// Parse metadata attachments.
4279 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
4280 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
4281 return error("Invalid record");
4283 SmallVector<uint64_t, 64> Record;
4285 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4287 switch (Entry.Kind) {
4288 case BitstreamEntry::SubBlock: // Handled for us already.
4289 case BitstreamEntry::Error:
4290 return error("Malformed block");
4291 case BitstreamEntry::EndBlock:
4292 return std::error_code();
4293 case BitstreamEntry::Record:
4294 // The interesting case.
4298 // Read a metadata attachment record.
4300 switch (Stream.readRecord(Entry.ID, Record)) {
4301 default: // Default behavior: ignore.
4303 case bitc::METADATA_ATTACHMENT: {
4304 unsigned RecordLength = Record.size();
4306 return error("Invalid record");
4307 if (RecordLength % 2 == 0) {
4308 // A function attachment.
4309 if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
4314 // An instruction attachment.
4315 Instruction *Inst = InstructionList[Record[0]];
4316 for (unsigned i = 1; i != RecordLength; i = i+2) {
4317 unsigned Kind = Record[i];
4318 DenseMap<unsigned, unsigned>::iterator I =
4319 MDKindMap.find(Kind);
4320 if (I == MDKindMap.end())
4321 return error("Invalid ID");
4322 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
4323 if (isa<LocalAsMetadata>(Node))
4324 // Drop the attachment. This used to be legal, but there's no
4327 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
4329 return error("Invalid metadata attachment");
4331 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
4332 MD = upgradeInstructionLoopAttachment(*MD);
4334 Inst->setMetadata(I->second, MD);
4335 if (I->second == LLVMContext::MD_tbaa) {
4336 InstsWithTBAATag.push_back(Inst);
4346 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4347 LLVMContext &Context = PtrType->getContext();
4348 if (!isa<PointerType>(PtrType))
4349 return error(Context, "Load/Store operand is not a pointer type");
4350 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4352 if (ValType && ValType != ElemType)
4353 return error(Context, "Explicit load/store type does not match pointee "
4354 "type of pointer operand");
4355 if (!PointerType::isLoadableOrStorableType(ElemType))
4356 return error(Context, "Cannot load/store from pointer");
4357 return std::error_code();
4360 /// Lazily parse the specified function body block.
4361 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
4362 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4363 return error("Invalid record");
4365 // Unexpected unresolved metadata when parsing function.
4366 if (MetadataList.hasFwdRefs())
4367 return error("Invalid function metadata: incoming forward references");
4369 InstructionList.clear();
4370 unsigned ModuleValueListSize = ValueList.size();
4371 unsigned ModuleMetadataListSize = MetadataList.size();
4373 // Add all the function arguments to the value table.
4374 for (Argument &I : F->args())
4375 ValueList.push_back(&I);
4377 unsigned NextValueNo = ValueList.size();
4378 BasicBlock *CurBB = nullptr;
4379 unsigned CurBBNo = 0;
4382 auto getLastInstruction = [&]() -> Instruction * {
4383 if (CurBB && !CurBB->empty())
4384 return &CurBB->back();
4385 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4386 !FunctionBBs[CurBBNo - 1]->empty())
4387 return &FunctionBBs[CurBBNo - 1]->back();
4391 std::vector<OperandBundleDef> OperandBundles;
4393 // Read all the records.
4394 SmallVector<uint64_t, 64> Record;
4396 BitstreamEntry Entry = Stream.advance();
4398 switch (Entry.Kind) {
4399 case BitstreamEntry::Error:
4400 return error("Malformed block");
4401 case BitstreamEntry::EndBlock:
4402 goto OutOfRecordLoop;
4404 case BitstreamEntry::SubBlock:
4406 default: // Skip unknown content.
4407 if (Stream.SkipBlock())
4408 return error("Invalid record");
4410 case bitc::CONSTANTS_BLOCK_ID:
4411 if (std::error_code EC = parseConstants())
4413 NextValueNo = ValueList.size();
4415 case bitc::VALUE_SYMTAB_BLOCK_ID:
4416 if (std::error_code EC = parseValueSymbolTable())
4419 case bitc::METADATA_ATTACHMENT_ID:
4420 if (std::error_code EC = parseMetadataAttachment(*F))
4423 case bitc::METADATA_BLOCK_ID:
4424 if (std::error_code EC = parseMetadata())
4427 case bitc::USELIST_BLOCK_ID:
4428 if (std::error_code EC = parseUseLists())
4434 case BitstreamEntry::Record:
4435 // The interesting case.
4441 Instruction *I = nullptr;
4442 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
4444 default: // Default behavior: reject
4445 return error("Invalid value");
4446 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
4447 if (Record.size() < 1 || Record[0] == 0)
4448 return error("Invalid record");
4449 // Create all the basic blocks for the function.
4450 FunctionBBs.resize(Record[0]);
4452 // See if anything took the address of blocks in this function.
4453 auto BBFRI = BasicBlockFwdRefs.find(F);
4454 if (BBFRI == BasicBlockFwdRefs.end()) {
4455 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4456 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4458 auto &BBRefs = BBFRI->second;
4459 // Check for invalid basic block references.
4460 if (BBRefs.size() > FunctionBBs.size())
4461 return error("Invalid ID");
4462 assert(!BBRefs.empty() && "Unexpected empty array");
4463 assert(!BBRefs.front() && "Invalid reference to entry block");
4464 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4466 if (I < RE && BBRefs[I]) {
4467 BBRefs[I]->insertInto(F);
4468 FunctionBBs[I] = BBRefs[I];
4470 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4473 // Erase from the table.
4474 BasicBlockFwdRefs.erase(BBFRI);
4477 CurBB = FunctionBBs[0];
4481 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4482 // This record indicates that the last instruction is at the same
4483 // location as the previous instruction with a location.
4484 I = getLastInstruction();
4487 return error("Invalid record");
4488 I->setDebugLoc(LastLoc);
4492 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4493 I = getLastInstruction();
4494 if (!I || Record.size() < 4)
4495 return error("Invalid record");
4497 unsigned Line = Record[0], Col = Record[1];
4498 unsigned ScopeID = Record[2], IAID = Record[3];
4500 MDNode *Scope = nullptr, *IA = nullptr;
4502 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4504 return error("Invalid record");
4507 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4509 return error("Invalid record");
4511 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4512 I->setDebugLoc(LastLoc);
4517 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4520 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4521 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4522 OpNum+1 > Record.size())
4523 return error("Invalid record");
4525 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4527 return error("Invalid record");
4528 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4529 InstructionList.push_back(I);
4530 if (OpNum < Record.size()) {
4531 if (Opc == Instruction::Add ||
4532 Opc == Instruction::Sub ||
4533 Opc == Instruction::Mul ||
4534 Opc == Instruction::Shl) {
4535 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4536 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4537 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4538 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4539 } else if (Opc == Instruction::SDiv ||
4540 Opc == Instruction::UDiv ||
4541 Opc == Instruction::LShr ||
4542 Opc == Instruction::AShr) {
4543 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4544 cast<BinaryOperator>(I)->setIsExact(true);
4545 } else if (isa<FPMathOperator>(I)) {
4546 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4548 I->setFastMathFlags(FMF);
4554 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4557 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4558 OpNum+2 != Record.size())
4559 return error("Invalid record");
4561 Type *ResTy = getTypeByID(Record[OpNum]);
4562 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4563 if (Opc == -1 || !ResTy)
4564 return error("Invalid record");
4565 Instruction *Temp = nullptr;
4566 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4568 InstructionList.push_back(Temp);
4569 CurBB->getInstList().push_back(Temp);
4572 auto CastOp = (Instruction::CastOps)Opc;
4573 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4574 return error("Invalid cast");
4575 I = CastInst::Create(CastOp, Op, ResTy);
4577 InstructionList.push_back(I);
4580 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4581 case bitc::FUNC_CODE_INST_GEP_OLD:
4582 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4588 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4589 InBounds = Record[OpNum++];
4590 Ty = getTypeByID(Record[OpNum++]);
4592 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4597 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4598 return error("Invalid record");
4601 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4604 cast<SequentialType>(BasePtr->getType()->getScalarType())
4607 "Explicit gep type does not match pointee type of pointer operand");
4609 SmallVector<Value*, 16> GEPIdx;
4610 while (OpNum != Record.size()) {
4612 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4613 return error("Invalid record");
4614 GEPIdx.push_back(Op);
4617 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4619 InstructionList.push_back(I);
4621 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4625 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4626 // EXTRACTVAL: [opty, opval, n x indices]
4629 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4630 return error("Invalid record");
4632 unsigned RecSize = Record.size();
4633 if (OpNum == RecSize)
4634 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4636 SmallVector<unsigned, 4> EXTRACTVALIdx;
4637 Type *CurTy = Agg->getType();
4638 for (; OpNum != RecSize; ++OpNum) {
4639 bool IsArray = CurTy->isArrayTy();
4640 bool IsStruct = CurTy->isStructTy();
4641 uint64_t Index = Record[OpNum];
4643 if (!IsStruct && !IsArray)
4644 return error("EXTRACTVAL: Invalid type");
4645 if ((unsigned)Index != Index)
4646 return error("Invalid value");
4647 if (IsStruct && Index >= CurTy->subtypes().size())
4648 return error("EXTRACTVAL: Invalid struct index");
4649 if (IsArray && Index >= CurTy->getArrayNumElements())
4650 return error("EXTRACTVAL: Invalid array index");
4651 EXTRACTVALIdx.push_back((unsigned)Index);
4654 CurTy = CurTy->subtypes()[Index];
4656 CurTy = CurTy->subtypes()[0];
4659 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4660 InstructionList.push_back(I);
4664 case bitc::FUNC_CODE_INST_INSERTVAL: {
4665 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4668 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4669 return error("Invalid record");
4671 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4672 return error("Invalid record");
4674 unsigned RecSize = Record.size();
4675 if (OpNum == RecSize)
4676 return error("INSERTVAL: Invalid instruction with 0 indices");
4678 SmallVector<unsigned, 4> INSERTVALIdx;
4679 Type *CurTy = Agg->getType();
4680 for (; OpNum != RecSize; ++OpNum) {
4681 bool IsArray = CurTy->isArrayTy();
4682 bool IsStruct = CurTy->isStructTy();
4683 uint64_t Index = Record[OpNum];
4685 if (!IsStruct && !IsArray)
4686 return error("INSERTVAL: Invalid type");
4687 if ((unsigned)Index != Index)
4688 return error("Invalid value");
4689 if (IsStruct && Index >= CurTy->subtypes().size())
4690 return error("INSERTVAL: Invalid struct index");
4691 if (IsArray && Index >= CurTy->getArrayNumElements())
4692 return error("INSERTVAL: Invalid array index");
4694 INSERTVALIdx.push_back((unsigned)Index);
4696 CurTy = CurTy->subtypes()[Index];
4698 CurTy = CurTy->subtypes()[0];
4701 if (CurTy != Val->getType())
4702 return error("Inserted value type doesn't match aggregate type");
4704 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4705 InstructionList.push_back(I);
4709 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4710 // obsolete form of select
4711 // handles select i1 ... in old bitcode
4713 Value *TrueVal, *FalseVal, *Cond;
4714 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4715 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4716 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4717 return error("Invalid record");
4719 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4720 InstructionList.push_back(I);
4724 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4725 // new form of select
4726 // handles select i1 or select [N x i1]
4728 Value *TrueVal, *FalseVal, *Cond;
4729 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4730 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4731 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4732 return error("Invalid record");
4734 // select condition can be either i1 or [N x i1]
4735 if (VectorType* vector_type =
4736 dyn_cast<VectorType>(Cond->getType())) {
4738 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4739 return error("Invalid type for value");
4742 if (Cond->getType() != Type::getInt1Ty(Context))
4743 return error("Invalid type for value");
4746 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4747 InstructionList.push_back(I);
4751 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4754 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4755 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4756 return error("Invalid record");
4757 if (!Vec->getType()->isVectorTy())
4758 return error("Invalid type for value");
4759 I = ExtractElementInst::Create(Vec, Idx);
4760 InstructionList.push_back(I);
4764 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4766 Value *Vec, *Elt, *Idx;
4767 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4768 return error("Invalid record");
4769 if (!Vec->getType()->isVectorTy())
4770 return error("Invalid type for value");
4771 if (popValue(Record, OpNum, NextValueNo,
4772 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4773 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4774 return error("Invalid record");
4775 I = InsertElementInst::Create(Vec, Elt, Idx);
4776 InstructionList.push_back(I);
4780 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4782 Value *Vec1, *Vec2, *Mask;
4783 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4784 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4785 return error("Invalid record");
4787 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4788 return error("Invalid record");
4789 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4790 return error("Invalid type for value");
4791 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4792 InstructionList.push_back(I);
4796 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4797 // Old form of ICmp/FCmp returning bool
4798 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4799 // both legal on vectors but had different behaviour.
4800 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4801 // FCmp/ICmp returning bool or vector of bool
4805 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4806 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4807 return error("Invalid record");
4809 unsigned PredVal = Record[OpNum];
4810 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4812 if (IsFP && Record.size() > OpNum+1)
4813 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4815 if (OpNum+1 != Record.size())
4816 return error("Invalid record");
4818 if (LHS->getType()->isFPOrFPVectorTy())
4819 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4821 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4824 I->setFastMathFlags(FMF);
4825 InstructionList.push_back(I);
4829 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4831 unsigned Size = Record.size();
4833 I = ReturnInst::Create(Context);
4834 InstructionList.push_back(I);
4839 Value *Op = nullptr;
4840 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4841 return error("Invalid record");
4842 if (OpNum != Record.size())
4843 return error("Invalid record");
4845 I = ReturnInst::Create(Context, Op);
4846 InstructionList.push_back(I);
4849 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4850 if (Record.size() != 1 && Record.size() != 3)
4851 return error("Invalid record");
4852 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4854 return error("Invalid record");
4856 if (Record.size() == 1) {
4857 I = BranchInst::Create(TrueDest);
4858 InstructionList.push_back(I);
4861 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4862 Value *Cond = getValue(Record, 2, NextValueNo,
4863 Type::getInt1Ty(Context));
4864 if (!FalseDest || !Cond)
4865 return error("Invalid record");
4866 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4867 InstructionList.push_back(I);
4871 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4872 if (Record.size() != 1 && Record.size() != 2)
4873 return error("Invalid record");
4876 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4878 return error("Invalid record");
4879 BasicBlock *UnwindDest = nullptr;
4880 if (Record.size() == 2) {
4881 UnwindDest = getBasicBlock(Record[Idx++]);
4883 return error("Invalid record");
4886 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4887 InstructionList.push_back(I);
4890 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4891 if (Record.size() != 2)
4892 return error("Invalid record");
4895 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4897 return error("Invalid record");
4898 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4900 return error("Invalid record");
4902 I = CatchReturnInst::Create(CatchPad, BB);
4903 InstructionList.push_back(I);
4906 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4907 // We must have, at minimum, the outer scope and the number of arguments.
4908 if (Record.size() < 2)
4909 return error("Invalid record");
4914 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4916 unsigned NumHandlers = Record[Idx++];
4918 SmallVector<BasicBlock *, 2> Handlers;
4919 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4920 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4922 return error("Invalid record");
4923 Handlers.push_back(BB);
4926 BasicBlock *UnwindDest = nullptr;
4927 if (Idx + 1 == Record.size()) {
4928 UnwindDest = getBasicBlock(Record[Idx++]);
4930 return error("Invalid record");
4933 if (Record.size() != Idx)
4934 return error("Invalid record");
4937 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4938 for (BasicBlock *Handler : Handlers)
4939 CatchSwitch->addHandler(Handler);
4941 InstructionList.push_back(I);
4944 case bitc::FUNC_CODE_INST_CATCHPAD:
4945 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4946 // We must have, at minimum, the outer scope and the number of arguments.
4947 if (Record.size() < 2)
4948 return error("Invalid record");
4953 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4955 unsigned NumArgOperands = Record[Idx++];
4957 SmallVector<Value *, 2> Args;
4958 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4960 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4961 return error("Invalid record");
4962 Args.push_back(Val);
4965 if (Record.size() != Idx)
4966 return error("Invalid record");
4968 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4969 I = CleanupPadInst::Create(ParentPad, Args);
4971 I = CatchPadInst::Create(ParentPad, Args);
4972 InstructionList.push_back(I);
4975 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4977 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4978 // "New" SwitchInst format with case ranges. The changes to write this
4979 // format were reverted but we still recognize bitcode that uses it.
4980 // Hopefully someday we will have support for case ranges and can use
4981 // this format again.
4983 Type *OpTy = getTypeByID(Record[1]);
4984 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4986 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4987 BasicBlock *Default = getBasicBlock(Record[3]);
4988 if (!OpTy || !Cond || !Default)
4989 return error("Invalid record");
4991 unsigned NumCases = Record[4];
4993 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4994 InstructionList.push_back(SI);
4996 unsigned CurIdx = 5;
4997 for (unsigned i = 0; i != NumCases; ++i) {
4998 SmallVector<ConstantInt*, 1> CaseVals;
4999 unsigned NumItems = Record[CurIdx++];
5000 for (unsigned ci = 0; ci != NumItems; ++ci) {
5001 bool isSingleNumber = Record[CurIdx++];
5004 unsigned ActiveWords = 1;
5005 if (ValueBitWidth > 64)
5006 ActiveWords = Record[CurIdx++];
5007 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
5009 CurIdx += ActiveWords;
5011 if (!isSingleNumber) {
5013 if (ValueBitWidth > 64)
5014 ActiveWords = Record[CurIdx++];
5015 APInt High = readWideAPInt(
5016 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
5017 CurIdx += ActiveWords;
5019 // FIXME: It is not clear whether values in the range should be
5020 // compared as signed or unsigned values. The partially
5021 // implemented changes that used this format in the past used
5022 // unsigned comparisons.
5023 for ( ; Low.ule(High); ++Low)
5024 CaseVals.push_back(ConstantInt::get(Context, Low));
5026 CaseVals.push_back(ConstantInt::get(Context, Low));
5028 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5029 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
5030 cve = CaseVals.end(); cvi != cve; ++cvi)
5031 SI->addCase(*cvi, DestBB);
5037 // Old SwitchInst format without case ranges.
5039 if (Record.size() < 3 || (Record.size() & 1) == 0)
5040 return error("Invalid record");
5041 Type *OpTy = getTypeByID(Record[0]);
5042 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
5043 BasicBlock *Default = getBasicBlock(Record[2]);
5044 if (!OpTy || !Cond || !Default)
5045 return error("Invalid record");
5046 unsigned NumCases = (Record.size()-3)/2;
5047 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5048 InstructionList.push_back(SI);
5049 for (unsigned i = 0, e = NumCases; i != e; ++i) {
5050 ConstantInt *CaseVal =
5051 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
5052 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5053 if (!CaseVal || !DestBB) {
5055 return error("Invalid record");
5057 SI->addCase(CaseVal, DestBB);
5062 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5063 if (Record.size() < 2)
5064 return error("Invalid record");
5065 Type *OpTy = getTypeByID(Record[0]);
5066 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
5067 if (!OpTy || !Address)
5068 return error("Invalid record");
5069 unsigned NumDests = Record.size()-2;
5070 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5071 InstructionList.push_back(IBI);
5072 for (unsigned i = 0, e = NumDests; i != e; ++i) {
5073 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5074 IBI->addDestination(DestBB);
5077 return error("Invalid record");
5084 case bitc::FUNC_CODE_INST_INVOKE: {
5085 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5086 if (Record.size() < 4)
5087 return error("Invalid record");
5089 AttributeSet PAL = getAttributes(Record[OpNum++]);
5090 unsigned CCInfo = Record[OpNum++];
5091 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5092 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5094 FunctionType *FTy = nullptr;
5095 if (CCInfo >> 13 & 1 &&
5096 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5097 return error("Explicit invoke type is not a function type");
5100 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5101 return error("Invalid record");
5103 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5105 return error("Callee is not a pointer");
5107 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
5109 return error("Callee is not of pointer to function type");
5110 } else if (CalleeTy->getElementType() != FTy)
5111 return error("Explicit invoke type does not match pointee type of "
5113 if (Record.size() < FTy->getNumParams() + OpNum)
5114 return error("Insufficient operands to call");
5116 SmallVector<Value*, 16> Ops;
5117 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5118 Ops.push_back(getValue(Record, OpNum, NextValueNo,
5119 FTy->getParamType(i)));
5121 return error("Invalid record");
5124 if (!FTy->isVarArg()) {
5125 if (Record.size() != OpNum)
5126 return error("Invalid record");
5128 // Read type/value pairs for varargs params.
5129 while (OpNum != Record.size()) {
5131 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5132 return error("Invalid record");
5137 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
5138 OperandBundles.clear();
5139 InstructionList.push_back(I);
5140 cast<InvokeInst>(I)->setCallingConv(
5141 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5142 cast<InvokeInst>(I)->setAttributes(PAL);
5145 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5147 Value *Val = nullptr;
5148 if (getValueTypePair(Record, Idx, NextValueNo, Val))
5149 return error("Invalid record");
5150 I = ResumeInst::Create(Val);
5151 InstructionList.push_back(I);
5154 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
5155 I = new UnreachableInst(Context);
5156 InstructionList.push_back(I);
5158 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5159 if (Record.size() < 1 || ((Record.size()-1)&1))
5160 return error("Invalid record");
5161 Type *Ty = getTypeByID(Record[0]);
5163 return error("Invalid record");
5165 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
5166 InstructionList.push_back(PN);
5168 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
5170 // With the new function encoding, it is possible that operands have
5171 // negative IDs (for forward references). Use a signed VBR
5172 // representation to keep the encoding small.
5174 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
5176 V = getValue(Record, 1+i, NextValueNo, Ty);
5177 BasicBlock *BB = getBasicBlock(Record[2+i]);
5179 return error("Invalid record");
5180 PN->addIncoming(V, BB);
5186 case bitc::FUNC_CODE_INST_LANDINGPAD:
5187 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
5188 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5190 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5191 if (Record.size() < 3)
5192 return error("Invalid record");
5194 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5195 if (Record.size() < 4)
5196 return error("Invalid record");
5198 Type *Ty = getTypeByID(Record[Idx++]);
5200 return error("Invalid record");
5201 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5202 Value *PersFn = nullptr;
5203 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
5204 return error("Invalid record");
5206 if (!F->hasPersonalityFn())
5207 F->setPersonalityFn(cast<Constant>(PersFn));
5208 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5209 return error("Personality function mismatch");
5212 bool IsCleanup = !!Record[Idx++];
5213 unsigned NumClauses = Record[Idx++];
5214 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
5215 LP->setCleanup(IsCleanup);
5216 for (unsigned J = 0; J != NumClauses; ++J) {
5217 LandingPadInst::ClauseType CT =
5218 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5221 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
5223 return error("Invalid record");
5226 assert((CT != LandingPadInst::Catch ||
5227 !isa<ArrayType>(Val->getType())) &&
5228 "Catch clause has a invalid type!");
5229 assert((CT != LandingPadInst::Filter ||
5230 isa<ArrayType>(Val->getType())) &&
5231 "Filter clause has invalid type!");
5232 LP->addClause(cast<Constant>(Val));
5236 InstructionList.push_back(I);
5240 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5241 if (Record.size() != 4)
5242 return error("Invalid record");
5243 uint64_t AlignRecord = Record[3];
5244 const uint64_t InAllocaMask = uint64_t(1) << 5;
5245 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
5246 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
5247 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
5249 bool InAlloca = AlignRecord & InAllocaMask;
5250 bool SwiftError = AlignRecord & SwiftErrorMask;
5251 Type *Ty = getTypeByID(Record[0]);
5252 if ((AlignRecord & ExplicitTypeMask) == 0) {
5253 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
5255 return error("Old-style alloca with a non-pointer type");
5256 Ty = PTy->getElementType();
5258 Type *OpTy = getTypeByID(Record[1]);
5259 Value *Size = getFnValueByID(Record[2], OpTy);
5261 if (std::error_code EC =
5262 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
5266 return error("Invalid record");
5267 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
5268 AI->setUsedWithInAlloca(InAlloca);
5269 AI->setSwiftError(SwiftError);
5271 InstructionList.push_back(I);
5274 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5277 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5278 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5279 return error("Invalid record");
5282 if (OpNum + 3 == Record.size())
5283 Ty = getTypeByID(Record[OpNum++]);
5284 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
5287 Ty = cast<PointerType>(Op->getType())->getElementType();
5290 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5292 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
5294 InstructionList.push_back(I);
5297 case bitc::FUNC_CODE_INST_LOADATOMIC: {
5298 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
5301 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5302 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5303 return error("Invalid record");
5306 if (OpNum + 5 == Record.size())
5307 Ty = getTypeByID(Record[OpNum++]);
5308 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
5311 Ty = cast<PointerType>(Op->getType())->getElementType();
5313 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5314 if (Ordering == AtomicOrdering::NotAtomic ||
5315 Ordering == AtomicOrdering::Release ||
5316 Ordering == AtomicOrdering::AcquireRelease)
5317 return error("Invalid record");
5318 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5319 return error("Invalid record");
5320 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5323 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5325 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
5327 InstructionList.push_back(I);
5330 case bitc::FUNC_CODE_INST_STORE:
5331 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5334 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5335 (BitCode == bitc::FUNC_CODE_INST_STORE
5336 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5337 : popValue(Record, OpNum, NextValueNo,
5338 cast<PointerType>(Ptr->getType())->getElementType(),
5340 OpNum + 2 != Record.size())
5341 return error("Invalid record");
5343 if (std::error_code EC =
5344 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5347 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5349 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
5350 InstructionList.push_back(I);
5353 case bitc::FUNC_CODE_INST_STOREATOMIC:
5354 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5355 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
5358 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5359 !isa<PointerType>(Ptr->getType()) ||
5360 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5361 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5362 : popValue(Record, OpNum, NextValueNo,
5363 cast<PointerType>(Ptr->getType())->getElementType(),
5365 OpNum + 4 != Record.size())
5366 return error("Invalid record");
5368 if (std::error_code EC =
5369 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5371 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5372 if (Ordering == AtomicOrdering::NotAtomic ||
5373 Ordering == AtomicOrdering::Acquire ||
5374 Ordering == AtomicOrdering::AcquireRelease)
5375 return error("Invalid record");
5376 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5377 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5378 return error("Invalid record");
5381 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5383 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
5384 InstructionList.push_back(I);
5387 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
5388 case bitc::FUNC_CODE_INST_CMPXCHG: {
5389 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
5390 // failureordering?, isweak?]
5392 Value *Ptr, *Cmp, *New;
5393 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5394 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5395 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5396 : popValue(Record, OpNum, NextValueNo,
5397 cast<PointerType>(Ptr->getType())->getElementType(),
5399 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5400 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
5401 return error("Invalid record");
5402 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
5403 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5404 SuccessOrdering == AtomicOrdering::Unordered)
5405 return error("Invalid record");
5406 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
5408 if (std::error_code EC =
5409 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5411 AtomicOrdering FailureOrdering;
5412 if (Record.size() < 7)
5414 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5416 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
5418 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5420 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5422 if (Record.size() < 8) {
5423 // Before weak cmpxchgs existed, the instruction simply returned the
5424 // value loaded from memory, so bitcode files from that era will be
5425 // expecting the first component of a modern cmpxchg.
5426 CurBB->getInstList().push_back(I);
5427 I = ExtractValueInst::Create(I, 0);
5429 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5432 InstructionList.push_back(I);
5435 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5436 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5439 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5440 !isa<PointerType>(Ptr->getType()) ||
5441 popValue(Record, OpNum, NextValueNo,
5442 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5443 OpNum+4 != Record.size())
5444 return error("Invalid record");
5445 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5446 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5447 Operation > AtomicRMWInst::LAST_BINOP)
5448 return error("Invalid record");
5449 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5450 if (Ordering == AtomicOrdering::NotAtomic ||
5451 Ordering == AtomicOrdering::Unordered)
5452 return error("Invalid record");
5453 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5454 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5455 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5456 InstructionList.push_back(I);
5459 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5460 if (2 != Record.size())
5461 return error("Invalid record");
5462 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5463 if (Ordering == AtomicOrdering::NotAtomic ||
5464 Ordering == AtomicOrdering::Unordered ||
5465 Ordering == AtomicOrdering::Monotonic)
5466 return error("Invalid record");
5467 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5468 I = new FenceInst(Context, Ordering, SynchScope);
5469 InstructionList.push_back(I);
5472 case bitc::FUNC_CODE_INST_CALL: {
5473 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5474 if (Record.size() < 3)
5475 return error("Invalid record");
5478 AttributeSet PAL = getAttributes(Record[OpNum++]);
5479 unsigned CCInfo = Record[OpNum++];
5482 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5483 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5485 return error("Fast math flags indicator set for call with no FMF");
5488 FunctionType *FTy = nullptr;
5489 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5490 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5491 return error("Explicit call type is not a function type");
5494 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5495 return error("Invalid record");
5497 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5499 return error("Callee is not a pointer type");
5501 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5503 return error("Callee is not of pointer to function type");
5504 } else if (OpTy->getElementType() != FTy)
5505 return error("Explicit call type does not match pointee type of "
5507 if (Record.size() < FTy->getNumParams() + OpNum)
5508 return error("Insufficient operands to call");
5510 SmallVector<Value*, 16> Args;
5511 // Read the fixed params.
5512 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5513 if (FTy->getParamType(i)->isLabelTy())
5514 Args.push_back(getBasicBlock(Record[OpNum]));
5516 Args.push_back(getValue(Record, OpNum, NextValueNo,
5517 FTy->getParamType(i)));
5519 return error("Invalid record");
5522 // Read type/value pairs for varargs params.
5523 if (!FTy->isVarArg()) {
5524 if (OpNum != Record.size())
5525 return error("Invalid record");
5527 while (OpNum != Record.size()) {
5529 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5530 return error("Invalid record");
5535 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5536 OperandBundles.clear();
5537 InstructionList.push_back(I);
5538 cast<CallInst>(I)->setCallingConv(
5539 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5540 CallInst::TailCallKind TCK = CallInst::TCK_None;
5541 if (CCInfo & 1 << bitc::CALL_TAIL)
5542 TCK = CallInst::TCK_Tail;
5543 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5544 TCK = CallInst::TCK_MustTail;
5545 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5546 TCK = CallInst::TCK_NoTail;
5547 cast<CallInst>(I)->setTailCallKind(TCK);
5548 cast<CallInst>(I)->setAttributes(PAL);
5550 if (!isa<FPMathOperator>(I))
5551 return error("Fast-math-flags specified for call without "
5552 "floating-point scalar or vector return type");
5553 I->setFastMathFlags(FMF);
5557 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5558 if (Record.size() < 3)
5559 return error("Invalid record");
5560 Type *OpTy = getTypeByID(Record[0]);
5561 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5562 Type *ResTy = getTypeByID(Record[2]);
5563 if (!OpTy || !Op || !ResTy)
5564 return error("Invalid record");
5565 I = new VAArgInst(Op, ResTy);
5566 InstructionList.push_back(I);
5570 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5571 // A call or an invoke can be optionally prefixed with some variable
5572 // number of operand bundle blocks. These blocks are read into
5573 // OperandBundles and consumed at the next call or invoke instruction.
5575 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5576 return error("Invalid record");
5578 std::vector<Value *> Inputs;
5581 while (OpNum != Record.size()) {
5583 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5584 return error("Invalid record");
5585 Inputs.push_back(Op);
5588 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5593 // Add instruction to end of current BB. If there is no current BB, reject
5597 return error("Invalid instruction with no BB");
5599 if (!OperandBundles.empty()) {
5601 return error("Operand bundles found with no consumer");
5603 CurBB->getInstList().push_back(I);
5605 // If this was a terminator instruction, move to the next block.
5606 if (isa<TerminatorInst>(I)) {
5608 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5611 // Non-void values get registered in the value table for future use.
5612 if (I && !I->getType()->isVoidTy())
5613 ValueList.assignValue(I, NextValueNo++);
5618 if (!OperandBundles.empty())
5619 return error("Operand bundles found with no consumer");
5621 // Check the function list for unresolved values.
5622 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5623 if (!A->getParent()) {
5624 // We found at least one unresolved value. Nuke them all to avoid leaks.
5625 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5626 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5627 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5631 return error("Never resolved value found in function");
5635 // Unexpected unresolved metadata about to be dropped.
5636 if (MetadataList.hasFwdRefs())
5637 return error("Invalid function metadata: outgoing forward refs");
5639 // Trim the value list down to the size it was before we parsed this function.
5640 ValueList.shrinkTo(ModuleValueListSize);
5641 MetadataList.shrinkTo(ModuleMetadataListSize);
5642 std::vector<BasicBlock*>().swap(FunctionBBs);
5643 return std::error_code();
5646 /// Find the function body in the bitcode stream
5647 std::error_code BitcodeReader::findFunctionInStream(
5649 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5650 while (DeferredFunctionInfoIterator->second == 0) {
5651 // This is the fallback handling for the old format bitcode that
5652 // didn't contain the function index in the VST, or when we have
5653 // an anonymous function which would not have a VST entry.
5654 // Assert that we have one of those two cases.
5655 assert(VSTOffset == 0 || !F->hasName());
5656 // Parse the next body in the stream and set its position in the
5657 // DeferredFunctionInfo map.
5658 if (std::error_code EC = rememberAndSkipFunctionBodies())
5661 return std::error_code();
5664 //===----------------------------------------------------------------------===//
5665 // GVMaterializer implementation
5666 //===----------------------------------------------------------------------===//
5668 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5670 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5671 Function *F = dyn_cast<Function>(GV);
5672 // If it's not a function or is already material, ignore the request.
5673 if (!F || !F->isMaterializable())
5674 return std::error_code();
5676 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5677 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5678 // If its position is recorded as 0, its body is somewhere in the stream
5679 // but we haven't seen it yet.
5680 if (DFII->second == 0)
5681 if (std::error_code EC = findFunctionInStream(F, DFII))
5684 // Materialize metadata before parsing any function bodies.
5685 if (std::error_code EC = materializeMetadata())
5688 // Move the bit stream to the saved position of the deferred function body.
5689 Stream.JumpToBit(DFII->second);
5691 if (std::error_code EC = parseFunctionBody(F))
5693 F->setIsMaterializable(false);
5698 // Upgrade any old intrinsic calls in the function.
5699 for (auto &I : UpgradedIntrinsics) {
5700 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5704 if (CallInst *CI = dyn_cast<CallInst>(U))
5705 UpgradeIntrinsicCall(CI, I.second);
5709 // Update calls to the remangled intrinsics
5710 for (auto &I : RemangledIntrinsics)
5711 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5713 // Don't expect any other users than call sites
5714 CallSite(*UI++).setCalledFunction(I.second);
5716 // Finish fn->subprogram upgrade for materialized functions.
5717 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5718 F->setSubprogram(SP);
5720 // Bring in any functions that this function forward-referenced via
5722 return materializeForwardReferencedFunctions();
5725 std::error_code BitcodeReader::materializeModule() {
5726 if (std::error_code EC = materializeMetadata())
5729 // Promise to materialize all forward references.
5730 WillMaterializeAllForwardRefs = true;
5732 // Iterate over the module, deserializing any functions that are still on
5734 for (Function &F : *TheModule) {
5735 if (std::error_code EC = materialize(&F))
5738 // At this point, if there are any function bodies, parse the rest of
5739 // the bits in the module past the last function block we have recorded
5740 // through either lazy scanning or the VST.
5741 if (LastFunctionBlockBit || NextUnreadBit)
5742 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5745 // Check that all block address forward references got resolved (as we
5747 if (!BasicBlockFwdRefs.empty())
5748 return error("Never resolved function from blockaddress");
5750 // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5751 // to prevent this instructions with TBAA tags should be upgraded first.
5752 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5753 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5755 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5756 // delete the old functions to clean up. We can't do this unless the entire
5757 // module is materialized because there could always be another function body
5758 // with calls to the old function.
5759 for (auto &I : UpgradedIntrinsics) {
5760 for (auto *U : I.first->users()) {
5761 if (CallInst *CI = dyn_cast<CallInst>(U))
5762 UpgradeIntrinsicCall(CI, I.second);
5764 if (!I.first->use_empty())
5765 I.first->replaceAllUsesWith(I.second);
5766 I.first->eraseFromParent();
5768 UpgradedIntrinsics.clear();
5769 // Do the same for remangled intrinsics
5770 for (auto &I : RemangledIntrinsics) {
5771 I.first->replaceAllUsesWith(I.second);
5772 I.first->eraseFromParent();
5774 RemangledIntrinsics.clear();
5776 UpgradeDebugInfo(*TheModule);
5778 UpgradeModuleFlags(*TheModule);
5779 return std::error_code();
5782 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5783 return IdentifiedStructTypes;
5787 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5789 return initLazyStream(std::move(Streamer));
5790 return initStreamFromBuffer();
5793 std::error_code BitcodeReader::initStreamFromBuffer() {
5794 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5795 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5797 if (Buffer->getBufferSize() & 3)
5798 return error("Invalid bitcode signature");
5800 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5801 // The magic number is 0x0B17C0DE stored in little endian.
5802 if (isBitcodeWrapper(BufPtr, BufEnd))
5803 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5804 return error("Invalid bitcode wrapper header");
5806 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5807 Stream.init(&*StreamFile);
5809 return std::error_code();
5813 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5814 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5817 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5818 StreamingMemoryObject &Bytes = *OwnedBytes;
5819 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5820 Stream.init(&*StreamFile);
5822 unsigned char buf[16];
5823 if (Bytes.readBytes(buf, 16, 0) != 16)
5824 return error("Invalid bitcode signature");
5826 if (!isBitcode(buf, buf + 16))
5827 return error("Invalid bitcode signature");
5829 if (isBitcodeWrapper(buf, buf + 4)) {
5830 const unsigned char *bitcodeStart = buf;
5831 const unsigned char *bitcodeEnd = buf + 16;
5832 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5833 Bytes.dropLeadingBytes(bitcodeStart - buf);
5834 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5836 return std::error_code();
5839 std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
5840 return ::error(DiagnosticHandler,
5841 make_error_code(BitcodeError::CorruptedBitcode), Message);
5844 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5845 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5846 bool CheckGlobalValSummaryPresenceOnly)
5847 : DiagnosticHandler(std::move(DiagnosticHandler)), Buffer(Buffer),
5848 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
5850 void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
5852 void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5854 std::pair<GlobalValue::GUID, GlobalValue::GUID>
5855 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
5856 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5857 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5861 // Specialized value symbol table parser used when reading module index
5862 // blocks where we don't actually create global values. The parsed information
5863 // is saved in the bitcode reader for use when later parsing summaries.
5864 std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5866 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5867 assert(Offset > 0 && "Expected non-zero VST offset");
5868 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5870 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5871 return error("Invalid record");
5873 SmallVector<uint64_t, 64> Record;
5875 // Read all the records for this value table.
5876 SmallString<128> ValueName;
5878 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5880 switch (Entry.Kind) {
5881 case BitstreamEntry::SubBlock: // Handled for us already.
5882 case BitstreamEntry::Error:
5883 return error("Malformed block");
5884 case BitstreamEntry::EndBlock:
5885 // Done parsing VST, jump back to wherever we came from.
5886 Stream.JumpToBit(CurrentBit);
5887 return std::error_code();
5888 case BitstreamEntry::Record:
5889 // The interesting case.
5895 switch (Stream.readRecord(Entry.ID, Record)) {
5896 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5898 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5899 if (convertToString(Record, 1, ValueName))
5900 return error("Invalid record");
5901 unsigned ValueID = Record[0];
5902 assert(!SourceFileName.empty());
5903 auto VLI = ValueIdToLinkageMap.find(ValueID);
5904 assert(VLI != ValueIdToLinkageMap.end() &&
5905 "No linkage found for VST entry?");
5906 auto Linkage = VLI->second;
5907 std::string GlobalId =
5908 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
5909 auto ValueGUID = GlobalValue::getGUID(GlobalId);
5910 auto OriginalNameID = ValueGUID;
5911 if (GlobalValue::isLocalLinkage(Linkage))
5912 OriginalNameID = GlobalValue::getGUID(ValueName);
5913 if (PrintSummaryGUIDs)
5914 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5915 << ValueName << "\n";
5916 ValueIdToCallGraphGUIDMap[ValueID] =
5917 std::make_pair(ValueGUID, OriginalNameID);
5921 case bitc::VST_CODE_FNENTRY: {
5922 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5923 if (convertToString(Record, 2, ValueName))
5924 return error("Invalid record");
5925 unsigned ValueID = Record[0];
5926 assert(!SourceFileName.empty());
5927 auto VLI = ValueIdToLinkageMap.find(ValueID);
5928 assert(VLI != ValueIdToLinkageMap.end() &&
5929 "No linkage found for VST entry?");
5930 auto Linkage = VLI->second;
5931 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
5932 ValueName, VLI->second, SourceFileName);
5933 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
5934 auto OriginalNameID = FunctionGUID;
5935 if (GlobalValue::isLocalLinkage(Linkage))
5936 OriginalNameID = GlobalValue::getGUID(ValueName);
5937 if (PrintSummaryGUIDs)
5938 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
5939 << ValueName << "\n";
5940 ValueIdToCallGraphGUIDMap[ValueID] =
5941 std::make_pair(FunctionGUID, OriginalNameID);
5946 case bitc::VST_CODE_COMBINED_ENTRY: {
5947 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5948 unsigned ValueID = Record[0];
5949 GlobalValue::GUID RefGUID = Record[1];
5950 // The "original name", which is the second value of the pair will be
5951 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5952 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
5959 // Parse just the blocks needed for building the index out of the module.
5960 // At the end of this routine the module Index is populated with a map
5961 // from global value id to GlobalValueSummary objects.
5962 std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
5963 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5964 return error("Invalid record");
5966 SmallVector<uint64_t, 64> Record;
5967 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5968 unsigned ValueId = 0;
5970 // Read the index for this module.
5972 BitstreamEntry Entry = Stream.advance();
5974 switch (Entry.Kind) {
5975 case BitstreamEntry::Error:
5976 return error("Malformed block");
5977 case BitstreamEntry::EndBlock:
5978 return std::error_code();
5980 case BitstreamEntry::SubBlock:
5981 if (CheckGlobalValSummaryPresenceOnly) {
5982 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5983 SeenGlobalValSummary = true;
5984 // No need to parse the rest since we found the summary.
5985 return std::error_code();
5987 if (Stream.SkipBlock())
5988 return error("Invalid record");
5992 default: // Skip unknown content.
5993 if (Stream.SkipBlock())
5994 return error("Invalid record");
5996 case bitc::BLOCKINFO_BLOCK_ID:
5997 // Need to parse these to get abbrev ids (e.g. for VST)
5998 if (Stream.ReadBlockInfoBlock())
5999 return error("Malformed block");
6001 case bitc::VALUE_SYMTAB_BLOCK_ID:
6002 // Should have been parsed earlier via VSTOffset, unless there
6003 // is no summary section.
6004 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
6005 !SeenGlobalValSummary) &&
6006 "Expected early VST parse via VSTOffset record");
6007 if (Stream.SkipBlock())
6008 return error("Invalid record");
6010 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
6011 assert(VSTOffset > 0 && "Expected non-zero VST offset");
6012 assert(!SeenValueSymbolTable &&
6013 "Already read VST when parsing summary block?");
6014 if (std::error_code EC =
6015 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
6017 SeenValueSymbolTable = true;
6018 SeenGlobalValSummary = true;
6019 if (std::error_code EC = parseEntireSummary())
6022 case bitc::MODULE_STRTAB_BLOCK_ID:
6023 if (std::error_code EC = parseModuleStringTable())
6029 case BitstreamEntry::Record: {
6031 auto BitCode = Stream.readRecord(Entry.ID, Record);
6034 break; // Default behavior, ignore unknown content.
6035 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
6036 case bitc::MODULE_CODE_SOURCE_FILENAME: {
6037 SmallString<128> ValueName;
6038 if (convertToString(Record, 0, ValueName))
6039 return error("Invalid record");
6040 SourceFileName = ValueName.c_str();
6043 /// MODULE_CODE_HASH: [5*i32]
6044 case bitc::MODULE_CODE_HASH: {
6045 if (Record.size() != 5)
6046 return error("Invalid hash length " + Twine(Record.size()).str());
6049 if (TheIndex->modulePaths().empty())
6050 // Does not have any summary emitted.
6052 if (TheIndex->modulePaths().size() != 1)
6053 return error("Don't expect multiple modules defined?");
6054 auto &Hash = TheIndex->modulePaths().begin()->second.second;
6056 for (auto &Val : Record) {
6057 assert(!(Val >> 32) && "Unexpected high bits set");
6062 /// MODULE_CODE_VSTOFFSET: [offset]
6063 case bitc::MODULE_CODE_VSTOFFSET:
6064 if (Record.size() < 1)
6065 return error("Invalid record");
6066 VSTOffset = Record[0];
6068 // GLOBALVAR: [pointer type, isconst, initid,
6069 // linkage, alignment, section, visibility, threadlocal,
6070 // unnamed_addr, externally_initialized, dllstorageclass,
6072 case bitc::MODULE_CODE_GLOBALVAR: {
6073 if (Record.size() < 6)
6074 return error("Invalid record");
6075 uint64_t RawLinkage = Record[3];
6076 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6077 ValueIdToLinkageMap[ValueId++] = Linkage;
6080 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
6081 // alignment, section, visibility, gc, unnamed_addr,
6082 // prologuedata, dllstorageclass, comdat, prefixdata]
6083 case bitc::MODULE_CODE_FUNCTION: {
6084 if (Record.size() < 8)
6085 return error("Invalid record");
6086 uint64_t RawLinkage = Record[3];
6087 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6088 ValueIdToLinkageMap[ValueId++] = Linkage;
6091 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
6093 case bitc::MODULE_CODE_ALIAS: {
6094 if (Record.size() < 6)
6095 return error("Invalid record");
6096 uint64_t RawLinkage = Record[3];
6097 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6098 ValueIdToLinkageMap[ValueId++] = Linkage;
6108 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6109 // objects in the index.
6110 std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
6111 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
6112 return error("Invalid record");
6113 SmallVector<uint64_t, 64> Record;
6117 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6118 if (Entry.Kind != BitstreamEntry::Record)
6119 return error("Invalid Summary Block: record for version expected");
6120 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
6121 return error("Invalid Summary Block: version expected");
6123 const uint64_t Version = Record[0];
6125 return error("Invalid summary version " + Twine(Version) + ", 1 expected");
6128 // Keep around the last seen summary to be used when we see an optional
6129 // "OriginalName" attachement.
6130 GlobalValueSummary *LastSeenSummary = nullptr;
6131 bool Combined = false;
6133 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6135 switch (Entry.Kind) {
6136 case BitstreamEntry::SubBlock: // Handled for us already.
6137 case BitstreamEntry::Error:
6138 return error("Malformed block");
6139 case BitstreamEntry::EndBlock:
6140 // For a per-module index, remove any entries that still have empty
6141 // summaries. The VST parsing creates entries eagerly for all symbols,
6142 // but not all have associated summaries (e.g. it doesn't know how to
6143 // distinguish between VST_CODE_ENTRY for function declarations vs global
6144 // variables with initializers that end up with a summary). Remove those
6145 // entries now so that we don't need to rely on the combined index merger
6146 // to clean them up (especially since that may not run for the first
6147 // module's index if we merge into that).
6149 TheIndex->removeEmptySummaryEntries();
6150 return std::error_code();
6151 case BitstreamEntry::Record:
6152 // The interesting case.
6156 // Read a record. The record format depends on whether this
6157 // is a per-module index or a combined index file. In the per-module
6158 // case the records contain the associated value's ID for correlation
6159 // with VST entries. In the combined index the correlation is done
6160 // via the bitcode offset of the summary records (which were saved
6161 // in the combined index VST entries). The records also contain
6162 // information used for ThinLTO renaming and importing.
6164 auto BitCode = Stream.readRecord(Entry.ID, Record);
6166 default: // Default behavior: ignore.
6168 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
6169 // n x (valueid, callsitecount)]
6170 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
6171 // numrefs x valueid,
6172 // n x (valueid, callsitecount, profilecount)]
6173 case bitc::FS_PERMODULE:
6174 case bitc::FS_PERMODULE_PROFILE: {
6175 unsigned ValueID = Record[0];
6176 uint64_t RawFlags = Record[1];
6177 unsigned InstCount = Record[2];
6178 unsigned NumRefs = Record[3];
6179 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6180 std::unique_ptr<FunctionSummary> FS =
6181 llvm::make_unique<FunctionSummary>(Flags, InstCount);
6182 // The module path string ref set in the summary must be owned by the
6183 // index's module string table. Since we don't have a module path
6184 // string table section in the per-module index, we create a single
6185 // module path string table entry with an empty (0) ID to take
6188 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6189 static int RefListStartIndex = 4;
6190 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6191 assert(Record.size() >= RefListStartIndex + NumRefs &&
6192 "Record size inconsistent with number of references");
6193 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
6194 unsigned RefValueId = Record[I];
6195 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6196 FS->addRefEdge(RefGUID);
6198 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6199 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6201 unsigned CalleeValueId = Record[I];
6202 unsigned CallsiteCount = Record[++I];
6203 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
6204 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
6205 FS->addCallGraphEdge(CalleeGUID,
6206 CalleeInfo(CallsiteCount, ProfileCount));
6208 auto GUID = getGUIDFromValueId(ValueID);
6209 FS->setOriginalName(GUID.second);
6210 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
6213 // FS_ALIAS: [valueid, flags, valueid]
6214 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6215 // they expect all aliasee summaries to be available.
6216 case bitc::FS_ALIAS: {
6217 unsigned ValueID = Record[0];
6218 uint64_t RawFlags = Record[1];
6219 unsigned AliaseeID = Record[2];
6220 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6221 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
6222 // The module path string ref set in the summary must be owned by the
6223 // index's module string table. Since we don't have a module path
6224 // string table section in the per-module index, we create a single
6225 // module path string table entry with an empty (0) ID to take
6228 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6230 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
6231 auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID);
6232 if (!AliaseeSummary)
6233 return error("Alias expects aliasee summary to be parsed");
6234 AS->setAliasee(AliaseeSummary);
6236 auto GUID = getGUIDFromValueId(ValueID);
6237 AS->setOriginalName(GUID.second);
6238 TheIndex->addGlobalValueSummary(GUID.first, std::move(AS));
6241 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
6242 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6243 unsigned ValueID = Record[0];
6244 uint64_t RawFlags = Record[1];
6245 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6246 std::unique_ptr<GlobalVarSummary> FS =
6247 llvm::make_unique<GlobalVarSummary>(Flags);
6249 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6250 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
6251 unsigned RefValueId = Record[I];
6252 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6253 FS->addRefEdge(RefGUID);
6255 auto GUID = getGUIDFromValueId(ValueID);
6256 FS->setOriginalName(GUID.second);
6257 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
6260 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
6261 // numrefs x valueid, n x (valueid, callsitecount)]
6262 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
6263 // numrefs x valueid,
6264 // n x (valueid, callsitecount, profilecount)]
6265 case bitc::FS_COMBINED:
6266 case bitc::FS_COMBINED_PROFILE: {
6267 unsigned ValueID = Record[0];
6268 uint64_t ModuleId = Record[1];
6269 uint64_t RawFlags = Record[2];
6270 unsigned InstCount = Record[3];
6271 unsigned NumRefs = Record[4];
6272 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6273 std::unique_ptr<FunctionSummary> FS =
6274 llvm::make_unique<FunctionSummary>(Flags, InstCount);
6275 LastSeenSummary = FS.get();
6276 FS->setModulePath(ModuleIdMap[ModuleId]);
6277 static int RefListStartIndex = 5;
6278 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6279 assert(Record.size() >= RefListStartIndex + NumRefs &&
6280 "Record size inconsistent with number of references");
6281 for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E;
6283 unsigned RefValueId = Record[I];
6284 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6285 FS->addRefEdge(RefGUID);
6287 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6288 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6290 unsigned CalleeValueId = Record[I];
6291 unsigned CallsiteCount = Record[++I];
6292 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
6293 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
6294 FS->addCallGraphEdge(CalleeGUID,
6295 CalleeInfo(CallsiteCount, ProfileCount));
6297 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
6298 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
6302 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6303 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6304 // they expect all aliasee summaries to be available.
6305 case bitc::FS_COMBINED_ALIAS: {
6306 unsigned ValueID = Record[0];
6307 uint64_t ModuleId = Record[1];
6308 uint64_t RawFlags = Record[2];
6309 unsigned AliaseeValueId = Record[3];
6310 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6311 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
6312 LastSeenSummary = AS.get();
6313 AS->setModulePath(ModuleIdMap[ModuleId]);
6315 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
6316 auto AliaseeInModule =
6317 TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath());
6318 if (!AliaseeInModule)
6319 return error("Alias expects aliasee summary to be parsed");
6320 AS->setAliasee(AliaseeInModule);
6322 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
6323 TheIndex->addGlobalValueSummary(GUID, std::move(AS));
6327 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6328 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6329 unsigned ValueID = Record[0];
6330 uint64_t ModuleId = Record[1];
6331 uint64_t RawFlags = Record[2];
6332 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6333 std::unique_ptr<GlobalVarSummary> FS =
6334 llvm::make_unique<GlobalVarSummary>(Flags);
6335 LastSeenSummary = FS.get();
6336 FS->setModulePath(ModuleIdMap[ModuleId]);
6337 for (unsigned I = 3, E = Record.size(); I != E; ++I) {
6338 unsigned RefValueId = Record[I];
6339 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6340 FS->addRefEdge(RefGUID);
6342 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
6343 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
6347 // FS_COMBINED_ORIGINAL_NAME: [original_name]
6348 case bitc::FS_COMBINED_ORIGINAL_NAME: {
6349 uint64_t OriginalName = Record[0];
6350 if (!LastSeenSummary)
6351 return error("Name attachment that does not follow a combined record");
6352 LastSeenSummary->setOriginalName(OriginalName);
6353 // Reset the LastSeenSummary
6354 LastSeenSummary = nullptr;
6358 llvm_unreachable("Exit infinite loop");
6361 // Parse the module string table block into the Index.
6362 // This populates the ModulePathStringTable map in the index.
6363 std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6364 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6365 return error("Invalid record");
6367 SmallVector<uint64_t, 64> Record;
6369 SmallString<128> ModulePath;
6370 ModulePathStringTableTy::iterator LastSeenModulePath;
6372 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6374 switch (Entry.Kind) {
6375 case BitstreamEntry::SubBlock: // Handled for us already.
6376 case BitstreamEntry::Error:
6377 return error("Malformed block");
6378 case BitstreamEntry::EndBlock:
6379 return std::error_code();
6380 case BitstreamEntry::Record:
6381 // The interesting case.
6386 switch (Stream.readRecord(Entry.ID, Record)) {
6387 default: // Default behavior: ignore.
6389 case bitc::MST_CODE_ENTRY: {
6390 // MST_ENTRY: [modid, namechar x N]
6391 uint64_t ModuleId = Record[0];
6393 if (convertToString(Record, 1, ModulePath))
6394 return error("Invalid record");
6396 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
6397 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
6402 /// MST_CODE_HASH: [5*i32]
6403 case bitc::MST_CODE_HASH: {
6404 if (Record.size() != 5)
6405 return error("Invalid hash length " + Twine(Record.size()).str());
6406 if (LastSeenModulePath == TheIndex->modulePaths().end())
6407 return error("Invalid hash that does not follow a module path");
6409 for (auto &Val : Record) {
6410 assert(!(Val >> 32) && "Unexpected high bits set");
6411 LastSeenModulePath->second.second[Pos++] = Val;
6413 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
6414 LastSeenModulePath = TheIndex->modulePaths().end();
6419 llvm_unreachable("Exit infinite loop");
6422 // Parse the function info index from the bitcode streamer into the given index.
6423 std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
6424 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
6427 if (std::error_code EC = initStream(std::move(Streamer)))
6430 // Sniff for the signature.
6431 if (!hasValidBitcodeHeader(Stream))
6432 return error("Invalid bitcode signature");
6434 // We expect a number of well-defined blocks, though we don't necessarily
6435 // need to understand them all.
6437 if (Stream.AtEndOfStream()) {
6438 // We didn't really read a proper Module block.
6439 return error("Malformed block");
6442 BitstreamEntry Entry =
6443 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6445 if (Entry.Kind != BitstreamEntry::SubBlock)
6446 return error("Malformed block");
6448 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6449 // building the function summary index.
6450 if (Entry.ID == bitc::MODULE_BLOCK_ID)
6451 return parseModule();
6453 if (Stream.SkipBlock())
6454 return error("Invalid record");
6458 std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6459 std::unique_ptr<DataStreamer> Streamer) {
6461 return initLazyStream(std::move(Streamer));
6462 return initStreamFromBuffer();
6465 std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
6466 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6467 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6469 if (Buffer->getBufferSize() & 3)
6470 return error("Invalid bitcode signature");
6472 // If we have a wrapper header, parse it and ignore the non-bc file contents.
6473 // The magic number is 0x0B17C0DE stored in little endian.
6474 if (isBitcodeWrapper(BufPtr, BufEnd))
6475 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6476 return error("Invalid bitcode wrapper header");
6478 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6479 Stream.init(&*StreamFile);
6481 return std::error_code();
6484 std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
6485 std::unique_ptr<DataStreamer> Streamer) {
6486 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6489 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6490 StreamingMemoryObject &Bytes = *OwnedBytes;
6491 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6492 Stream.init(&*StreamFile);
6494 unsigned char buf[16];
6495 if (Bytes.readBytes(buf, 16, 0) != 16)
6496 return error("Invalid bitcode signature");
6498 if (!isBitcode(buf, buf + 16))
6499 return error("Invalid bitcode signature");
6501 if (isBitcodeWrapper(buf, buf + 4)) {
6502 const unsigned char *bitcodeStart = buf;
6503 const unsigned char *bitcodeEnd = buf + 16;
6504 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6505 Bytes.dropLeadingBytes(bitcodeStart - buf);
6506 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6508 return std::error_code();
6512 // FIXME: This class is only here to support the transition to llvm::Error. It
6513 // will be removed once this transition is complete. Clients should prefer to
6514 // deal with the Error value directly, rather than converting to error_code.
6515 class BitcodeErrorCategoryType : public std::error_category {
6516 const char *name() const LLVM_NOEXCEPT override {
6517 return "llvm.bitcode";
6519 std::string message(int IE) const override {
6520 BitcodeError E = static_cast<BitcodeError>(IE);
6522 case BitcodeError::InvalidBitcodeSignature:
6523 return "Invalid bitcode signature";
6524 case BitcodeError::CorruptedBitcode:
6525 return "Corrupted bitcode";
6527 llvm_unreachable("Unknown error type!");
6530 } // end anonymous namespace
6532 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6534 const std::error_category &llvm::BitcodeErrorCategory() {
6535 return *ErrorCategory;
6538 //===----------------------------------------------------------------------===//
6539 // External interface
6540 //===----------------------------------------------------------------------===//
6542 static ErrorOr<std::unique_ptr<Module>>
6543 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6544 BitcodeReader *R, LLVMContext &Context,
6545 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6546 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6547 M->setMaterializer(R);
6549 auto cleanupOnError = [&](std::error_code EC) {
6550 R->releaseBuffer(); // Never take ownership on error.
6554 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6555 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6556 ShouldLazyLoadMetadata))
6557 return cleanupOnError(EC);
6559 if (MaterializeAll) {
6560 // Read in the entire module, and destroy the BitcodeReader.
6561 if (std::error_code EC = M->materializeAll())
6562 return cleanupOnError(EC);
6564 // Resolve forward references from blockaddresses.
6565 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6566 return cleanupOnError(EC);
6568 return std::move(M);
6571 /// \brief Get a lazy one-at-time loading module from bitcode.
6573 /// This isn't always used in a lazy context. In particular, it's also used by
6574 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6575 /// in forward-referenced functions from block address references.
6577 /// \param[in] MaterializeAll Set to \c true if we should materialize
6579 static ErrorOr<std::unique_ptr<Module>>
6580 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
6581 LLVMContext &Context, bool MaterializeAll,
6582 bool ShouldLazyLoadMetadata = false) {
6583 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
6585 ErrorOr<std::unique_ptr<Module>> Ret =
6586 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6587 MaterializeAll, ShouldLazyLoadMetadata);
6591 Buffer.release(); // The BitcodeReader owns it now.
6595 ErrorOr<std::unique_ptr<Module>>
6596 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6597 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
6598 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
6599 ShouldLazyLoadMetadata);
6602 ErrorOr<std::unique_ptr<Module>>
6603 llvm::getStreamedBitcodeModule(StringRef Name,
6604 std::unique_ptr<DataStreamer> Streamer,
6605 LLVMContext &Context) {
6606 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6607 BitcodeReader *R = new BitcodeReader(Context);
6609 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6613 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6614 LLVMContext &Context) {
6615 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6616 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
6617 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6618 // written. We must defer until the Module has been fully materialized.
6621 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6622 LLVMContext &Context) {
6623 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6624 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
6625 ErrorOr<std::string> Triple = R->parseTriple();
6626 if (Triple.getError())
6628 return Triple.get();
6631 bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer,
6632 LLVMContext &Context) {
6633 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6634 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
6635 ErrorOr<bool> hasObjCCategory = R->hasObjCCategory();
6636 if (hasObjCCategory.getError())
6638 return hasObjCCategory.get();
6641 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6642 LLVMContext &Context) {
6643 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6644 BitcodeReader R(Buf.release(), Context);
6645 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6646 if (ProducerString.getError())
6648 return ProducerString.get();
6651 // Parse the specified bitcode buffer, returning the function info index.
6652 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex(
6653 MemoryBufferRef Buffer,
6654 const DiagnosticHandlerFunction &DiagnosticHandler) {
6655 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6656 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
6658 auto Index = llvm::make_unique<ModuleSummaryIndex>();
6660 auto cleanupOnError = [&](std::error_code EC) {
6661 R.releaseBuffer(); // Never take ownership on error.
6665 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6666 return cleanupOnError(EC);
6668 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
6669 return std::move(Index);
6672 // Check if the given bitcode buffer contains a global value summary block.
6673 bool llvm::hasGlobalValueSummary(
6674 MemoryBufferRef Buffer,
6675 const DiagnosticHandlerFunction &DiagnosticHandler) {
6676 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6677 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, true);
6679 auto cleanupOnError = [&](std::error_code EC) {
6680 R.releaseBuffer(); // Never take ownership on error.
6684 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6685 return cleanupOnError(EC);
6687 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
6688 return R.foundGlobalValSummary();