1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/FunctionInfo.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/DataStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
42 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
45 /// Indicates which operator an operand allows (for the few operands that may
46 /// only reference a certain operator).
47 enum OperatorConstraint {
48 OC_None = 0, // No constraint
49 OC_CatchPad, // Must be CatchPadInst
50 OC_CleanupPad // Must be CleanupPadInst
53 class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
56 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
59 /// ResolveConstantForwardRefs for more information about this.
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
75 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
78 assert(ResolveConstants.empty() && "Constants not resolved?");
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
87 Value *back() const { return ValuePtrs.back(); }
88 void pop_back() { ValuePtrs.pop_back(); }
89 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
96 Value *getValueFwdRef(unsigned Idx, Type *Ty,
97 OperatorConstraint OC = OC_None);
99 bool assignValue(Value *V, unsigned Idx);
101 /// Once all constants are read, this method bulk resolves any forward
103 void resolveConstantForwardRefs();
106 class BitcodeReaderMDValueList {
111 std::vector<TrackingMDRef> MDValuePtrs;
113 LLVMContext &Context;
115 BitcodeReaderMDValueList(LLVMContext &C)
116 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
118 // vector compatibility methods
119 unsigned size() const { return MDValuePtrs.size(); }
120 void resize(unsigned N) { MDValuePtrs.resize(N); }
121 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
122 void clear() { MDValuePtrs.clear(); }
123 Metadata *back() const { return MDValuePtrs.back(); }
124 void pop_back() { MDValuePtrs.pop_back(); }
125 bool empty() const { return MDValuePtrs.empty(); }
127 Metadata *operator[](unsigned i) const {
128 assert(i < MDValuePtrs.size());
129 return MDValuePtrs[i];
132 void shrinkTo(unsigned N) {
133 assert(N <= size() && "Invalid shrinkTo request!");
134 MDValuePtrs.resize(N);
137 Metadata *getValueFwdRef(unsigned Idx);
138 void assignValue(Metadata *MD, unsigned Idx);
139 void tryToResolveCycles();
142 class BitcodeReader : public GVMaterializer {
143 LLVMContext &Context;
144 DiagnosticHandlerFunction DiagnosticHandler;
145 Module *TheModule = nullptr;
146 std::unique_ptr<MemoryBuffer> Buffer;
147 std::unique_ptr<BitstreamReader> StreamFile;
148 BitstreamCursor Stream;
149 uint64_t NextUnreadBit = 0;
150 bool SeenValueSymbolTable = false;
151 unsigned VSTOffset = 0;
153 std::vector<Type*> TypeList;
154 BitcodeReaderValueList ValueList;
155 BitcodeReaderMDValueList MDValueList;
156 std::vector<Comdat *> ComdatList;
157 SmallVector<Instruction *, 64> InstructionList;
159 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
160 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
161 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
162 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
163 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
165 SmallVector<Instruction*, 64> InstsWithTBAATag;
167 /// The set of attributes by index. Index zero in the file is for null, and
168 /// is thus not represented here. As such all indices are off by one.
169 std::vector<AttributeSet> MAttributes;
171 /// The set of attribute groups.
172 std::map<unsigned, AttributeSet> MAttributeGroups;
174 /// While parsing a function body, this is a list of the basic blocks for the
176 std::vector<BasicBlock*> FunctionBBs;
178 // When reading the module header, this list is populated with functions that
179 // have bodies later in the file.
180 std::vector<Function*> FunctionsWithBodies;
182 // When intrinsic functions are encountered which require upgrading they are
183 // stored here with their replacement function.
184 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
185 UpgradedIntrinsicMap UpgradedIntrinsics;
187 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
188 DenseMap<unsigned, unsigned> MDKindMap;
190 // Several operations happen after the module header has been read, but
191 // before function bodies are processed. This keeps track of whether
192 // we've done this yet.
193 bool SeenFirstFunctionBody = false;
195 /// When function bodies are initially scanned, this map contains info about
196 /// where to find deferred function body in the stream.
197 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
199 /// When Metadata block is initially scanned when parsing the module, we may
200 /// choose to defer parsing of the metadata. This vector contains info about
201 /// which Metadata blocks are deferred.
202 std::vector<uint64_t> DeferredMetadataInfo;
204 /// These are basic blocks forward-referenced by block addresses. They are
205 /// inserted lazily into functions when they're loaded. The basic block ID is
206 /// its index into the vector.
207 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
208 std::deque<Function *> BasicBlockFwdRefQueue;
210 /// Indicates that we are using a new encoding for instruction operands where
211 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
212 /// instruction number, for a more compact encoding. Some instruction
213 /// operands are not relative to the instruction ID: basic block numbers, and
214 /// types. Once the old style function blocks have been phased out, we would
215 /// not need this flag.
216 bool UseRelativeIDs = false;
218 /// True if all functions will be materialized, negating the need to process
219 /// (e.g.) blockaddress forward references.
220 bool WillMaterializeAllForwardRefs = false;
222 /// Functions that have block addresses taken. This is usually empty.
223 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
225 /// True if any Metadata block has been materialized.
226 bool IsMetadataMaterialized = false;
228 bool StripDebugInfo = false;
230 std::vector<std::string> BundleTags;
233 std::error_code error(BitcodeError E, const Twine &Message);
234 std::error_code error(BitcodeError E);
235 std::error_code error(const Twine &Message);
237 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
238 DiagnosticHandlerFunction DiagnosticHandler);
239 BitcodeReader(LLVMContext &Context,
240 DiagnosticHandlerFunction DiagnosticHandler);
241 ~BitcodeReader() override { freeState(); }
243 std::error_code materializeForwardReferencedFunctions();
247 void releaseBuffer();
249 bool isDematerializable(const GlobalValue *GV) const override;
250 std::error_code materialize(GlobalValue *GV) override;
251 std::error_code materializeModule(Module *M) override;
252 std::vector<StructType *> getIdentifiedStructTypes() const override;
253 void dematerialize(GlobalValue *GV) override;
255 /// \brief Main interface to parsing a bitcode buffer.
256 /// \returns true if an error occurred.
257 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
259 bool ShouldLazyLoadMetadata = false);
261 /// \brief Cheap mechanism to just extract module triple
262 /// \returns true if an error occurred.
263 ErrorOr<std::string> parseTriple();
265 static uint64_t decodeSignRotatedValue(uint64_t V);
267 /// Materialize any deferred Metadata block.
268 std::error_code materializeMetadata() override;
270 void setStripDebugInfo() override;
273 std::vector<StructType *> IdentifiedStructTypes;
274 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
275 StructType *createIdentifiedStructType(LLVMContext &Context);
277 Type *getTypeByID(unsigned ID);
278 Value *getFnValueByID(unsigned ID, Type *Ty,
279 OperatorConstraint OC = OC_None) {
280 if (Ty && Ty->isMetadataTy())
281 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
282 return ValueList.getValueFwdRef(ID, Ty, OC);
284 Metadata *getFnMetadataByID(unsigned ID) {
285 return MDValueList.getValueFwdRef(ID);
287 BasicBlock *getBasicBlock(unsigned ID) const {
288 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
289 return FunctionBBs[ID];
291 AttributeSet getAttributes(unsigned i) const {
292 if (i-1 < MAttributes.size())
293 return MAttributes[i-1];
294 return AttributeSet();
297 /// Read a value/type pair out of the specified record from slot 'Slot'.
298 /// Increment Slot past the number of slots used in the record. Return true on
300 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
301 unsigned InstNum, Value *&ResVal) {
302 if (Slot == Record.size()) return true;
303 unsigned ValNo = (unsigned)Record[Slot++];
304 // Adjust the ValNo, if it was encoded relative to the InstNum.
306 ValNo = InstNum - ValNo;
307 if (ValNo < InstNum) {
308 // If this is not a forward reference, just return the value we already
310 ResVal = getFnValueByID(ValNo, nullptr);
311 return ResVal == nullptr;
313 if (Slot == Record.size())
316 unsigned TypeNo = (unsigned)Record[Slot++];
317 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
318 return ResVal == nullptr;
321 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
322 /// past the number of slots used by the value in the record. Return true if
323 /// there is an error.
324 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
325 unsigned InstNum, Type *Ty, Value *&ResVal,
326 OperatorConstraint OC = OC_None) {
327 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
329 // All values currently take a single record slot.
334 /// Like popValue, but does not increment the Slot number.
335 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
336 unsigned InstNum, Type *Ty, Value *&ResVal,
337 OperatorConstraint OC = OC_None) {
338 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
339 return ResVal == nullptr;
342 /// Version of getValue that returns ResVal directly, or 0 if there is an
344 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
345 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
346 if (Slot == Record.size()) return nullptr;
347 unsigned ValNo = (unsigned)Record[Slot];
348 // Adjust the ValNo, if it was encoded relative to the InstNum.
350 ValNo = InstNum - ValNo;
351 return getFnValueByID(ValNo, Ty, OC);
354 /// Like getValue, but decodes signed VBRs.
355 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
356 unsigned InstNum, Type *Ty,
357 OperatorConstraint OC = OC_None) {
358 if (Slot == Record.size()) return nullptr;
359 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
360 // Adjust the ValNo, if it was encoded relative to the InstNum.
362 ValNo = InstNum - ValNo;
363 return getFnValueByID(ValNo, Ty, OC);
366 /// Converts alignment exponent (i.e. power of two (or zero)) to the
367 /// corresponding alignment to use. If alignment is too large, returns
368 /// a corresponding error code.
369 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
370 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
371 std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
372 std::error_code parseAttributeBlock();
373 std::error_code parseAttributeGroupBlock();
374 std::error_code parseTypeTable();
375 std::error_code parseTypeTableBody();
376 std::error_code parseOperandBundleTags();
378 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
379 unsigned NameIndex, Triple &TT);
380 std::error_code parseValueSymbolTable(unsigned Offset = 0);
381 std::error_code parseConstants();
382 std::error_code rememberAndSkipFunctionBody();
383 /// Save the positions of the Metadata blocks and skip parsing the blocks.
384 std::error_code rememberAndSkipMetadata();
385 std::error_code parseFunctionBody(Function *F);
386 std::error_code globalCleanup();
387 std::error_code resolveGlobalAndAliasInits();
388 std::error_code parseMetadata();
389 std::error_code parseMetadataAttachment(Function &F);
390 ErrorOr<std::string> parseModuleTriple();
391 std::error_code parseUseLists();
392 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
393 std::error_code initStreamFromBuffer();
394 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
395 std::error_code findFunctionInStream(
397 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
400 /// Class to manage reading and parsing function summary index bitcode
402 class FunctionIndexBitcodeReader {
403 DiagnosticHandlerFunction DiagnosticHandler;
405 /// Eventually points to the function index built during parsing.
406 FunctionInfoIndex *TheIndex = nullptr;
408 std::unique_ptr<MemoryBuffer> Buffer;
409 std::unique_ptr<BitstreamReader> StreamFile;
410 BitstreamCursor Stream;
412 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
414 /// If false, the summary section is fully parsed into the index during
415 /// the initial parse. Otherwise, if true, the caller is expected to
416 /// invoke \a readFunctionSummary for each summary needed, and the summary
417 /// section is thus parsed lazily.
420 /// Used to indicate whether caller only wants to check for the presence
421 /// of the function summary bitcode section. All blocks are skipped,
422 /// but the SeenFuncSummary boolean is set.
423 bool CheckFuncSummaryPresenceOnly = false;
425 /// Indicates whether we have encountered a function summary section
426 /// yet during parsing, used when checking if file contains function
428 bool SeenFuncSummary = false;
430 /// \brief Map populated during function summary section parsing, and
431 /// consumed during ValueSymbolTable parsing.
433 /// Used to correlate summary records with VST entries. For the per-module
434 /// index this maps the ValueID to the parsed function summary, and
435 /// for the combined index this maps the summary record's bitcode
436 /// offset to the function summary (since in the combined index the
437 /// VST records do not hold value IDs but rather hold the function
438 /// summary record offset).
439 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
441 /// Map populated during module path string table parsing, from the
442 /// module ID to a string reference owned by the index's module
443 /// path string table, used to correlate with combined index function
445 DenseMap<uint64_t, StringRef> ModuleIdMap;
448 std::error_code error(BitcodeError E, const Twine &Message);
449 std::error_code error(BitcodeError E);
450 std::error_code error(const Twine &Message);
452 FunctionIndexBitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
453 DiagnosticHandlerFunction DiagnosticHandler,
455 bool CheckFuncSummaryPresenceOnly = false);
456 FunctionIndexBitcodeReader(LLVMContext &Context,
457 DiagnosticHandlerFunction DiagnosticHandler,
459 bool CheckFuncSummaryPresenceOnly = false);
460 ~FunctionIndexBitcodeReader() { freeState(); }
464 void releaseBuffer();
466 /// Check if the parser has encountered a function summary section.
467 bool foundFuncSummary() { return SeenFuncSummary; }
469 /// \brief Main interface to parsing a bitcode buffer.
470 /// \returns true if an error occurred.
471 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
472 FunctionInfoIndex *I);
474 /// \brief Interface for parsing a function summary lazily.
475 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
476 FunctionInfoIndex *I,
477 size_t FunctionSummaryOffset);
480 std::error_code parseModule();
481 std::error_code parseValueSymbolTable();
482 std::error_code parseEntireSummary();
483 std::error_code parseModuleStringTable();
484 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
485 std::error_code initStreamFromBuffer();
486 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
490 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
491 DiagnosticSeverity Severity,
493 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
495 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
497 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
498 std::error_code EC, const Twine &Message) {
499 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
500 DiagnosticHandler(DI);
504 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
505 std::error_code EC) {
506 return error(DiagnosticHandler, EC, EC.message());
509 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
510 const Twine &Message) {
511 return error(DiagnosticHandler,
512 make_error_code(BitcodeError::CorruptedBitcode), Message);
515 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
516 return ::error(DiagnosticHandler, make_error_code(E), Message);
519 std::error_code BitcodeReader::error(const Twine &Message) {
520 return ::error(DiagnosticHandler,
521 make_error_code(BitcodeError::CorruptedBitcode), Message);
524 std::error_code BitcodeReader::error(BitcodeError E) {
525 return ::error(DiagnosticHandler, make_error_code(E));
528 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
532 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
535 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
536 DiagnosticHandlerFunction DiagnosticHandler)
538 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
539 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
541 BitcodeReader::BitcodeReader(LLVMContext &Context,
542 DiagnosticHandlerFunction DiagnosticHandler)
544 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
545 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
547 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
548 if (WillMaterializeAllForwardRefs)
549 return std::error_code();
551 // Prevent recursion.
552 WillMaterializeAllForwardRefs = true;
554 while (!BasicBlockFwdRefQueue.empty()) {
555 Function *F = BasicBlockFwdRefQueue.front();
556 BasicBlockFwdRefQueue.pop_front();
557 assert(F && "Expected valid function");
558 if (!BasicBlockFwdRefs.count(F))
559 // Already materialized.
562 // Check for a function that isn't materializable to prevent an infinite
563 // loop. When parsing a blockaddress stored in a global variable, there
564 // isn't a trivial way to check if a function will have a body without a
565 // linear search through FunctionsWithBodies, so just check it here.
566 if (!F->isMaterializable())
567 return error("Never resolved function from blockaddress");
569 // Try to materialize F.
570 if (std::error_code EC = materialize(F))
573 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
576 WillMaterializeAllForwardRefs = false;
577 return std::error_code();
580 void BitcodeReader::freeState() {
582 std::vector<Type*>().swap(TypeList);
585 std::vector<Comdat *>().swap(ComdatList);
587 std::vector<AttributeSet>().swap(MAttributes);
588 std::vector<BasicBlock*>().swap(FunctionBBs);
589 std::vector<Function*>().swap(FunctionsWithBodies);
590 DeferredFunctionInfo.clear();
591 DeferredMetadataInfo.clear();
594 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
595 BasicBlockFwdRefQueue.clear();
598 //===----------------------------------------------------------------------===//
599 // Helper functions to implement forward reference resolution, etc.
600 //===----------------------------------------------------------------------===//
602 /// Convert a string from a record into an std::string, return true on failure.
603 template <typename StrTy>
604 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
606 if (Idx > Record.size())
609 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
610 Result += (char)Record[i];
614 static bool hasImplicitComdat(size_t Val) {
618 case 1: // Old WeakAnyLinkage
619 case 4: // Old LinkOnceAnyLinkage
620 case 10: // Old WeakODRLinkage
621 case 11: // Old LinkOnceODRLinkage
626 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
628 default: // Map unknown/new linkages to external
630 return GlobalValue::ExternalLinkage;
632 return GlobalValue::AppendingLinkage;
634 return GlobalValue::InternalLinkage;
636 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
638 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
640 return GlobalValue::ExternalWeakLinkage;
642 return GlobalValue::CommonLinkage;
644 return GlobalValue::PrivateLinkage;
646 return GlobalValue::AvailableExternallyLinkage;
648 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
650 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
652 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
653 case 1: // Old value with implicit comdat.
655 return GlobalValue::WeakAnyLinkage;
656 case 10: // Old value with implicit comdat.
658 return GlobalValue::WeakODRLinkage;
659 case 4: // Old value with implicit comdat.
661 return GlobalValue::LinkOnceAnyLinkage;
662 case 11: // Old value with implicit comdat.
664 return GlobalValue::LinkOnceODRLinkage;
668 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
670 default: // Map unknown visibilities to default.
671 case 0: return GlobalValue::DefaultVisibility;
672 case 1: return GlobalValue::HiddenVisibility;
673 case 2: return GlobalValue::ProtectedVisibility;
677 static GlobalValue::DLLStorageClassTypes
678 getDecodedDLLStorageClass(unsigned Val) {
680 default: // Map unknown values to default.
681 case 0: return GlobalValue::DefaultStorageClass;
682 case 1: return GlobalValue::DLLImportStorageClass;
683 case 2: return GlobalValue::DLLExportStorageClass;
687 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
689 case 0: return GlobalVariable::NotThreadLocal;
690 default: // Map unknown non-zero value to general dynamic.
691 case 1: return GlobalVariable::GeneralDynamicTLSModel;
692 case 2: return GlobalVariable::LocalDynamicTLSModel;
693 case 3: return GlobalVariable::InitialExecTLSModel;
694 case 4: return GlobalVariable::LocalExecTLSModel;
698 static int getDecodedCastOpcode(unsigned Val) {
701 case bitc::CAST_TRUNC : return Instruction::Trunc;
702 case bitc::CAST_ZEXT : return Instruction::ZExt;
703 case bitc::CAST_SEXT : return Instruction::SExt;
704 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
705 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
706 case bitc::CAST_UITOFP : return Instruction::UIToFP;
707 case bitc::CAST_SITOFP : return Instruction::SIToFP;
708 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
709 case bitc::CAST_FPEXT : return Instruction::FPExt;
710 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
711 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
712 case bitc::CAST_BITCAST : return Instruction::BitCast;
713 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
717 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
718 bool IsFP = Ty->isFPOrFPVectorTy();
719 // BinOps are only valid for int/fp or vector of int/fp types
720 if (!IsFP && !Ty->isIntOrIntVectorTy())
726 case bitc::BINOP_ADD:
727 return IsFP ? Instruction::FAdd : Instruction::Add;
728 case bitc::BINOP_SUB:
729 return IsFP ? Instruction::FSub : Instruction::Sub;
730 case bitc::BINOP_MUL:
731 return IsFP ? Instruction::FMul : Instruction::Mul;
732 case bitc::BINOP_UDIV:
733 return IsFP ? -1 : Instruction::UDiv;
734 case bitc::BINOP_SDIV:
735 return IsFP ? Instruction::FDiv : Instruction::SDiv;
736 case bitc::BINOP_UREM:
737 return IsFP ? -1 : Instruction::URem;
738 case bitc::BINOP_SREM:
739 return IsFP ? Instruction::FRem : Instruction::SRem;
740 case bitc::BINOP_SHL:
741 return IsFP ? -1 : Instruction::Shl;
742 case bitc::BINOP_LSHR:
743 return IsFP ? -1 : Instruction::LShr;
744 case bitc::BINOP_ASHR:
745 return IsFP ? -1 : Instruction::AShr;
746 case bitc::BINOP_AND:
747 return IsFP ? -1 : Instruction::And;
749 return IsFP ? -1 : Instruction::Or;
750 case bitc::BINOP_XOR:
751 return IsFP ? -1 : Instruction::Xor;
755 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
757 default: return AtomicRMWInst::BAD_BINOP;
758 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
759 case bitc::RMW_ADD: return AtomicRMWInst::Add;
760 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
761 case bitc::RMW_AND: return AtomicRMWInst::And;
762 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
763 case bitc::RMW_OR: return AtomicRMWInst::Or;
764 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
765 case bitc::RMW_MAX: return AtomicRMWInst::Max;
766 case bitc::RMW_MIN: return AtomicRMWInst::Min;
767 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
768 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
772 static AtomicOrdering getDecodedOrdering(unsigned Val) {
774 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
775 case bitc::ORDERING_UNORDERED: return Unordered;
776 case bitc::ORDERING_MONOTONIC: return Monotonic;
777 case bitc::ORDERING_ACQUIRE: return Acquire;
778 case bitc::ORDERING_RELEASE: return Release;
779 case bitc::ORDERING_ACQREL: return AcquireRelease;
780 default: // Map unknown orderings to sequentially-consistent.
781 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
785 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
787 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
788 default: // Map unknown scopes to cross-thread.
789 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
793 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
795 default: // Map unknown selection kinds to any.
796 case bitc::COMDAT_SELECTION_KIND_ANY:
798 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
799 return Comdat::ExactMatch;
800 case bitc::COMDAT_SELECTION_KIND_LARGEST:
801 return Comdat::Largest;
802 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
803 return Comdat::NoDuplicates;
804 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
805 return Comdat::SameSize;
809 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
811 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
812 FMF.setUnsafeAlgebra();
813 if (0 != (Val & FastMathFlags::NoNaNs))
815 if (0 != (Val & FastMathFlags::NoInfs))
817 if (0 != (Val & FastMathFlags::NoSignedZeros))
818 FMF.setNoSignedZeros();
819 if (0 != (Val & FastMathFlags::AllowReciprocal))
820 FMF.setAllowReciprocal();
824 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
826 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
827 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
833 /// \brief A class for maintaining the slot number definition
834 /// as a placeholder for the actual definition for forward constants defs.
835 class ConstantPlaceHolder : public ConstantExpr {
836 void operator=(const ConstantPlaceHolder &) = delete;
839 // allocate space for exactly one operand
840 void *operator new(size_t s) { return User::operator new(s, 1); }
841 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
842 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
843 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
846 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
847 static bool classof(const Value *V) {
848 return isa<ConstantExpr>(V) &&
849 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
852 /// Provide fast operand accessors
853 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
857 // FIXME: can we inherit this from ConstantExpr?
859 struct OperandTraits<ConstantPlaceHolder> :
860 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
862 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
865 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
874 WeakVH &OldV = ValuePtrs[Idx];
880 // Handle constants and non-constants (e.g. instrs) differently for
882 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
883 ResolveConstants.push_back(std::make_pair(PHC, Idx));
886 // If there was a forward reference to this value, replace it.
887 Value *PrevVal = OldV;
888 // Check operator constraints. We only put cleanuppads or catchpads in
889 // the forward value map if the value is constrained to match.
890 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
891 if (!isa<CatchPadInst>(V))
893 // Delete the dummy basic block that was created with the sentinel
895 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
896 assert(DummyBlock == CatchPad->getNormalDest());
897 CatchPad->dropAllReferences();
899 } else if (isa<CleanupPadInst>(PrevVal)) {
900 if (!isa<CleanupPadInst>(V))
903 OldV->replaceAllUsesWith(V);
911 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
916 if (Value *V = ValuePtrs[Idx]) {
917 if (Ty != V->getType())
918 report_fatal_error("Type mismatch in constant table!");
919 return cast<Constant>(V);
922 // Create and return a placeholder, which will later be RAUW'd.
923 Constant *C = new ConstantPlaceHolder(Ty, Context);
928 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
929 OperatorConstraint OC) {
930 // Bail out for a clearly invalid value. This would make us call resize(0)
937 if (Value *V = ValuePtrs[Idx]) {
938 // If the types don't match, it's invalid.
939 if (Ty && Ty != V->getType())
943 // Use dyn_cast to enforce operator constraints
946 return dyn_cast<CatchPadInst>(V);
948 return dyn_cast<CleanupPadInst>(V);
950 llvm_unreachable("Unexpected operator constraint");
954 // No type specified, must be invalid reference.
955 if (!Ty) return nullptr;
957 // Create and return a placeholder, which will later be RAUW'd.
961 V = new Argument(Ty);
964 BasicBlock *BB = BasicBlock::Create(Context);
965 V = CatchPadInst::Create(BB, BB, {});
969 assert(OC == OC_CleanupPad && "unexpected operator constraint");
970 V = CleanupPadInst::Create(Context, {});
978 /// Once all constants are read, this method bulk resolves any forward
979 /// references. The idea behind this is that we sometimes get constants (such
980 /// as large arrays) which reference *many* forward ref constants. Replacing
981 /// each of these causes a lot of thrashing when building/reuniquing the
982 /// constant. Instead of doing this, we look at all the uses and rewrite all
983 /// the place holders at once for any constant that uses a placeholder.
984 void BitcodeReaderValueList::resolveConstantForwardRefs() {
985 // Sort the values by-pointer so that they are efficient to look up with a
987 std::sort(ResolveConstants.begin(), ResolveConstants.end());
989 SmallVector<Constant*, 64> NewOps;
991 while (!ResolveConstants.empty()) {
992 Value *RealVal = operator[](ResolveConstants.back().second);
993 Constant *Placeholder = ResolveConstants.back().first;
994 ResolveConstants.pop_back();
996 // Loop over all users of the placeholder, updating them to reference the
997 // new value. If they reference more than one placeholder, update them all
999 while (!Placeholder->use_empty()) {
1000 auto UI = Placeholder->user_begin();
1003 // If the using object isn't uniqued, just update the operands. This
1004 // handles instructions and initializers for global variables.
1005 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1006 UI.getUse().set(RealVal);
1010 // Otherwise, we have a constant that uses the placeholder. Replace that
1011 // constant with a new constant that has *all* placeholder uses updated.
1012 Constant *UserC = cast<Constant>(U);
1013 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1016 if (!isa<ConstantPlaceHolder>(*I)) {
1017 // Not a placeholder reference.
1019 } else if (*I == Placeholder) {
1020 // Common case is that it just references this one placeholder.
1023 // Otherwise, look up the placeholder in ResolveConstants.
1024 ResolveConstantsTy::iterator It =
1025 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1026 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1028 assert(It != ResolveConstants.end() && It->first == *I);
1029 NewOp = operator[](It->second);
1032 NewOps.push_back(cast<Constant>(NewOp));
1035 // Make the new constant.
1037 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1038 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1039 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1040 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1041 } else if (isa<ConstantVector>(UserC)) {
1042 NewC = ConstantVector::get(NewOps);
1044 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1045 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1048 UserC->replaceAllUsesWith(NewC);
1049 UserC->destroyConstant();
1053 // Update all ValueHandles, they should be the only users at this point.
1054 Placeholder->replaceAllUsesWith(RealVal);
1059 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1060 if (Idx == size()) {
1068 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1074 // If there was a forward reference to this value, replace it.
1075 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1076 PrevMD->replaceAllUsesWith(MD);
1080 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1084 if (Metadata *MD = MDValuePtrs[Idx])
1087 // Track forward refs to be resolved later.
1089 MinFwdRef = std::min(MinFwdRef, Idx);
1090 MaxFwdRef = std::max(MaxFwdRef, Idx);
1093 MinFwdRef = MaxFwdRef = Idx;
1097 // Create and return a placeholder, which will later be RAUW'd.
1098 Metadata *MD = MDNode::getTemporary(Context, None).release();
1099 MDValuePtrs[Idx].reset(MD);
1103 void BitcodeReaderMDValueList::tryToResolveCycles() {
1109 // Still forward references... can't resolve cycles.
1112 // Resolve any cycles.
1113 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1114 auto &MD = MDValuePtrs[I];
1115 auto *N = dyn_cast_or_null<MDNode>(MD);
1119 assert(!N->isTemporary() && "Unexpected forward reference");
1123 // Make sure we return early again until there's another forward ref.
1127 Type *BitcodeReader::getTypeByID(unsigned ID) {
1128 // The type table size is always specified correctly.
1129 if (ID >= TypeList.size())
1132 if (Type *Ty = TypeList[ID])
1135 // If we have a forward reference, the only possible case is when it is to a
1136 // named struct. Just create a placeholder for now.
1137 return TypeList[ID] = createIdentifiedStructType(Context);
1140 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1142 auto *Ret = StructType::create(Context, Name);
1143 IdentifiedStructTypes.push_back(Ret);
1147 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1148 auto *Ret = StructType::create(Context);
1149 IdentifiedStructTypes.push_back(Ret);
1154 //===----------------------------------------------------------------------===//
1155 // Functions for parsing blocks from the bitcode file
1156 //===----------------------------------------------------------------------===//
1159 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1160 /// been decoded from the given integer. This function must stay in sync with
1161 /// 'encodeLLVMAttributesForBitcode'.
1162 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1163 uint64_t EncodedAttrs) {
1164 // FIXME: Remove in 4.0.
1166 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1167 // the bits above 31 down by 11 bits.
1168 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1169 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1170 "Alignment must be a power of two.");
1173 B.addAlignmentAttr(Alignment);
1174 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1175 (EncodedAttrs & 0xffff));
1178 std::error_code BitcodeReader::parseAttributeBlock() {
1179 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1180 return error("Invalid record");
1182 if (!MAttributes.empty())
1183 return error("Invalid multiple blocks");
1185 SmallVector<uint64_t, 64> Record;
1187 SmallVector<AttributeSet, 8> Attrs;
1189 // Read all the records.
1191 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1193 switch (Entry.Kind) {
1194 case BitstreamEntry::SubBlock: // Handled for us already.
1195 case BitstreamEntry::Error:
1196 return error("Malformed block");
1197 case BitstreamEntry::EndBlock:
1198 return std::error_code();
1199 case BitstreamEntry::Record:
1200 // The interesting case.
1206 switch (Stream.readRecord(Entry.ID, Record)) {
1207 default: // Default behavior: ignore.
1209 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1210 // FIXME: Remove in 4.0.
1211 if (Record.size() & 1)
1212 return error("Invalid record");
1214 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1216 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1217 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1220 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1224 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1225 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1226 Attrs.push_back(MAttributeGroups[Record[i]]);
1228 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1236 // Returns Attribute::None on unrecognized codes.
1237 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1240 return Attribute::None;
1241 case bitc::ATTR_KIND_ALIGNMENT:
1242 return Attribute::Alignment;
1243 case bitc::ATTR_KIND_ALWAYS_INLINE:
1244 return Attribute::AlwaysInline;
1245 case bitc::ATTR_KIND_ARGMEMONLY:
1246 return Attribute::ArgMemOnly;
1247 case bitc::ATTR_KIND_BUILTIN:
1248 return Attribute::Builtin;
1249 case bitc::ATTR_KIND_BY_VAL:
1250 return Attribute::ByVal;
1251 case bitc::ATTR_KIND_IN_ALLOCA:
1252 return Attribute::InAlloca;
1253 case bitc::ATTR_KIND_COLD:
1254 return Attribute::Cold;
1255 case bitc::ATTR_KIND_CONVERGENT:
1256 return Attribute::Convergent;
1257 case bitc::ATTR_KIND_INLINE_HINT:
1258 return Attribute::InlineHint;
1259 case bitc::ATTR_KIND_IN_REG:
1260 return Attribute::InReg;
1261 case bitc::ATTR_KIND_JUMP_TABLE:
1262 return Attribute::JumpTable;
1263 case bitc::ATTR_KIND_MIN_SIZE:
1264 return Attribute::MinSize;
1265 case bitc::ATTR_KIND_NAKED:
1266 return Attribute::Naked;
1267 case bitc::ATTR_KIND_NEST:
1268 return Attribute::Nest;
1269 case bitc::ATTR_KIND_NO_ALIAS:
1270 return Attribute::NoAlias;
1271 case bitc::ATTR_KIND_NO_BUILTIN:
1272 return Attribute::NoBuiltin;
1273 case bitc::ATTR_KIND_NO_CAPTURE:
1274 return Attribute::NoCapture;
1275 case bitc::ATTR_KIND_NO_DUPLICATE:
1276 return Attribute::NoDuplicate;
1277 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1278 return Attribute::NoImplicitFloat;
1279 case bitc::ATTR_KIND_NO_INLINE:
1280 return Attribute::NoInline;
1281 case bitc::ATTR_KIND_NON_LAZY_BIND:
1282 return Attribute::NonLazyBind;
1283 case bitc::ATTR_KIND_NON_NULL:
1284 return Attribute::NonNull;
1285 case bitc::ATTR_KIND_DEREFERENCEABLE:
1286 return Attribute::Dereferenceable;
1287 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1288 return Attribute::DereferenceableOrNull;
1289 case bitc::ATTR_KIND_NO_RED_ZONE:
1290 return Attribute::NoRedZone;
1291 case bitc::ATTR_KIND_NO_RETURN:
1292 return Attribute::NoReturn;
1293 case bitc::ATTR_KIND_NO_UNWIND:
1294 return Attribute::NoUnwind;
1295 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1296 return Attribute::OptimizeForSize;
1297 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1298 return Attribute::OptimizeNone;
1299 case bitc::ATTR_KIND_READ_NONE:
1300 return Attribute::ReadNone;
1301 case bitc::ATTR_KIND_READ_ONLY:
1302 return Attribute::ReadOnly;
1303 case bitc::ATTR_KIND_RETURNED:
1304 return Attribute::Returned;
1305 case bitc::ATTR_KIND_RETURNS_TWICE:
1306 return Attribute::ReturnsTwice;
1307 case bitc::ATTR_KIND_S_EXT:
1308 return Attribute::SExt;
1309 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1310 return Attribute::StackAlignment;
1311 case bitc::ATTR_KIND_STACK_PROTECT:
1312 return Attribute::StackProtect;
1313 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1314 return Attribute::StackProtectReq;
1315 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1316 return Attribute::StackProtectStrong;
1317 case bitc::ATTR_KIND_SAFESTACK:
1318 return Attribute::SafeStack;
1319 case bitc::ATTR_KIND_STRUCT_RET:
1320 return Attribute::StructRet;
1321 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1322 return Attribute::SanitizeAddress;
1323 case bitc::ATTR_KIND_SANITIZE_THREAD:
1324 return Attribute::SanitizeThread;
1325 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1326 return Attribute::SanitizeMemory;
1327 case bitc::ATTR_KIND_UW_TABLE:
1328 return Attribute::UWTable;
1329 case bitc::ATTR_KIND_Z_EXT:
1330 return Attribute::ZExt;
1334 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1335 unsigned &Alignment) {
1336 // Note: Alignment in bitcode files is incremented by 1, so that zero
1337 // can be used for default alignment.
1338 if (Exponent > Value::MaxAlignmentExponent + 1)
1339 return error("Invalid alignment value");
1340 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1341 return std::error_code();
1344 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1345 Attribute::AttrKind *Kind) {
1346 *Kind = getAttrFromCode(Code);
1347 if (*Kind == Attribute::None)
1348 return error(BitcodeError::CorruptedBitcode,
1349 "Unknown attribute kind (" + Twine(Code) + ")");
1350 return std::error_code();
1353 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1354 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1355 return error("Invalid record");
1357 if (!MAttributeGroups.empty())
1358 return error("Invalid multiple blocks");
1360 SmallVector<uint64_t, 64> Record;
1362 // Read all the records.
1364 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1366 switch (Entry.Kind) {
1367 case BitstreamEntry::SubBlock: // Handled for us already.
1368 case BitstreamEntry::Error:
1369 return error("Malformed block");
1370 case BitstreamEntry::EndBlock:
1371 return std::error_code();
1372 case BitstreamEntry::Record:
1373 // The interesting case.
1379 switch (Stream.readRecord(Entry.ID, Record)) {
1380 default: // Default behavior: ignore.
1382 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1383 if (Record.size() < 3)
1384 return error("Invalid record");
1386 uint64_t GrpID = Record[0];
1387 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1390 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1391 if (Record[i] == 0) { // Enum attribute
1392 Attribute::AttrKind Kind;
1393 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1396 B.addAttribute(Kind);
1397 } else if (Record[i] == 1) { // Integer attribute
1398 Attribute::AttrKind Kind;
1399 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1401 if (Kind == Attribute::Alignment)
1402 B.addAlignmentAttr(Record[++i]);
1403 else if (Kind == Attribute::StackAlignment)
1404 B.addStackAlignmentAttr(Record[++i]);
1405 else if (Kind == Attribute::Dereferenceable)
1406 B.addDereferenceableAttr(Record[++i]);
1407 else if (Kind == Attribute::DereferenceableOrNull)
1408 B.addDereferenceableOrNullAttr(Record[++i]);
1409 } else { // String attribute
1410 assert((Record[i] == 3 || Record[i] == 4) &&
1411 "Invalid attribute group entry");
1412 bool HasValue = (Record[i++] == 4);
1413 SmallString<64> KindStr;
1414 SmallString<64> ValStr;
1416 while (Record[i] != 0 && i != e)
1417 KindStr += Record[i++];
1418 assert(Record[i] == 0 && "Kind string not null terminated");
1421 // Has a value associated with it.
1422 ++i; // Skip the '0' that terminates the "kind" string.
1423 while (Record[i] != 0 && i != e)
1424 ValStr += Record[i++];
1425 assert(Record[i] == 0 && "Value string not null terminated");
1428 B.addAttribute(KindStr.str(), ValStr.str());
1432 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1439 std::error_code BitcodeReader::parseTypeTable() {
1440 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1441 return error("Invalid record");
1443 return parseTypeTableBody();
1446 std::error_code BitcodeReader::parseTypeTableBody() {
1447 if (!TypeList.empty())
1448 return error("Invalid multiple blocks");
1450 SmallVector<uint64_t, 64> Record;
1451 unsigned NumRecords = 0;
1453 SmallString<64> TypeName;
1455 // Read all the records for this type table.
1457 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1459 switch (Entry.Kind) {
1460 case BitstreamEntry::SubBlock: // Handled for us already.
1461 case BitstreamEntry::Error:
1462 return error("Malformed block");
1463 case BitstreamEntry::EndBlock:
1464 if (NumRecords != TypeList.size())
1465 return error("Malformed block");
1466 return std::error_code();
1467 case BitstreamEntry::Record:
1468 // The interesting case.
1474 Type *ResultTy = nullptr;
1475 switch (Stream.readRecord(Entry.ID, Record)) {
1477 return error("Invalid value");
1478 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1479 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1480 // type list. This allows us to reserve space.
1481 if (Record.size() < 1)
1482 return error("Invalid record");
1483 TypeList.resize(Record[0]);
1485 case bitc::TYPE_CODE_VOID: // VOID
1486 ResultTy = Type::getVoidTy(Context);
1488 case bitc::TYPE_CODE_HALF: // HALF
1489 ResultTy = Type::getHalfTy(Context);
1491 case bitc::TYPE_CODE_FLOAT: // FLOAT
1492 ResultTy = Type::getFloatTy(Context);
1494 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1495 ResultTy = Type::getDoubleTy(Context);
1497 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1498 ResultTy = Type::getX86_FP80Ty(Context);
1500 case bitc::TYPE_CODE_FP128: // FP128
1501 ResultTy = Type::getFP128Ty(Context);
1503 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1504 ResultTy = Type::getPPC_FP128Ty(Context);
1506 case bitc::TYPE_CODE_LABEL: // LABEL
1507 ResultTy = Type::getLabelTy(Context);
1509 case bitc::TYPE_CODE_METADATA: // METADATA
1510 ResultTy = Type::getMetadataTy(Context);
1512 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1513 ResultTy = Type::getX86_MMXTy(Context);
1515 case bitc::TYPE_CODE_TOKEN: // TOKEN
1516 ResultTy = Type::getTokenTy(Context);
1518 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1519 if (Record.size() < 1)
1520 return error("Invalid record");
1522 uint64_t NumBits = Record[0];
1523 if (NumBits < IntegerType::MIN_INT_BITS ||
1524 NumBits > IntegerType::MAX_INT_BITS)
1525 return error("Bitwidth for integer type out of range");
1526 ResultTy = IntegerType::get(Context, NumBits);
1529 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1530 // [pointee type, address space]
1531 if (Record.size() < 1)
1532 return error("Invalid record");
1533 unsigned AddressSpace = 0;
1534 if (Record.size() == 2)
1535 AddressSpace = Record[1];
1536 ResultTy = getTypeByID(Record[0]);
1538 !PointerType::isValidElementType(ResultTy))
1539 return error("Invalid type");
1540 ResultTy = PointerType::get(ResultTy, AddressSpace);
1543 case bitc::TYPE_CODE_FUNCTION_OLD: {
1544 // FIXME: attrid is dead, remove it in LLVM 4.0
1545 // FUNCTION: [vararg, attrid, retty, paramty x N]
1546 if (Record.size() < 3)
1547 return error("Invalid record");
1548 SmallVector<Type*, 8> ArgTys;
1549 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1550 if (Type *T = getTypeByID(Record[i]))
1551 ArgTys.push_back(T);
1556 ResultTy = getTypeByID(Record[2]);
1557 if (!ResultTy || ArgTys.size() < Record.size()-3)
1558 return error("Invalid type");
1560 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1563 case bitc::TYPE_CODE_FUNCTION: {
1564 // FUNCTION: [vararg, retty, paramty x N]
1565 if (Record.size() < 2)
1566 return error("Invalid record");
1567 SmallVector<Type*, 8> ArgTys;
1568 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1569 if (Type *T = getTypeByID(Record[i])) {
1570 if (!FunctionType::isValidArgumentType(T))
1571 return error("Invalid function argument type");
1572 ArgTys.push_back(T);
1578 ResultTy = getTypeByID(Record[1]);
1579 if (!ResultTy || ArgTys.size() < Record.size()-2)
1580 return error("Invalid type");
1582 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1585 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1586 if (Record.size() < 1)
1587 return error("Invalid record");
1588 SmallVector<Type*, 8> EltTys;
1589 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1590 if (Type *T = getTypeByID(Record[i]))
1591 EltTys.push_back(T);
1595 if (EltTys.size() != Record.size()-1)
1596 return error("Invalid type");
1597 ResultTy = StructType::get(Context, EltTys, Record[0]);
1600 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1601 if (convertToString(Record, 0, TypeName))
1602 return error("Invalid record");
1605 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1606 if (Record.size() < 1)
1607 return error("Invalid record");
1609 if (NumRecords >= TypeList.size())
1610 return error("Invalid TYPE table");
1612 // Check to see if this was forward referenced, if so fill in the temp.
1613 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1615 Res->setName(TypeName);
1616 TypeList[NumRecords] = nullptr;
1617 } else // Otherwise, create a new struct.
1618 Res = createIdentifiedStructType(Context, TypeName);
1621 SmallVector<Type*, 8> EltTys;
1622 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1623 if (Type *T = getTypeByID(Record[i]))
1624 EltTys.push_back(T);
1628 if (EltTys.size() != Record.size()-1)
1629 return error("Invalid record");
1630 Res->setBody(EltTys, Record[0]);
1634 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1635 if (Record.size() != 1)
1636 return error("Invalid record");
1638 if (NumRecords >= TypeList.size())
1639 return error("Invalid TYPE table");
1641 // Check to see if this was forward referenced, if so fill in the temp.
1642 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1644 Res->setName(TypeName);
1645 TypeList[NumRecords] = nullptr;
1646 } else // Otherwise, create a new struct with no body.
1647 Res = createIdentifiedStructType(Context, TypeName);
1652 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1653 if (Record.size() < 2)
1654 return error("Invalid record");
1655 ResultTy = getTypeByID(Record[1]);
1656 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1657 return error("Invalid type");
1658 ResultTy = ArrayType::get(ResultTy, Record[0]);
1660 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1661 if (Record.size() < 2)
1662 return error("Invalid record");
1664 return error("Invalid vector length");
1665 ResultTy = getTypeByID(Record[1]);
1666 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1667 return error("Invalid type");
1668 ResultTy = VectorType::get(ResultTy, Record[0]);
1672 if (NumRecords >= TypeList.size())
1673 return error("Invalid TYPE table");
1674 if (TypeList[NumRecords])
1676 "Invalid TYPE table: Only named structs can be forward referenced");
1677 assert(ResultTy && "Didn't read a type?");
1678 TypeList[NumRecords++] = ResultTy;
1682 std::error_code BitcodeReader::parseOperandBundleTags() {
1683 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1684 return error("Invalid record");
1686 if (!BundleTags.empty())
1687 return error("Invalid multiple blocks");
1689 SmallVector<uint64_t, 64> Record;
1692 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1694 switch (Entry.Kind) {
1695 case BitstreamEntry::SubBlock: // Handled for us already.
1696 case BitstreamEntry::Error:
1697 return error("Malformed block");
1698 case BitstreamEntry::EndBlock:
1699 return std::error_code();
1700 case BitstreamEntry::Record:
1701 // The interesting case.
1705 // Tags are implicitly mapped to integers by their order.
1707 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1708 return error("Invalid record");
1710 // OPERAND_BUNDLE_TAG: [strchr x N]
1711 BundleTags.emplace_back();
1712 if (convertToString(Record, 0, BundleTags.back()))
1713 return error("Invalid record");
1718 /// Associate a value with its name from the given index in the provided record.
1719 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1720 unsigned NameIndex, Triple &TT) {
1721 SmallString<128> ValueName;
1722 if (convertToString(Record, NameIndex, ValueName))
1723 return error("Invalid record");
1724 unsigned ValueID = Record[0];
1725 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1726 return error("Invalid record");
1727 Value *V = ValueList[ValueID];
1729 V->setName(StringRef(ValueName.data(), ValueName.size()));
1730 auto *GO = dyn_cast<GlobalObject>(V);
1732 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1733 if (TT.isOSBinFormatMachO())
1734 GO->setComdat(nullptr);
1736 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1742 /// Parse the value symbol table at either the current parsing location or
1743 /// at the given bit offset if provided.
1744 std::error_code BitcodeReader::parseValueSymbolTable(unsigned Offset) {
1745 uint64_t CurrentBit;
1746 // Pass in the Offset to distinguish between calling for the module-level
1747 // VST (where we want to jump to the VST offset) and the function-level
1748 // VST (where we don't).
1750 // Save the current parsing location so we can jump back at the end
1752 CurrentBit = Stream.GetCurrentBitNo();
1753 Stream.JumpToBit(Offset * 32);
1755 // Do some checking if we are in debug mode.
1756 BitstreamEntry Entry = Stream.advance();
1757 assert(Entry.Kind == BitstreamEntry::SubBlock);
1758 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1760 // In NDEBUG mode ignore the output so we don't get an unused variable
1766 // Compute the delta between the bitcode indices in the VST (the word offset
1767 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1768 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1769 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1770 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1771 // just before entering the VST subblock because: 1) the EnterSubBlock
1772 // changes the AbbrevID width; 2) the VST block is nested within the same
1773 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1774 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1775 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1776 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1777 unsigned FuncBitcodeOffsetDelta =
1778 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1780 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1781 return error("Invalid record");
1783 SmallVector<uint64_t, 64> Record;
1785 Triple TT(TheModule->getTargetTriple());
1787 // Read all the records for this value table.
1788 SmallString<128> ValueName;
1790 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1792 switch (Entry.Kind) {
1793 case BitstreamEntry::SubBlock: // Handled for us already.
1794 case BitstreamEntry::Error:
1795 return error("Malformed block");
1796 case BitstreamEntry::EndBlock:
1798 Stream.JumpToBit(CurrentBit);
1799 return std::error_code();
1800 case BitstreamEntry::Record:
1801 // The interesting case.
1807 switch (Stream.readRecord(Entry.ID, Record)) {
1808 default: // Default behavior: unknown type.
1810 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1811 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1812 if (std::error_code EC = ValOrErr.getError())
1817 case bitc::VST_CODE_FNENTRY: {
1818 // VST_FNENTRY: [valueid, offset, namechar x N]
1819 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1820 if (std::error_code EC = ValOrErr.getError())
1822 Value *V = ValOrErr.get();
1824 auto *GO = dyn_cast<GlobalObject>(V);
1826 // If this is an alias, need to get the actual Function object
1827 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1828 auto *GA = dyn_cast<GlobalAlias>(V);
1830 GO = GA->getBaseObject();
1834 uint64_t FuncWordOffset = Record[1];
1835 Function *F = dyn_cast<Function>(GO);
1837 uint64_t FuncBitOffset = FuncWordOffset * 32;
1838 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1839 // Set the NextUnreadBit to point to the last function block.
1840 // Later when parsing is resumed after function materialization,
1841 // we can simply skip that last function block.
1842 if (FuncBitOffset > NextUnreadBit)
1843 NextUnreadBit = FuncBitOffset;
1846 case bitc::VST_CODE_BBENTRY: {
1847 if (convertToString(Record, 1, ValueName))
1848 return error("Invalid record");
1849 BasicBlock *BB = getBasicBlock(Record[0]);
1851 return error("Invalid record");
1853 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1861 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1863 std::error_code BitcodeReader::parseMetadata() {
1864 IsMetadataMaterialized = true;
1865 unsigned NextMDValueNo = MDValueList.size();
1867 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1868 return error("Invalid record");
1870 SmallVector<uint64_t, 64> Record;
1873 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1874 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1876 return getMD(ID - 1);
1879 auto getMDString = [&](unsigned ID) -> MDString *{
1880 // This requires that the ID is not really a forward reference. In
1881 // particular, the MDString must already have been resolved.
1882 return cast_or_null<MDString>(getMDOrNull(ID));
1885 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1886 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1888 // Read all the records.
1890 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1892 switch (Entry.Kind) {
1893 case BitstreamEntry::SubBlock: // Handled for us already.
1894 case BitstreamEntry::Error:
1895 return error("Malformed block");
1896 case BitstreamEntry::EndBlock:
1897 MDValueList.tryToResolveCycles();
1898 return std::error_code();
1899 case BitstreamEntry::Record:
1900 // The interesting case.
1906 unsigned Code = Stream.readRecord(Entry.ID, Record);
1907 bool IsDistinct = false;
1909 default: // Default behavior: ignore.
1911 case bitc::METADATA_NAME: {
1912 // Read name of the named metadata.
1913 SmallString<8> Name(Record.begin(), Record.end());
1915 Code = Stream.ReadCode();
1917 unsigned NextBitCode = Stream.readRecord(Code, Record);
1918 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1919 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1921 // Read named metadata elements.
1922 unsigned Size = Record.size();
1923 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1924 for (unsigned i = 0; i != Size; ++i) {
1925 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1927 return error("Invalid record");
1928 NMD->addOperand(MD);
1932 case bitc::METADATA_OLD_FN_NODE: {
1933 // FIXME: Remove in 4.0.
1934 // This is a LocalAsMetadata record, the only type of function-local
1936 if (Record.size() % 2 == 1)
1937 return error("Invalid record");
1939 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1940 // to be legal, but there's no upgrade path.
1941 auto dropRecord = [&] {
1942 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1944 if (Record.size() != 2) {
1949 Type *Ty = getTypeByID(Record[0]);
1950 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1955 MDValueList.assignValue(
1956 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1960 case bitc::METADATA_OLD_NODE: {
1961 // FIXME: Remove in 4.0.
1962 if (Record.size() % 2 == 1)
1963 return error("Invalid record");
1965 unsigned Size = Record.size();
1966 SmallVector<Metadata *, 8> Elts;
1967 for (unsigned i = 0; i != Size; i += 2) {
1968 Type *Ty = getTypeByID(Record[i]);
1970 return error("Invalid record");
1971 if (Ty->isMetadataTy())
1972 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1973 else if (!Ty->isVoidTy()) {
1975 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1976 assert(isa<ConstantAsMetadata>(MD) &&
1977 "Expected non-function-local metadata");
1980 Elts.push_back(nullptr);
1982 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1985 case bitc::METADATA_VALUE: {
1986 if (Record.size() != 2)
1987 return error("Invalid record");
1989 Type *Ty = getTypeByID(Record[0]);
1990 if (Ty->isMetadataTy() || Ty->isVoidTy())
1991 return error("Invalid record");
1993 MDValueList.assignValue(
1994 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1998 case bitc::METADATA_DISTINCT_NODE:
2001 case bitc::METADATA_NODE: {
2002 SmallVector<Metadata *, 8> Elts;
2003 Elts.reserve(Record.size());
2004 for (unsigned ID : Record)
2005 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2006 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2007 : MDNode::get(Context, Elts),
2011 case bitc::METADATA_LOCATION: {
2012 if (Record.size() != 5)
2013 return error("Invalid record");
2015 unsigned Line = Record[1];
2016 unsigned Column = Record[2];
2017 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2018 Metadata *InlinedAt =
2019 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2020 MDValueList.assignValue(
2021 GET_OR_DISTINCT(DILocation, Record[0],
2022 (Context, Line, Column, Scope, InlinedAt)),
2026 case bitc::METADATA_GENERIC_DEBUG: {
2027 if (Record.size() < 4)
2028 return error("Invalid record");
2030 unsigned Tag = Record[1];
2031 unsigned Version = Record[2];
2033 if (Tag >= 1u << 16 || Version != 0)
2034 return error("Invalid record");
2036 auto *Header = getMDString(Record[3]);
2037 SmallVector<Metadata *, 8> DwarfOps;
2038 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2039 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2041 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2042 (Context, Tag, Header, DwarfOps)),
2046 case bitc::METADATA_SUBRANGE: {
2047 if (Record.size() != 3)
2048 return error("Invalid record");
2050 MDValueList.assignValue(
2051 GET_OR_DISTINCT(DISubrange, Record[0],
2052 (Context, Record[1], unrotateSign(Record[2]))),
2056 case bitc::METADATA_ENUMERATOR: {
2057 if (Record.size() != 3)
2058 return error("Invalid record");
2060 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2061 (Context, unrotateSign(Record[1]),
2062 getMDString(Record[2]))),
2066 case bitc::METADATA_BASIC_TYPE: {
2067 if (Record.size() != 6)
2068 return error("Invalid record");
2070 MDValueList.assignValue(
2071 GET_OR_DISTINCT(DIBasicType, Record[0],
2072 (Context, Record[1], getMDString(Record[2]),
2073 Record[3], Record[4], Record[5])),
2077 case bitc::METADATA_DERIVED_TYPE: {
2078 if (Record.size() != 12)
2079 return error("Invalid record");
2081 MDValueList.assignValue(
2082 GET_OR_DISTINCT(DIDerivedType, Record[0],
2083 (Context, Record[1], getMDString(Record[2]),
2084 getMDOrNull(Record[3]), Record[4],
2085 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2086 Record[7], Record[8], Record[9], Record[10],
2087 getMDOrNull(Record[11]))),
2091 case bitc::METADATA_COMPOSITE_TYPE: {
2092 if (Record.size() != 16)
2093 return error("Invalid record");
2095 MDValueList.assignValue(
2096 GET_OR_DISTINCT(DICompositeType, Record[0],
2097 (Context, Record[1], getMDString(Record[2]),
2098 getMDOrNull(Record[3]), Record[4],
2099 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2100 Record[7], Record[8], Record[9], Record[10],
2101 getMDOrNull(Record[11]), Record[12],
2102 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2103 getMDString(Record[15]))),
2107 case bitc::METADATA_SUBROUTINE_TYPE: {
2108 if (Record.size() != 3)
2109 return error("Invalid record");
2111 MDValueList.assignValue(
2112 GET_OR_DISTINCT(DISubroutineType, Record[0],
2113 (Context, Record[1], getMDOrNull(Record[2]))),
2118 case bitc::METADATA_MODULE: {
2119 if (Record.size() != 6)
2120 return error("Invalid record");
2122 MDValueList.assignValue(
2123 GET_OR_DISTINCT(DIModule, Record[0],
2124 (Context, getMDOrNull(Record[1]),
2125 getMDString(Record[2]), getMDString(Record[3]),
2126 getMDString(Record[4]), getMDString(Record[5]))),
2131 case bitc::METADATA_FILE: {
2132 if (Record.size() != 3)
2133 return error("Invalid record");
2135 MDValueList.assignValue(
2136 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2137 getMDString(Record[2]))),
2141 case bitc::METADATA_COMPILE_UNIT: {
2142 if (Record.size() < 14 || Record.size() > 15)
2143 return error("Invalid record");
2145 // Ignore Record[1], which indicates whether this compile unit is
2146 // distinct. It's always distinct.
2147 MDValueList.assignValue(
2148 DICompileUnit::getDistinct(
2149 Context, Record[1], getMDOrNull(Record[2]),
2150 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2151 Record[6], getMDString(Record[7]), Record[8],
2152 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2153 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2154 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2158 case bitc::METADATA_SUBPROGRAM: {
2159 if (Record.size() != 19)
2160 return error("Invalid record");
2162 MDValueList.assignValue(
2165 Record[0] || Record[8], // All definitions should be distinct.
2166 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2167 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2168 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2169 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2170 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
2171 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
2175 case bitc::METADATA_LEXICAL_BLOCK: {
2176 if (Record.size() != 5)
2177 return error("Invalid record");
2179 MDValueList.assignValue(
2180 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2181 (Context, getMDOrNull(Record[1]),
2182 getMDOrNull(Record[2]), Record[3], Record[4])),
2186 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2187 if (Record.size() != 4)
2188 return error("Invalid record");
2190 MDValueList.assignValue(
2191 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2192 (Context, getMDOrNull(Record[1]),
2193 getMDOrNull(Record[2]), Record[3])),
2197 case bitc::METADATA_NAMESPACE: {
2198 if (Record.size() != 5)
2199 return error("Invalid record");
2201 MDValueList.assignValue(
2202 GET_OR_DISTINCT(DINamespace, Record[0],
2203 (Context, getMDOrNull(Record[1]),
2204 getMDOrNull(Record[2]), getMDString(Record[3]),
2209 case bitc::METADATA_TEMPLATE_TYPE: {
2210 if (Record.size() != 3)
2211 return error("Invalid record");
2213 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2215 (Context, getMDString(Record[1]),
2216 getMDOrNull(Record[2]))),
2220 case bitc::METADATA_TEMPLATE_VALUE: {
2221 if (Record.size() != 5)
2222 return error("Invalid record");
2224 MDValueList.assignValue(
2225 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2226 (Context, Record[1], getMDString(Record[2]),
2227 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2231 case bitc::METADATA_GLOBAL_VAR: {
2232 if (Record.size() != 11)
2233 return error("Invalid record");
2235 MDValueList.assignValue(
2236 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2237 (Context, getMDOrNull(Record[1]),
2238 getMDString(Record[2]), getMDString(Record[3]),
2239 getMDOrNull(Record[4]), Record[5],
2240 getMDOrNull(Record[6]), Record[7], Record[8],
2241 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2245 case bitc::METADATA_LOCAL_VAR: {
2246 // 10th field is for the obseleted 'inlinedAt:' field.
2247 if (Record.size() < 8 || Record.size() > 10)
2248 return error("Invalid record");
2250 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2251 // DW_TAG_arg_variable.
2252 bool HasTag = Record.size() > 8;
2253 MDValueList.assignValue(
2254 GET_OR_DISTINCT(DILocalVariable, Record[0],
2255 (Context, getMDOrNull(Record[1 + HasTag]),
2256 getMDString(Record[2 + HasTag]),
2257 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2258 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2259 Record[7 + HasTag])),
2263 case bitc::METADATA_EXPRESSION: {
2264 if (Record.size() < 1)
2265 return error("Invalid record");
2267 MDValueList.assignValue(
2268 GET_OR_DISTINCT(DIExpression, Record[0],
2269 (Context, makeArrayRef(Record).slice(1))),
2273 case bitc::METADATA_OBJC_PROPERTY: {
2274 if (Record.size() != 8)
2275 return error("Invalid record");
2277 MDValueList.assignValue(
2278 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2279 (Context, getMDString(Record[1]),
2280 getMDOrNull(Record[2]), Record[3],
2281 getMDString(Record[4]), getMDString(Record[5]),
2282 Record[6], getMDOrNull(Record[7]))),
2286 case bitc::METADATA_IMPORTED_ENTITY: {
2287 if (Record.size() != 6)
2288 return error("Invalid record");
2290 MDValueList.assignValue(
2291 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2292 (Context, Record[1], getMDOrNull(Record[2]),
2293 getMDOrNull(Record[3]), Record[4],
2294 getMDString(Record[5]))),
2298 case bitc::METADATA_STRING: {
2299 std::string String(Record.begin(), Record.end());
2300 llvm::UpgradeMDStringConstant(String);
2301 Metadata *MD = MDString::get(Context, String);
2302 MDValueList.assignValue(MD, NextMDValueNo++);
2305 case bitc::METADATA_KIND: {
2306 if (Record.size() < 2)
2307 return error("Invalid record");
2309 unsigned Kind = Record[0];
2310 SmallString<8> Name(Record.begin()+1, Record.end());
2312 unsigned NewKind = TheModule->getMDKindID(Name.str());
2313 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2314 return error("Conflicting METADATA_KIND records");
2319 #undef GET_OR_DISTINCT
2322 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2324 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2329 // There is no such thing as -0 with integers. "-0" really means MININT.
2333 /// Resolve all of the initializers for global values and aliases that we can.
2334 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2335 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2336 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2337 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2338 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2339 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2341 GlobalInitWorklist.swap(GlobalInits);
2342 AliasInitWorklist.swap(AliasInits);
2343 FunctionPrefixWorklist.swap(FunctionPrefixes);
2344 FunctionPrologueWorklist.swap(FunctionPrologues);
2345 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2347 while (!GlobalInitWorklist.empty()) {
2348 unsigned ValID = GlobalInitWorklist.back().second;
2349 if (ValID >= ValueList.size()) {
2350 // Not ready to resolve this yet, it requires something later in the file.
2351 GlobalInits.push_back(GlobalInitWorklist.back());
2353 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2354 GlobalInitWorklist.back().first->setInitializer(C);
2356 return error("Expected a constant");
2358 GlobalInitWorklist.pop_back();
2361 while (!AliasInitWorklist.empty()) {
2362 unsigned ValID = AliasInitWorklist.back().second;
2363 if (ValID >= ValueList.size()) {
2364 AliasInits.push_back(AliasInitWorklist.back());
2366 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2368 return error("Expected a constant");
2369 GlobalAlias *Alias = AliasInitWorklist.back().first;
2370 if (C->getType() != Alias->getType())
2371 return error("Alias and aliasee types don't match");
2372 Alias->setAliasee(C);
2374 AliasInitWorklist.pop_back();
2377 while (!FunctionPrefixWorklist.empty()) {
2378 unsigned ValID = FunctionPrefixWorklist.back().second;
2379 if (ValID >= ValueList.size()) {
2380 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2382 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2383 FunctionPrefixWorklist.back().first->setPrefixData(C);
2385 return error("Expected a constant");
2387 FunctionPrefixWorklist.pop_back();
2390 while (!FunctionPrologueWorklist.empty()) {
2391 unsigned ValID = FunctionPrologueWorklist.back().second;
2392 if (ValID >= ValueList.size()) {
2393 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2395 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2396 FunctionPrologueWorklist.back().first->setPrologueData(C);
2398 return error("Expected a constant");
2400 FunctionPrologueWorklist.pop_back();
2403 while (!FunctionPersonalityFnWorklist.empty()) {
2404 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2405 if (ValID >= ValueList.size()) {
2406 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2408 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2409 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2411 return error("Expected a constant");
2413 FunctionPersonalityFnWorklist.pop_back();
2416 return std::error_code();
2419 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2420 SmallVector<uint64_t, 8> Words(Vals.size());
2421 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2422 BitcodeReader::decodeSignRotatedValue);
2424 return APInt(TypeBits, Words);
2427 std::error_code BitcodeReader::parseConstants() {
2428 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2429 return error("Invalid record");
2431 SmallVector<uint64_t, 64> Record;
2433 // Read all the records for this value table.
2434 Type *CurTy = Type::getInt32Ty(Context);
2435 unsigned NextCstNo = ValueList.size();
2437 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2439 switch (Entry.Kind) {
2440 case BitstreamEntry::SubBlock: // Handled for us already.
2441 case BitstreamEntry::Error:
2442 return error("Malformed block");
2443 case BitstreamEntry::EndBlock:
2444 if (NextCstNo != ValueList.size())
2445 return error("Invalid ronstant reference");
2447 // Once all the constants have been read, go through and resolve forward
2449 ValueList.resolveConstantForwardRefs();
2450 return std::error_code();
2451 case BitstreamEntry::Record:
2452 // The interesting case.
2459 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2461 default: // Default behavior: unknown constant
2462 case bitc::CST_CODE_UNDEF: // UNDEF
2463 V = UndefValue::get(CurTy);
2465 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2467 return error("Invalid record");
2468 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2469 return error("Invalid record");
2470 CurTy = TypeList[Record[0]];
2471 continue; // Skip the ValueList manipulation.
2472 case bitc::CST_CODE_NULL: // NULL
2473 V = Constant::getNullValue(CurTy);
2475 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2476 if (!CurTy->isIntegerTy() || Record.empty())
2477 return error("Invalid record");
2478 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2480 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2481 if (!CurTy->isIntegerTy() || Record.empty())
2482 return error("Invalid record");
2485 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2486 V = ConstantInt::get(Context, VInt);
2490 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2492 return error("Invalid record");
2493 if (CurTy->isHalfTy())
2494 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2495 APInt(16, (uint16_t)Record[0])));
2496 else if (CurTy->isFloatTy())
2497 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2498 APInt(32, (uint32_t)Record[0])));
2499 else if (CurTy->isDoubleTy())
2500 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2501 APInt(64, Record[0])));
2502 else if (CurTy->isX86_FP80Ty()) {
2503 // Bits are not stored the same way as a normal i80 APInt, compensate.
2504 uint64_t Rearrange[2];
2505 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2506 Rearrange[1] = Record[0] >> 48;
2507 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2508 APInt(80, Rearrange)));
2509 } else if (CurTy->isFP128Ty())
2510 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2511 APInt(128, Record)));
2512 else if (CurTy->isPPC_FP128Ty())
2513 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2514 APInt(128, Record)));
2516 V = UndefValue::get(CurTy);
2520 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2522 return error("Invalid record");
2524 unsigned Size = Record.size();
2525 SmallVector<Constant*, 16> Elts;
2527 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2528 for (unsigned i = 0; i != Size; ++i)
2529 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2530 STy->getElementType(i)));
2531 V = ConstantStruct::get(STy, Elts);
2532 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2533 Type *EltTy = ATy->getElementType();
2534 for (unsigned i = 0; i != Size; ++i)
2535 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2536 V = ConstantArray::get(ATy, Elts);
2537 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2538 Type *EltTy = VTy->getElementType();
2539 for (unsigned i = 0; i != Size; ++i)
2540 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2541 V = ConstantVector::get(Elts);
2543 V = UndefValue::get(CurTy);
2547 case bitc::CST_CODE_STRING: // STRING: [values]
2548 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2550 return error("Invalid record");
2552 SmallString<16> Elts(Record.begin(), Record.end());
2553 V = ConstantDataArray::getString(Context, Elts,
2554 BitCode == bitc::CST_CODE_CSTRING);
2557 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2559 return error("Invalid record");
2561 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2562 unsigned Size = Record.size();
2564 if (EltTy->isIntegerTy(8)) {
2565 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2566 if (isa<VectorType>(CurTy))
2567 V = ConstantDataVector::get(Context, Elts);
2569 V = ConstantDataArray::get(Context, Elts);
2570 } else if (EltTy->isIntegerTy(16)) {
2571 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2572 if (isa<VectorType>(CurTy))
2573 V = ConstantDataVector::get(Context, Elts);
2575 V = ConstantDataArray::get(Context, Elts);
2576 } else if (EltTy->isIntegerTy(32)) {
2577 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2578 if (isa<VectorType>(CurTy))
2579 V = ConstantDataVector::get(Context, Elts);
2581 V = ConstantDataArray::get(Context, Elts);
2582 } else if (EltTy->isIntegerTy(64)) {
2583 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2584 if (isa<VectorType>(CurTy))
2585 V = ConstantDataVector::get(Context, Elts);
2587 V = ConstantDataArray::get(Context, Elts);
2588 } else if (EltTy->isFloatTy()) {
2589 SmallVector<float, 16> Elts(Size);
2590 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2591 if (isa<VectorType>(CurTy))
2592 V = ConstantDataVector::get(Context, Elts);
2594 V = ConstantDataArray::get(Context, Elts);
2595 } else if (EltTy->isDoubleTy()) {
2596 SmallVector<double, 16> Elts(Size);
2597 std::transform(Record.begin(), Record.end(), Elts.begin(),
2599 if (isa<VectorType>(CurTy))
2600 V = ConstantDataVector::get(Context, Elts);
2602 V = ConstantDataArray::get(Context, Elts);
2604 return error("Invalid type for value");
2609 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2610 if (Record.size() < 3)
2611 return error("Invalid record");
2612 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2614 V = UndefValue::get(CurTy); // Unknown binop.
2616 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2617 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2619 if (Record.size() >= 4) {
2620 if (Opc == Instruction::Add ||
2621 Opc == Instruction::Sub ||
2622 Opc == Instruction::Mul ||
2623 Opc == Instruction::Shl) {
2624 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2625 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2626 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2627 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2628 } else if (Opc == Instruction::SDiv ||
2629 Opc == Instruction::UDiv ||
2630 Opc == Instruction::LShr ||
2631 Opc == Instruction::AShr) {
2632 if (Record[3] & (1 << bitc::PEO_EXACT))
2633 Flags |= SDivOperator::IsExact;
2636 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2640 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2641 if (Record.size() < 3)
2642 return error("Invalid record");
2643 int Opc = getDecodedCastOpcode(Record[0]);
2645 V = UndefValue::get(CurTy); // Unknown cast.
2647 Type *OpTy = getTypeByID(Record[1]);
2649 return error("Invalid record");
2650 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2651 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2652 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2656 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2657 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2659 Type *PointeeType = nullptr;
2660 if (Record.size() % 2)
2661 PointeeType = getTypeByID(Record[OpNum++]);
2662 SmallVector<Constant*, 16> Elts;
2663 while (OpNum != Record.size()) {
2664 Type *ElTy = getTypeByID(Record[OpNum++]);
2666 return error("Invalid record");
2667 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2672 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2674 return error("Explicit gep operator type does not match pointee type "
2675 "of pointer operand");
2677 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2678 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2680 bitc::CST_CODE_CE_INBOUNDS_GEP);
2683 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2684 if (Record.size() < 3)
2685 return error("Invalid record");
2687 Type *SelectorTy = Type::getInt1Ty(Context);
2689 // The selector might be an i1 or an <n x i1>
2690 // Get the type from the ValueList before getting a forward ref.
2691 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2692 if (Value *V = ValueList[Record[0]])
2693 if (SelectorTy != V->getType())
2694 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2696 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2698 ValueList.getConstantFwdRef(Record[1],CurTy),
2699 ValueList.getConstantFwdRef(Record[2],CurTy));
2702 case bitc::CST_CODE_CE_EXTRACTELT
2703 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2704 if (Record.size() < 3)
2705 return error("Invalid record");
2707 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2709 return error("Invalid record");
2710 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2711 Constant *Op1 = nullptr;
2712 if (Record.size() == 4) {
2713 Type *IdxTy = getTypeByID(Record[2]);
2715 return error("Invalid record");
2716 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2717 } else // TODO: Remove with llvm 4.0
2718 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2720 return error("Invalid record");
2721 V = ConstantExpr::getExtractElement(Op0, Op1);
2724 case bitc::CST_CODE_CE_INSERTELT
2725 : { // CE_INSERTELT: [opval, opval, opty, opval]
2726 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2727 if (Record.size() < 3 || !OpTy)
2728 return error("Invalid record");
2729 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2730 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2731 OpTy->getElementType());
2732 Constant *Op2 = nullptr;
2733 if (Record.size() == 4) {
2734 Type *IdxTy = getTypeByID(Record[2]);
2736 return error("Invalid record");
2737 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2738 } else // TODO: Remove with llvm 4.0
2739 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2741 return error("Invalid record");
2742 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2745 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2746 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2747 if (Record.size() < 3 || !OpTy)
2748 return error("Invalid record");
2749 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2750 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2751 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2752 OpTy->getNumElements());
2753 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2754 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2757 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2758 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2760 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2761 if (Record.size() < 4 || !RTy || !OpTy)
2762 return error("Invalid record");
2763 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2764 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2765 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2766 RTy->getNumElements());
2767 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2768 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2771 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2772 if (Record.size() < 4)
2773 return error("Invalid record");
2774 Type *OpTy = getTypeByID(Record[0]);
2776 return error("Invalid record");
2777 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2778 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2780 if (OpTy->isFPOrFPVectorTy())
2781 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2783 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2786 // This maintains backward compatibility, pre-asm dialect keywords.
2787 // FIXME: Remove with the 4.0 release.
2788 case bitc::CST_CODE_INLINEASM_OLD: {
2789 if (Record.size() < 2)
2790 return error("Invalid record");
2791 std::string AsmStr, ConstrStr;
2792 bool HasSideEffects = Record[0] & 1;
2793 bool IsAlignStack = Record[0] >> 1;
2794 unsigned AsmStrSize = Record[1];
2795 if (2+AsmStrSize >= Record.size())
2796 return error("Invalid record");
2797 unsigned ConstStrSize = Record[2+AsmStrSize];
2798 if (3+AsmStrSize+ConstStrSize > Record.size())
2799 return error("Invalid record");
2801 for (unsigned i = 0; i != AsmStrSize; ++i)
2802 AsmStr += (char)Record[2+i];
2803 for (unsigned i = 0; i != ConstStrSize; ++i)
2804 ConstrStr += (char)Record[3+AsmStrSize+i];
2805 PointerType *PTy = cast<PointerType>(CurTy);
2806 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2807 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2810 // This version adds support for the asm dialect keywords (e.g.,
2812 case bitc::CST_CODE_INLINEASM: {
2813 if (Record.size() < 2)
2814 return error("Invalid record");
2815 std::string AsmStr, ConstrStr;
2816 bool HasSideEffects = Record[0] & 1;
2817 bool IsAlignStack = (Record[0] >> 1) & 1;
2818 unsigned AsmDialect = Record[0] >> 2;
2819 unsigned AsmStrSize = Record[1];
2820 if (2+AsmStrSize >= Record.size())
2821 return error("Invalid record");
2822 unsigned ConstStrSize = Record[2+AsmStrSize];
2823 if (3+AsmStrSize+ConstStrSize > Record.size())
2824 return error("Invalid record");
2826 for (unsigned i = 0; i != AsmStrSize; ++i)
2827 AsmStr += (char)Record[2+i];
2828 for (unsigned i = 0; i != ConstStrSize; ++i)
2829 ConstrStr += (char)Record[3+AsmStrSize+i];
2830 PointerType *PTy = cast<PointerType>(CurTy);
2831 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2832 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2833 InlineAsm::AsmDialect(AsmDialect));
2836 case bitc::CST_CODE_BLOCKADDRESS:{
2837 if (Record.size() < 3)
2838 return error("Invalid record");
2839 Type *FnTy = getTypeByID(Record[0]);
2841 return error("Invalid record");
2843 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2845 return error("Invalid record");
2847 // Don't let Fn get dematerialized.
2848 BlockAddressesTaken.insert(Fn);
2850 // If the function is already parsed we can insert the block address right
2853 unsigned BBID = Record[2];
2855 // Invalid reference to entry block.
2856 return error("Invalid ID");
2858 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2859 for (size_t I = 0, E = BBID; I != E; ++I) {
2861 return error("Invalid ID");
2866 // Otherwise insert a placeholder and remember it so it can be inserted
2867 // when the function is parsed.
2868 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2870 BasicBlockFwdRefQueue.push_back(Fn);
2871 if (FwdBBs.size() < BBID + 1)
2872 FwdBBs.resize(BBID + 1);
2874 FwdBBs[BBID] = BasicBlock::Create(Context);
2877 V = BlockAddress::get(Fn, BB);
2882 if (ValueList.assignValue(V, NextCstNo))
2883 return error("Invalid forward reference");
2888 std::error_code BitcodeReader::parseUseLists() {
2889 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2890 return error("Invalid record");
2892 // Read all the records.
2893 SmallVector<uint64_t, 64> Record;
2895 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2897 switch (Entry.Kind) {
2898 case BitstreamEntry::SubBlock: // Handled for us already.
2899 case BitstreamEntry::Error:
2900 return error("Malformed block");
2901 case BitstreamEntry::EndBlock:
2902 return std::error_code();
2903 case BitstreamEntry::Record:
2904 // The interesting case.
2908 // Read a use list record.
2911 switch (Stream.readRecord(Entry.ID, Record)) {
2912 default: // Default behavior: unknown type.
2914 case bitc::USELIST_CODE_BB:
2917 case bitc::USELIST_CODE_DEFAULT: {
2918 unsigned RecordLength = Record.size();
2919 if (RecordLength < 3)
2920 // Records should have at least an ID and two indexes.
2921 return error("Invalid record");
2922 unsigned ID = Record.back();
2927 assert(ID < FunctionBBs.size() && "Basic block not found");
2928 V = FunctionBBs[ID];
2931 unsigned NumUses = 0;
2932 SmallDenseMap<const Use *, unsigned, 16> Order;
2933 for (const Use &U : V->uses()) {
2934 if (++NumUses > Record.size())
2936 Order[&U] = Record[NumUses - 1];
2938 if (Order.size() != Record.size() || NumUses > Record.size())
2939 // Mismatches can happen if the functions are being materialized lazily
2940 // (out-of-order), or a value has been upgraded.
2943 V->sortUseList([&](const Use &L, const Use &R) {
2944 return Order.lookup(&L) < Order.lookup(&R);
2952 /// When we see the block for metadata, remember where it is and then skip it.
2953 /// This lets us lazily deserialize the metadata.
2954 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2955 // Save the current stream state.
2956 uint64_t CurBit = Stream.GetCurrentBitNo();
2957 DeferredMetadataInfo.push_back(CurBit);
2959 // Skip over the block for now.
2960 if (Stream.SkipBlock())
2961 return error("Invalid record");
2962 return std::error_code();
2965 std::error_code BitcodeReader::materializeMetadata() {
2966 for (uint64_t BitPos : DeferredMetadataInfo) {
2967 // Move the bit stream to the saved position.
2968 Stream.JumpToBit(BitPos);
2969 if (std::error_code EC = parseMetadata())
2972 DeferredMetadataInfo.clear();
2973 return std::error_code();
2976 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2978 /// When we see the block for a function body, remember where it is and then
2979 /// skip it. This lets us lazily deserialize the functions.
2980 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2981 // Get the function we are talking about.
2982 if (FunctionsWithBodies.empty())
2983 return error("Insufficient function protos");
2985 Function *Fn = FunctionsWithBodies.back();
2986 FunctionsWithBodies.pop_back();
2988 // Save the current stream state.
2989 uint64_t CurBit = Stream.GetCurrentBitNo();
2990 DeferredFunctionInfo[Fn] = CurBit;
2992 // Skip over the function block for now.
2993 if (Stream.SkipBlock())
2994 return error("Invalid record");
2995 return std::error_code();
2998 std::error_code BitcodeReader::globalCleanup() {
2999 // Patch the initializers for globals and aliases up.
3000 resolveGlobalAndAliasInits();
3001 if (!GlobalInits.empty() || !AliasInits.empty())
3002 return error("Malformed global initializer set");
3004 // Look for intrinsic functions which need to be upgraded at some point
3005 for (Function &F : *TheModule) {
3007 if (UpgradeIntrinsicFunction(&F, NewFn))
3008 UpgradedIntrinsics[&F] = NewFn;
3011 // Look for global variables which need to be renamed.
3012 for (GlobalVariable &GV : TheModule->globals())
3013 UpgradeGlobalVariable(&GV);
3015 // Force deallocation of memory for these vectors to favor the client that
3016 // want lazy deserialization.
3017 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3018 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3019 return std::error_code();
3022 std::error_code BitcodeReader::parseModule(bool Resume,
3023 bool ShouldLazyLoadMetadata) {
3025 Stream.JumpToBit(NextUnreadBit);
3026 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3027 return error("Invalid record");
3029 SmallVector<uint64_t, 64> Record;
3030 std::vector<std::string> SectionTable;
3031 std::vector<std::string> GCTable;
3033 // Read all the records for this module.
3035 BitstreamEntry Entry = Stream.advance();
3037 switch (Entry.Kind) {
3038 case BitstreamEntry::Error:
3039 return error("Malformed block");
3040 case BitstreamEntry::EndBlock:
3041 return globalCleanup();
3043 case BitstreamEntry::SubBlock:
3045 default: // Skip unknown content.
3046 if (Stream.SkipBlock())
3047 return error("Invalid record");
3049 case bitc::BLOCKINFO_BLOCK_ID:
3050 if (Stream.ReadBlockInfoBlock())
3051 return error("Malformed block");
3053 case bitc::PARAMATTR_BLOCK_ID:
3054 if (std::error_code EC = parseAttributeBlock())
3057 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3058 if (std::error_code EC = parseAttributeGroupBlock())
3061 case bitc::TYPE_BLOCK_ID_NEW:
3062 if (std::error_code EC = parseTypeTable())
3065 case bitc::VALUE_SYMTAB_BLOCK_ID:
3066 if (!SeenValueSymbolTable) {
3067 // Either this is an old form VST without function index and an
3068 // associated VST forward declaration record (which would have caused
3069 // the VST to be jumped to and parsed before it was encountered
3070 // normally in the stream), or there were no function blocks to
3071 // trigger an earlier parsing of the VST.
3072 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3073 if (std::error_code EC = parseValueSymbolTable())
3075 SeenValueSymbolTable = true;
3077 // We must have had a VST forward declaration record, which caused
3078 // the parser to jump to and parse the VST earlier.
3079 assert(VSTOffset > 0);
3080 if (Stream.SkipBlock())
3081 return error("Invalid record");
3084 case bitc::CONSTANTS_BLOCK_ID:
3085 if (std::error_code EC = parseConstants())
3087 if (std::error_code EC = resolveGlobalAndAliasInits())
3090 case bitc::METADATA_BLOCK_ID:
3091 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3092 if (std::error_code EC = rememberAndSkipMetadata())
3096 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3097 if (std::error_code EC = parseMetadata())
3100 case bitc::FUNCTION_BLOCK_ID:
3101 // If this is the first function body we've seen, reverse the
3102 // FunctionsWithBodies list.
3103 if (!SeenFirstFunctionBody) {
3104 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3105 if (std::error_code EC = globalCleanup())
3107 SeenFirstFunctionBody = true;
3110 if (VSTOffset > 0) {
3111 // If we have a VST forward declaration record, make sure we
3112 // parse the VST now if we haven't already. It is needed to
3113 // set up the DeferredFunctionInfo vector for lazy reading.
3114 if (!SeenValueSymbolTable) {
3115 if (std::error_code EC =
3116 BitcodeReader::parseValueSymbolTable(VSTOffset))
3118 SeenValueSymbolTable = true;
3119 return std::error_code();
3121 // If we have a VST forward declaration record, but have already
3122 // parsed the VST (just above, when the first function body was
3123 // encountered here), then we are resuming the parse after
3124 // materializing functions. The NextUnreadBit points to the start
3125 // of the last function block recorded in the VST (set when
3126 // parsing the VST function entries). Skip it.
3127 if (Stream.SkipBlock())
3128 return error("Invalid record");
3133 // Support older bitcode files that did not have the function
3134 // index in the VST, nor a VST forward declaration record.
3135 // Build the DeferredFunctionInfo vector on the fly.
3136 if (std::error_code EC = rememberAndSkipFunctionBody())
3138 // Suspend parsing when we reach the function bodies. Subsequent
3139 // materialization calls will resume it when necessary. If the bitcode
3140 // file is old, the symbol table will be at the end instead and will not
3141 // have been seen yet. In this case, just finish the parse now.
3142 if (SeenValueSymbolTable) {
3143 NextUnreadBit = Stream.GetCurrentBitNo();
3144 return std::error_code();
3147 case bitc::USELIST_BLOCK_ID:
3148 if (std::error_code EC = parseUseLists())
3151 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3152 if (std::error_code EC = parseOperandBundleTags())
3158 case BitstreamEntry::Record:
3159 // The interesting case.
3165 auto BitCode = Stream.readRecord(Entry.ID, Record);
3167 default: break; // Default behavior, ignore unknown content.
3168 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3169 if (Record.size() < 1)
3170 return error("Invalid record");
3171 // Only version #0 and #1 are supported so far.
3172 unsigned module_version = Record[0];
3173 switch (module_version) {
3175 return error("Invalid value");
3177 UseRelativeIDs = false;
3180 UseRelativeIDs = true;
3185 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3187 if (convertToString(Record, 0, S))
3188 return error("Invalid record");
3189 TheModule->setTargetTriple(S);
3192 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3194 if (convertToString(Record, 0, S))
3195 return error("Invalid record");
3196 TheModule->setDataLayout(S);
3199 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3201 if (convertToString(Record, 0, S))
3202 return error("Invalid record");
3203 TheModule->setModuleInlineAsm(S);
3206 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3207 // FIXME: Remove in 4.0.
3209 if (convertToString(Record, 0, S))
3210 return error("Invalid record");
3214 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3216 if (convertToString(Record, 0, S))
3217 return error("Invalid record");
3218 SectionTable.push_back(S);
3221 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3223 if (convertToString(Record, 0, S))
3224 return error("Invalid record");
3225 GCTable.push_back(S);
3228 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3229 if (Record.size() < 2)
3230 return error("Invalid record");
3231 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3232 unsigned ComdatNameSize = Record[1];
3233 std::string ComdatName;
3234 ComdatName.reserve(ComdatNameSize);
3235 for (unsigned i = 0; i != ComdatNameSize; ++i)
3236 ComdatName += (char)Record[2 + i];
3237 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3238 C->setSelectionKind(SK);
3239 ComdatList.push_back(C);
3242 // GLOBALVAR: [pointer type, isconst, initid,
3243 // linkage, alignment, section, visibility, threadlocal,
3244 // unnamed_addr, externally_initialized, dllstorageclass,
3246 case bitc::MODULE_CODE_GLOBALVAR: {
3247 if (Record.size() < 6)
3248 return error("Invalid record");
3249 Type *Ty = getTypeByID(Record[0]);
3251 return error("Invalid record");
3252 bool isConstant = Record[1] & 1;
3253 bool explicitType = Record[1] & 2;
3254 unsigned AddressSpace;
3256 AddressSpace = Record[1] >> 2;
3258 if (!Ty->isPointerTy())
3259 return error("Invalid type for value");
3260 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3261 Ty = cast<PointerType>(Ty)->getElementType();
3264 uint64_t RawLinkage = Record[3];
3265 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3267 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3269 std::string Section;
3271 if (Record[5]-1 >= SectionTable.size())
3272 return error("Invalid ID");
3273 Section = SectionTable[Record[5]-1];
3275 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3276 // Local linkage must have default visibility.
3277 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3278 // FIXME: Change to an error if non-default in 4.0.
3279 Visibility = getDecodedVisibility(Record[6]);
3281 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3282 if (Record.size() > 7)
3283 TLM = getDecodedThreadLocalMode(Record[7]);
3285 bool UnnamedAddr = false;
3286 if (Record.size() > 8)
3287 UnnamedAddr = Record[8];
3289 bool ExternallyInitialized = false;
3290 if (Record.size() > 9)
3291 ExternallyInitialized = Record[9];
3293 GlobalVariable *NewGV =
3294 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3295 TLM, AddressSpace, ExternallyInitialized);
3296 NewGV->setAlignment(Alignment);
3297 if (!Section.empty())
3298 NewGV->setSection(Section);
3299 NewGV->setVisibility(Visibility);
3300 NewGV->setUnnamedAddr(UnnamedAddr);
3302 if (Record.size() > 10)
3303 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3305 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3307 ValueList.push_back(NewGV);
3309 // Remember which value to use for the global initializer.
3310 if (unsigned InitID = Record[2])
3311 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3313 if (Record.size() > 11) {
3314 if (unsigned ComdatID = Record[11]) {
3315 if (ComdatID > ComdatList.size())
3316 return error("Invalid global variable comdat ID");
3317 NewGV->setComdat(ComdatList[ComdatID - 1]);
3319 } else if (hasImplicitComdat(RawLinkage)) {
3320 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3324 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3325 // alignment, section, visibility, gc, unnamed_addr,
3326 // prologuedata, dllstorageclass, comdat, prefixdata]
3327 case bitc::MODULE_CODE_FUNCTION: {
3328 if (Record.size() < 8)
3329 return error("Invalid record");
3330 Type *Ty = getTypeByID(Record[0]);
3332 return error("Invalid record");
3333 if (auto *PTy = dyn_cast<PointerType>(Ty))
3334 Ty = PTy->getElementType();
3335 auto *FTy = dyn_cast<FunctionType>(Ty);
3337 return error("Invalid type for value");
3339 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3342 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
3343 bool isProto = Record[2];
3344 uint64_t RawLinkage = Record[3];
3345 Func->setLinkage(getDecodedLinkage(RawLinkage));
3346 Func->setAttributes(getAttributes(Record[4]));
3349 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3351 Func->setAlignment(Alignment);
3353 if (Record[6]-1 >= SectionTable.size())
3354 return error("Invalid ID");
3355 Func->setSection(SectionTable[Record[6]-1]);
3357 // Local linkage must have default visibility.
3358 if (!Func->hasLocalLinkage())
3359 // FIXME: Change to an error if non-default in 4.0.
3360 Func->setVisibility(getDecodedVisibility(Record[7]));
3361 if (Record.size() > 8 && Record[8]) {
3362 if (Record[8]-1 >= GCTable.size())
3363 return error("Invalid ID");
3364 Func->setGC(GCTable[Record[8]-1].c_str());
3366 bool UnnamedAddr = false;
3367 if (Record.size() > 9)
3368 UnnamedAddr = Record[9];
3369 Func->setUnnamedAddr(UnnamedAddr);
3370 if (Record.size() > 10 && Record[10] != 0)
3371 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3373 if (Record.size() > 11)
3374 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3376 upgradeDLLImportExportLinkage(Func, RawLinkage);
3378 if (Record.size() > 12) {
3379 if (unsigned ComdatID = Record[12]) {
3380 if (ComdatID > ComdatList.size())
3381 return error("Invalid function comdat ID");
3382 Func->setComdat(ComdatList[ComdatID - 1]);
3384 } else if (hasImplicitComdat(RawLinkage)) {
3385 Func->setComdat(reinterpret_cast<Comdat *>(1));
3388 if (Record.size() > 13 && Record[13] != 0)
3389 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3391 if (Record.size() > 14 && Record[14] != 0)
3392 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3394 ValueList.push_back(Func);
3396 // If this is a function with a body, remember the prototype we are
3397 // creating now, so that we can match up the body with them later.
3399 Func->setIsMaterializable(true);
3400 FunctionsWithBodies.push_back(Func);
3401 DeferredFunctionInfo[Func] = 0;
3405 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3406 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3407 case bitc::MODULE_CODE_ALIAS:
3408 case bitc::MODULE_CODE_ALIAS_OLD: {
3409 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3410 if (Record.size() < (3 + (unsigned)NewRecord))
3411 return error("Invalid record");
3413 Type *Ty = getTypeByID(Record[OpNum++]);
3415 return error("Invalid record");
3419 auto *PTy = dyn_cast<PointerType>(Ty);
3421 return error("Invalid type for value");
3422 Ty = PTy->getElementType();
3423 AddrSpace = PTy->getAddressSpace();
3425 AddrSpace = Record[OpNum++];
3428 auto Val = Record[OpNum++];
3429 auto Linkage = Record[OpNum++];
3430 auto *NewGA = GlobalAlias::create(
3431 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3432 // Old bitcode files didn't have visibility field.
3433 // Local linkage must have default visibility.
3434 if (OpNum != Record.size()) {
3435 auto VisInd = OpNum++;
3436 if (!NewGA->hasLocalLinkage())
3437 // FIXME: Change to an error if non-default in 4.0.
3438 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3440 if (OpNum != Record.size())
3441 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3443 upgradeDLLImportExportLinkage(NewGA, Linkage);
3444 if (OpNum != Record.size())
3445 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3446 if (OpNum != Record.size())
3447 NewGA->setUnnamedAddr(Record[OpNum++]);
3448 ValueList.push_back(NewGA);
3449 AliasInits.push_back(std::make_pair(NewGA, Val));
3452 /// MODULE_CODE_PURGEVALS: [numvals]
3453 case bitc::MODULE_CODE_PURGEVALS:
3454 // Trim down the value list to the specified size.
3455 if (Record.size() < 1 || Record[0] > ValueList.size())
3456 return error("Invalid record");
3457 ValueList.shrinkTo(Record[0]);
3459 /// MODULE_CODE_VSTOFFSET: [offset]
3460 case bitc::MODULE_CODE_VSTOFFSET:
3461 if (Record.size() < 1)
3462 return error("Invalid record");
3463 VSTOffset = Record[0];
3470 /// Helper to read the header common to all bitcode files.
3471 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3472 // Sniff for the signature.
3473 if (Stream.Read(8) != 'B' ||
3474 Stream.Read(8) != 'C' ||
3475 Stream.Read(4) != 0x0 ||
3476 Stream.Read(4) != 0xC ||
3477 Stream.Read(4) != 0xE ||
3478 Stream.Read(4) != 0xD)
3484 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3485 Module *M, bool ShouldLazyLoadMetadata) {
3488 if (std::error_code EC = initStream(std::move(Streamer)))
3491 // Sniff for the signature.
3492 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
3494 // We expect a number of well-defined blocks, though we don't necessarily
3495 // need to understand them all.
3497 if (Stream.AtEndOfStream()) {
3498 // We didn't really read a proper Module.
3499 return error("Malformed IR file");
3502 BitstreamEntry Entry =
3503 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3505 if (Entry.Kind != BitstreamEntry::SubBlock)
3506 return error("Malformed block");
3508 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3509 return parseModule(false, ShouldLazyLoadMetadata);
3511 if (Stream.SkipBlock())
3512 return error("Invalid record");
3516 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3517 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3518 return error("Invalid record");
3520 SmallVector<uint64_t, 64> Record;
3523 // Read all the records for this module.
3525 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3527 switch (Entry.Kind) {
3528 case BitstreamEntry::SubBlock: // Handled for us already.
3529 case BitstreamEntry::Error:
3530 return error("Malformed block");
3531 case BitstreamEntry::EndBlock:
3533 case BitstreamEntry::Record:
3534 // The interesting case.
3539 switch (Stream.readRecord(Entry.ID, Record)) {
3540 default: break; // Default behavior, ignore unknown content.
3541 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3543 if (convertToString(Record, 0, S))
3544 return error("Invalid record");
3551 llvm_unreachable("Exit infinite loop");
3554 ErrorOr<std::string> BitcodeReader::parseTriple() {
3555 if (std::error_code EC = initStream(nullptr))
3558 // Sniff for the signature.
3559 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
3561 // We expect a number of well-defined blocks, though we don't necessarily
3562 // need to understand them all.
3564 BitstreamEntry Entry = Stream.advance();
3566 switch (Entry.Kind) {
3567 case BitstreamEntry::Error:
3568 return error("Malformed block");
3569 case BitstreamEntry::EndBlock:
3570 return std::error_code();
3572 case BitstreamEntry::SubBlock:
3573 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3574 return parseModuleTriple();
3576 // Ignore other sub-blocks.
3577 if (Stream.SkipBlock())
3578 return error("Malformed block");
3581 case BitstreamEntry::Record:
3582 Stream.skipRecord(Entry.ID);
3588 /// Parse metadata attachments.
3589 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3590 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3591 return error("Invalid record");
3593 SmallVector<uint64_t, 64> Record;
3595 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3597 switch (Entry.Kind) {
3598 case BitstreamEntry::SubBlock: // Handled for us already.
3599 case BitstreamEntry::Error:
3600 return error("Malformed block");
3601 case BitstreamEntry::EndBlock:
3602 return std::error_code();
3603 case BitstreamEntry::Record:
3604 // The interesting case.
3608 // Read a metadata attachment record.
3610 switch (Stream.readRecord(Entry.ID, Record)) {
3611 default: // Default behavior: ignore.
3613 case bitc::METADATA_ATTACHMENT: {
3614 unsigned RecordLength = Record.size();
3616 return error("Invalid record");
3617 if (RecordLength % 2 == 0) {
3618 // A function attachment.
3619 for (unsigned I = 0; I != RecordLength; I += 2) {
3620 auto K = MDKindMap.find(Record[I]);
3621 if (K == MDKindMap.end())
3622 return error("Invalid ID");
3623 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3624 F.setMetadata(K->second, cast<MDNode>(MD));
3629 // An instruction attachment.
3630 Instruction *Inst = InstructionList[Record[0]];
3631 for (unsigned i = 1; i != RecordLength; i = i+2) {
3632 unsigned Kind = Record[i];
3633 DenseMap<unsigned, unsigned>::iterator I =
3634 MDKindMap.find(Kind);
3635 if (I == MDKindMap.end())
3636 return error("Invalid ID");
3637 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3638 if (isa<LocalAsMetadata>(Node))
3639 // Drop the attachment. This used to be legal, but there's no
3642 Inst->setMetadata(I->second, cast<MDNode>(Node));
3643 if (I->second == LLVMContext::MD_tbaa)
3644 InstsWithTBAATag.push_back(Inst);
3652 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3653 Type *ValType, Type *PtrType) {
3654 if (!isa<PointerType>(PtrType))
3655 return error(DH, "Load/Store operand is not a pointer type");
3656 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3658 if (ValType && ValType != ElemType)
3659 return error(DH, "Explicit load/store type does not match pointee type of "
3661 if (!PointerType::isLoadableOrStorableType(ElemType))
3662 return error(DH, "Cannot load/store from pointer");
3663 return std::error_code();
3666 /// Lazily parse the specified function body block.
3667 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3668 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3669 return error("Invalid record");
3671 InstructionList.clear();
3672 unsigned ModuleValueListSize = ValueList.size();
3673 unsigned ModuleMDValueListSize = MDValueList.size();
3675 // Add all the function arguments to the value table.
3676 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3677 ValueList.push_back(I);
3679 unsigned NextValueNo = ValueList.size();
3680 BasicBlock *CurBB = nullptr;
3681 unsigned CurBBNo = 0;
3684 auto getLastInstruction = [&]() -> Instruction * {
3685 if (CurBB && !CurBB->empty())
3686 return &CurBB->back();
3687 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3688 !FunctionBBs[CurBBNo - 1]->empty())
3689 return &FunctionBBs[CurBBNo - 1]->back();
3693 std::vector<OperandBundleDef> OperandBundles;
3695 // Read all the records.
3696 SmallVector<uint64_t, 64> Record;
3698 BitstreamEntry Entry = Stream.advance();
3700 switch (Entry.Kind) {
3701 case BitstreamEntry::Error:
3702 return error("Malformed block");
3703 case BitstreamEntry::EndBlock:
3704 goto OutOfRecordLoop;
3706 case BitstreamEntry::SubBlock:
3708 default: // Skip unknown content.
3709 if (Stream.SkipBlock())
3710 return error("Invalid record");
3712 case bitc::CONSTANTS_BLOCK_ID:
3713 if (std::error_code EC = parseConstants())
3715 NextValueNo = ValueList.size();
3717 case bitc::VALUE_SYMTAB_BLOCK_ID:
3718 if (std::error_code EC = parseValueSymbolTable())
3721 case bitc::METADATA_ATTACHMENT_ID:
3722 if (std::error_code EC = parseMetadataAttachment(*F))
3725 case bitc::METADATA_BLOCK_ID:
3726 if (std::error_code EC = parseMetadata())
3729 case bitc::USELIST_BLOCK_ID:
3730 if (std::error_code EC = parseUseLists())
3736 case BitstreamEntry::Record:
3737 // The interesting case.
3743 Instruction *I = nullptr;
3744 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3746 default: // Default behavior: reject
3747 return error("Invalid value");
3748 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3749 if (Record.size() < 1 || Record[0] == 0)
3750 return error("Invalid record");
3751 // Create all the basic blocks for the function.
3752 FunctionBBs.resize(Record[0]);
3754 // See if anything took the address of blocks in this function.
3755 auto BBFRI = BasicBlockFwdRefs.find(F);
3756 if (BBFRI == BasicBlockFwdRefs.end()) {
3757 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3758 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3760 auto &BBRefs = BBFRI->second;
3761 // Check for invalid basic block references.
3762 if (BBRefs.size() > FunctionBBs.size())
3763 return error("Invalid ID");
3764 assert(!BBRefs.empty() && "Unexpected empty array");
3765 assert(!BBRefs.front() && "Invalid reference to entry block");
3766 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3768 if (I < RE && BBRefs[I]) {
3769 BBRefs[I]->insertInto(F);
3770 FunctionBBs[I] = BBRefs[I];
3772 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3775 // Erase from the table.
3776 BasicBlockFwdRefs.erase(BBFRI);
3779 CurBB = FunctionBBs[0];
3783 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3784 // This record indicates that the last instruction is at the same
3785 // location as the previous instruction with a location.
3786 I = getLastInstruction();
3789 return error("Invalid record");
3790 I->setDebugLoc(LastLoc);
3794 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3795 I = getLastInstruction();
3796 if (!I || Record.size() < 4)
3797 return error("Invalid record");
3799 unsigned Line = Record[0], Col = Record[1];
3800 unsigned ScopeID = Record[2], IAID = Record[3];
3802 MDNode *Scope = nullptr, *IA = nullptr;
3803 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3804 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3805 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3806 I->setDebugLoc(LastLoc);
3811 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3814 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3815 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3816 OpNum+1 > Record.size())
3817 return error("Invalid record");
3819 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3821 return error("Invalid record");
3822 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3823 InstructionList.push_back(I);
3824 if (OpNum < Record.size()) {
3825 if (Opc == Instruction::Add ||
3826 Opc == Instruction::Sub ||
3827 Opc == Instruction::Mul ||
3828 Opc == Instruction::Shl) {
3829 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3830 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3831 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3832 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3833 } else if (Opc == Instruction::SDiv ||
3834 Opc == Instruction::UDiv ||
3835 Opc == Instruction::LShr ||
3836 Opc == Instruction::AShr) {
3837 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3838 cast<BinaryOperator>(I)->setIsExact(true);
3839 } else if (isa<FPMathOperator>(I)) {
3840 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3842 I->setFastMathFlags(FMF);
3848 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3851 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3852 OpNum+2 != Record.size())
3853 return error("Invalid record");
3855 Type *ResTy = getTypeByID(Record[OpNum]);
3856 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3857 if (Opc == -1 || !ResTy)
3858 return error("Invalid record");
3859 Instruction *Temp = nullptr;
3860 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3862 InstructionList.push_back(Temp);
3863 CurBB->getInstList().push_back(Temp);
3866 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3868 InstructionList.push_back(I);
3871 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3872 case bitc::FUNC_CODE_INST_GEP_OLD:
3873 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3879 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3880 InBounds = Record[OpNum++];
3881 Ty = getTypeByID(Record[OpNum++]);
3883 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3888 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3889 return error("Invalid record");
3892 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3895 cast<SequentialType>(BasePtr->getType()->getScalarType())
3898 "Explicit gep type does not match pointee type of pointer operand");
3900 SmallVector<Value*, 16> GEPIdx;
3901 while (OpNum != Record.size()) {
3903 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3904 return error("Invalid record");
3905 GEPIdx.push_back(Op);
3908 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3910 InstructionList.push_back(I);
3912 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3916 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3917 // EXTRACTVAL: [opty, opval, n x indices]
3920 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3921 return error("Invalid record");
3923 unsigned RecSize = Record.size();
3924 if (OpNum == RecSize)
3925 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3927 SmallVector<unsigned, 4> EXTRACTVALIdx;
3928 Type *CurTy = Agg->getType();
3929 for (; OpNum != RecSize; ++OpNum) {
3930 bool IsArray = CurTy->isArrayTy();
3931 bool IsStruct = CurTy->isStructTy();
3932 uint64_t Index = Record[OpNum];
3934 if (!IsStruct && !IsArray)
3935 return error("EXTRACTVAL: Invalid type");
3936 if ((unsigned)Index != Index)
3937 return error("Invalid value");
3938 if (IsStruct && Index >= CurTy->subtypes().size())
3939 return error("EXTRACTVAL: Invalid struct index");
3940 if (IsArray && Index >= CurTy->getArrayNumElements())
3941 return error("EXTRACTVAL: Invalid array index");
3942 EXTRACTVALIdx.push_back((unsigned)Index);
3945 CurTy = CurTy->subtypes()[Index];
3947 CurTy = CurTy->subtypes()[0];
3950 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3951 InstructionList.push_back(I);
3955 case bitc::FUNC_CODE_INST_INSERTVAL: {
3956 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3959 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3960 return error("Invalid record");
3962 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3963 return error("Invalid record");
3965 unsigned RecSize = Record.size();
3966 if (OpNum == RecSize)
3967 return error("INSERTVAL: Invalid instruction with 0 indices");
3969 SmallVector<unsigned, 4> INSERTVALIdx;
3970 Type *CurTy = Agg->getType();
3971 for (; OpNum != RecSize; ++OpNum) {
3972 bool IsArray = CurTy->isArrayTy();
3973 bool IsStruct = CurTy->isStructTy();
3974 uint64_t Index = Record[OpNum];
3976 if (!IsStruct && !IsArray)
3977 return error("INSERTVAL: Invalid type");
3978 if ((unsigned)Index != Index)
3979 return error("Invalid value");
3980 if (IsStruct && Index >= CurTy->subtypes().size())
3981 return error("INSERTVAL: Invalid struct index");
3982 if (IsArray && Index >= CurTy->getArrayNumElements())
3983 return error("INSERTVAL: Invalid array index");
3985 INSERTVALIdx.push_back((unsigned)Index);
3987 CurTy = CurTy->subtypes()[Index];
3989 CurTy = CurTy->subtypes()[0];
3992 if (CurTy != Val->getType())
3993 return error("Inserted value type doesn't match aggregate type");
3995 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3996 InstructionList.push_back(I);
4000 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4001 // obsolete form of select
4002 // handles select i1 ... in old bitcode
4004 Value *TrueVal, *FalseVal, *Cond;
4005 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4006 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4007 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4008 return error("Invalid record");
4010 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4011 InstructionList.push_back(I);
4015 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4016 // new form of select
4017 // handles select i1 or select [N x i1]
4019 Value *TrueVal, *FalseVal, *Cond;
4020 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4021 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4022 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4023 return error("Invalid record");
4025 // select condition can be either i1 or [N x i1]
4026 if (VectorType* vector_type =
4027 dyn_cast<VectorType>(Cond->getType())) {
4029 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4030 return error("Invalid type for value");
4033 if (Cond->getType() != Type::getInt1Ty(Context))
4034 return error("Invalid type for value");
4037 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4038 InstructionList.push_back(I);
4042 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4045 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4046 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4047 return error("Invalid record");
4048 if (!Vec->getType()->isVectorTy())
4049 return error("Invalid type for value");
4050 I = ExtractElementInst::Create(Vec, Idx);
4051 InstructionList.push_back(I);
4055 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4057 Value *Vec, *Elt, *Idx;
4058 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4059 return error("Invalid record");
4060 if (!Vec->getType()->isVectorTy())
4061 return error("Invalid type for value");
4062 if (popValue(Record, OpNum, NextValueNo,
4063 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4064 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4065 return error("Invalid record");
4066 I = InsertElementInst::Create(Vec, Elt, Idx);
4067 InstructionList.push_back(I);
4071 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4073 Value *Vec1, *Vec2, *Mask;
4074 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4075 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4076 return error("Invalid record");
4078 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4079 return error("Invalid record");
4080 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4081 return error("Invalid type for value");
4082 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4083 InstructionList.push_back(I);
4087 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4088 // Old form of ICmp/FCmp returning bool
4089 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4090 // both legal on vectors but had different behaviour.
4091 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4092 // FCmp/ICmp returning bool or vector of bool
4096 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4097 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4098 return error("Invalid record");
4100 unsigned PredVal = Record[OpNum];
4101 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4103 if (IsFP && Record.size() > OpNum+1)
4104 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4106 if (OpNum+1 != Record.size())
4107 return error("Invalid record");
4109 if (LHS->getType()->isFPOrFPVectorTy())
4110 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4112 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4115 I->setFastMathFlags(FMF);
4116 InstructionList.push_back(I);
4120 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4122 unsigned Size = Record.size();
4124 I = ReturnInst::Create(Context);
4125 InstructionList.push_back(I);
4130 Value *Op = nullptr;
4131 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4132 return error("Invalid record");
4133 if (OpNum != Record.size())
4134 return error("Invalid record");
4136 I = ReturnInst::Create(Context, Op);
4137 InstructionList.push_back(I);
4140 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4141 if (Record.size() != 1 && Record.size() != 3)
4142 return error("Invalid record");
4143 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4145 return error("Invalid record");
4147 if (Record.size() == 1) {
4148 I = BranchInst::Create(TrueDest);
4149 InstructionList.push_back(I);
4152 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4153 Value *Cond = getValue(Record, 2, NextValueNo,
4154 Type::getInt1Ty(Context));
4155 if (!FalseDest || !Cond)
4156 return error("Invalid record");
4157 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4158 InstructionList.push_back(I);
4162 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4163 if (Record.size() != 1 && Record.size() != 2)
4164 return error("Invalid record");
4166 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4167 Type::getTokenTy(Context), OC_CleanupPad);
4169 return error("Invalid record");
4170 BasicBlock *UnwindDest = nullptr;
4171 if (Record.size() == 2) {
4172 UnwindDest = getBasicBlock(Record[Idx++]);
4174 return error("Invalid record");
4177 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4179 InstructionList.push_back(I);
4182 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4183 if (Record.size() != 2)
4184 return error("Invalid record");
4186 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4187 Type::getTokenTy(Context), OC_CatchPad);
4189 return error("Invalid record");
4190 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4192 return error("Invalid record");
4194 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4195 InstructionList.push_back(I);
4198 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4199 if (Record.size() < 3)
4200 return error("Invalid record");
4202 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4204 return error("Invalid record");
4205 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4207 return error("Invalid record");
4208 unsigned NumArgOperands = Record[Idx++];
4209 SmallVector<Value *, 2> Args;
4210 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4212 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4213 return error("Invalid record");
4214 Args.push_back(Val);
4216 if (Record.size() != Idx)
4217 return error("Invalid record");
4219 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4220 InstructionList.push_back(I);
4223 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4224 if (Record.size() < 1)
4225 return error("Invalid record");
4227 bool HasUnwindDest = !!Record[Idx++];
4228 BasicBlock *UnwindDest = nullptr;
4229 if (HasUnwindDest) {
4230 if (Idx == Record.size())
4231 return error("Invalid record");
4232 UnwindDest = getBasicBlock(Record[Idx++]);
4234 return error("Invalid record");
4236 unsigned NumArgOperands = Record[Idx++];
4237 SmallVector<Value *, 2> Args;
4238 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4240 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4241 return error("Invalid record");
4242 Args.push_back(Val);
4244 if (Record.size() != Idx)
4245 return error("Invalid record");
4247 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4248 InstructionList.push_back(I);
4251 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4252 if (Record.size() < 1)
4253 return error("Invalid record");
4255 unsigned NumArgOperands = Record[Idx++];
4256 SmallVector<Value *, 2> Args;
4257 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4259 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4260 return error("Invalid record");
4261 Args.push_back(Val);
4263 if (Record.size() != Idx)
4264 return error("Invalid record");
4266 I = CleanupPadInst::Create(Context, Args);
4267 InstructionList.push_back(I);
4270 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4271 if (Record.size() > 1)
4272 return error("Invalid record");
4273 BasicBlock *BB = nullptr;
4274 if (Record.size() == 1) {
4275 BB = getBasicBlock(Record[0]);
4277 return error("Invalid record");
4279 I = CatchEndPadInst::Create(Context, BB);
4280 InstructionList.push_back(I);
4283 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4284 if (Record.size() != 1 && Record.size() != 2)
4285 return error("Invalid record");
4287 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4288 Type::getTokenTy(Context), OC_CleanupPad);
4290 return error("Invalid record");
4292 BasicBlock *BB = nullptr;
4293 if (Record.size() == 2) {
4294 BB = getBasicBlock(Record[Idx++]);
4296 return error("Invalid record");
4298 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4299 InstructionList.push_back(I);
4302 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4304 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4305 // "New" SwitchInst format with case ranges. The changes to write this
4306 // format were reverted but we still recognize bitcode that uses it.
4307 // Hopefully someday we will have support for case ranges and can use
4308 // this format again.
4310 Type *OpTy = getTypeByID(Record[1]);
4311 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4313 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4314 BasicBlock *Default = getBasicBlock(Record[3]);
4315 if (!OpTy || !Cond || !Default)
4316 return error("Invalid record");
4318 unsigned NumCases = Record[4];
4320 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4321 InstructionList.push_back(SI);
4323 unsigned CurIdx = 5;
4324 for (unsigned i = 0; i != NumCases; ++i) {
4325 SmallVector<ConstantInt*, 1> CaseVals;
4326 unsigned NumItems = Record[CurIdx++];
4327 for (unsigned ci = 0; ci != NumItems; ++ci) {
4328 bool isSingleNumber = Record[CurIdx++];
4331 unsigned ActiveWords = 1;
4332 if (ValueBitWidth > 64)
4333 ActiveWords = Record[CurIdx++];
4334 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4336 CurIdx += ActiveWords;
4338 if (!isSingleNumber) {
4340 if (ValueBitWidth > 64)
4341 ActiveWords = Record[CurIdx++];
4342 APInt High = readWideAPInt(
4343 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4344 CurIdx += ActiveWords;
4346 // FIXME: It is not clear whether values in the range should be
4347 // compared as signed or unsigned values. The partially
4348 // implemented changes that used this format in the past used
4349 // unsigned comparisons.
4350 for ( ; Low.ule(High); ++Low)
4351 CaseVals.push_back(ConstantInt::get(Context, Low));
4353 CaseVals.push_back(ConstantInt::get(Context, Low));
4355 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4356 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4357 cve = CaseVals.end(); cvi != cve; ++cvi)
4358 SI->addCase(*cvi, DestBB);
4364 // Old SwitchInst format without case ranges.
4366 if (Record.size() < 3 || (Record.size() & 1) == 0)
4367 return error("Invalid record");
4368 Type *OpTy = getTypeByID(Record[0]);
4369 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4370 BasicBlock *Default = getBasicBlock(Record[2]);
4371 if (!OpTy || !Cond || !Default)
4372 return error("Invalid record");
4373 unsigned NumCases = (Record.size()-3)/2;
4374 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4375 InstructionList.push_back(SI);
4376 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4377 ConstantInt *CaseVal =
4378 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4379 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4380 if (!CaseVal || !DestBB) {
4382 return error("Invalid record");
4384 SI->addCase(CaseVal, DestBB);
4389 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4390 if (Record.size() < 2)
4391 return error("Invalid record");
4392 Type *OpTy = getTypeByID(Record[0]);
4393 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4394 if (!OpTy || !Address)
4395 return error("Invalid record");
4396 unsigned NumDests = Record.size()-2;
4397 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4398 InstructionList.push_back(IBI);
4399 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4400 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4401 IBI->addDestination(DestBB);
4404 return error("Invalid record");
4411 case bitc::FUNC_CODE_INST_INVOKE: {
4412 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4413 if (Record.size() < 4)
4414 return error("Invalid record");
4416 AttributeSet PAL = getAttributes(Record[OpNum++]);
4417 unsigned CCInfo = Record[OpNum++];
4418 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4419 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4421 FunctionType *FTy = nullptr;
4422 if (CCInfo >> 13 & 1 &&
4423 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4424 return error("Explicit invoke type is not a function type");
4427 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4428 return error("Invalid record");
4430 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4432 return error("Callee is not a pointer");
4434 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4436 return error("Callee is not of pointer to function type");
4437 } else if (CalleeTy->getElementType() != FTy)
4438 return error("Explicit invoke type does not match pointee type of "
4440 if (Record.size() < FTy->getNumParams() + OpNum)
4441 return error("Insufficient operands to call");
4443 SmallVector<Value*, 16> Ops;
4444 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4445 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4446 FTy->getParamType(i)));
4448 return error("Invalid record");
4451 if (!FTy->isVarArg()) {
4452 if (Record.size() != OpNum)
4453 return error("Invalid record");
4455 // Read type/value pairs for varargs params.
4456 while (OpNum != Record.size()) {
4458 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4459 return error("Invalid record");
4464 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4465 OperandBundles.clear();
4466 InstructionList.push_back(I);
4468 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
4469 cast<InvokeInst>(I)->setAttributes(PAL);
4472 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4474 Value *Val = nullptr;
4475 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4476 return error("Invalid record");
4477 I = ResumeInst::Create(Val);
4478 InstructionList.push_back(I);
4481 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4482 I = new UnreachableInst(Context);
4483 InstructionList.push_back(I);
4485 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4486 if (Record.size() < 1 || ((Record.size()-1)&1))
4487 return error("Invalid record");
4488 Type *Ty = getTypeByID(Record[0]);
4490 return error("Invalid record");
4492 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4493 InstructionList.push_back(PN);
4495 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4497 // With the new function encoding, it is possible that operands have
4498 // negative IDs (for forward references). Use a signed VBR
4499 // representation to keep the encoding small.
4501 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4503 V = getValue(Record, 1+i, NextValueNo, Ty);
4504 BasicBlock *BB = getBasicBlock(Record[2+i]);
4506 return error("Invalid record");
4507 PN->addIncoming(V, BB);
4513 case bitc::FUNC_CODE_INST_LANDINGPAD:
4514 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4515 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4517 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4518 if (Record.size() < 3)
4519 return error("Invalid record");
4521 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4522 if (Record.size() < 4)
4523 return error("Invalid record");
4525 Type *Ty = getTypeByID(Record[Idx++]);
4527 return error("Invalid record");
4528 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4529 Value *PersFn = nullptr;
4530 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4531 return error("Invalid record");
4533 if (!F->hasPersonalityFn())
4534 F->setPersonalityFn(cast<Constant>(PersFn));
4535 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4536 return error("Personality function mismatch");
4539 bool IsCleanup = !!Record[Idx++];
4540 unsigned NumClauses = Record[Idx++];
4541 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4542 LP->setCleanup(IsCleanup);
4543 for (unsigned J = 0; J != NumClauses; ++J) {
4544 LandingPadInst::ClauseType CT =
4545 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4548 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4550 return error("Invalid record");
4553 assert((CT != LandingPadInst::Catch ||
4554 !isa<ArrayType>(Val->getType())) &&
4555 "Catch clause has a invalid type!");
4556 assert((CT != LandingPadInst::Filter ||
4557 isa<ArrayType>(Val->getType())) &&
4558 "Filter clause has invalid type!");
4559 LP->addClause(cast<Constant>(Val));
4563 InstructionList.push_back(I);
4567 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4568 if (Record.size() != 4)
4569 return error("Invalid record");
4570 uint64_t AlignRecord = Record[3];
4571 const uint64_t InAllocaMask = uint64_t(1) << 5;
4572 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4573 // Reserve bit 7 for SwiftError flag.
4574 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4575 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4576 bool InAlloca = AlignRecord & InAllocaMask;
4577 Type *Ty = getTypeByID(Record[0]);
4578 if ((AlignRecord & ExplicitTypeMask) == 0) {
4579 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4581 return error("Old-style alloca with a non-pointer type");
4582 Ty = PTy->getElementType();
4584 Type *OpTy = getTypeByID(Record[1]);
4585 Value *Size = getFnValueByID(Record[2], OpTy);
4587 if (std::error_code EC =
4588 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4592 return error("Invalid record");
4593 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4594 AI->setUsedWithInAlloca(InAlloca);
4596 InstructionList.push_back(I);
4599 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4602 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4603 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4604 return error("Invalid record");
4607 if (OpNum + 3 == Record.size())
4608 Ty = getTypeByID(Record[OpNum++]);
4609 if (std::error_code EC =
4610 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4613 Ty = cast<PointerType>(Op->getType())->getElementType();
4616 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4618 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4620 InstructionList.push_back(I);
4623 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4624 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4627 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4628 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4629 return error("Invalid record");
4632 if (OpNum + 5 == Record.size())
4633 Ty = getTypeByID(Record[OpNum++]);
4634 if (std::error_code EC =
4635 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4638 Ty = cast<PointerType>(Op->getType())->getElementType();
4640 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4641 if (Ordering == NotAtomic || Ordering == Release ||
4642 Ordering == AcquireRelease)
4643 return error("Invalid record");
4644 if (Ordering != NotAtomic && Record[OpNum] == 0)
4645 return error("Invalid record");
4646 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4649 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4651 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4653 InstructionList.push_back(I);
4656 case bitc::FUNC_CODE_INST_STORE:
4657 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4660 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4661 (BitCode == bitc::FUNC_CODE_INST_STORE
4662 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4663 : popValue(Record, OpNum, NextValueNo,
4664 cast<PointerType>(Ptr->getType())->getElementType(),
4666 OpNum + 2 != Record.size())
4667 return error("Invalid record");
4669 if (std::error_code EC = typeCheckLoadStoreInst(
4670 DiagnosticHandler, Val->getType(), Ptr->getType()))
4673 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4675 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4676 InstructionList.push_back(I);
4679 case bitc::FUNC_CODE_INST_STOREATOMIC:
4680 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4681 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4684 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4685 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4686 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4687 : popValue(Record, OpNum, NextValueNo,
4688 cast<PointerType>(Ptr->getType())->getElementType(),
4690 OpNum + 4 != Record.size())
4691 return error("Invalid record");
4693 if (std::error_code EC = typeCheckLoadStoreInst(
4694 DiagnosticHandler, Val->getType(), Ptr->getType()))
4696 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4697 if (Ordering == NotAtomic || Ordering == Acquire ||
4698 Ordering == AcquireRelease)
4699 return error("Invalid record");
4700 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4701 if (Ordering != NotAtomic && Record[OpNum] == 0)
4702 return error("Invalid record");
4705 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4707 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4708 InstructionList.push_back(I);
4711 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4712 case bitc::FUNC_CODE_INST_CMPXCHG: {
4713 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4714 // failureordering?, isweak?]
4716 Value *Ptr, *Cmp, *New;
4717 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4718 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4719 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4720 : popValue(Record, OpNum, NextValueNo,
4721 cast<PointerType>(Ptr->getType())->getElementType(),
4723 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4724 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4725 return error("Invalid record");
4726 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4727 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4728 return error("Invalid record");
4729 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4731 if (std::error_code EC = typeCheckLoadStoreInst(
4732 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4734 AtomicOrdering FailureOrdering;
4735 if (Record.size() < 7)
4737 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4739 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4741 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4743 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4745 if (Record.size() < 8) {
4746 // Before weak cmpxchgs existed, the instruction simply returned the
4747 // value loaded from memory, so bitcode files from that era will be
4748 // expecting the first component of a modern cmpxchg.
4749 CurBB->getInstList().push_back(I);
4750 I = ExtractValueInst::Create(I, 0);
4752 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4755 InstructionList.push_back(I);
4758 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4759 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4762 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4763 popValue(Record, OpNum, NextValueNo,
4764 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4765 OpNum+4 != Record.size())
4766 return error("Invalid record");
4767 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4768 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4769 Operation > AtomicRMWInst::LAST_BINOP)
4770 return error("Invalid record");
4771 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4772 if (Ordering == NotAtomic || Ordering == Unordered)
4773 return error("Invalid record");
4774 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4775 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4776 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4777 InstructionList.push_back(I);
4780 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4781 if (2 != Record.size())
4782 return error("Invalid record");
4783 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4784 if (Ordering == NotAtomic || Ordering == Unordered ||
4785 Ordering == Monotonic)
4786 return error("Invalid record");
4787 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4788 I = new FenceInst(Context, Ordering, SynchScope);
4789 InstructionList.push_back(I);
4792 case bitc::FUNC_CODE_INST_CALL: {
4793 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4794 if (Record.size() < 3)
4795 return error("Invalid record");
4798 AttributeSet PAL = getAttributes(Record[OpNum++]);
4799 unsigned CCInfo = Record[OpNum++];
4801 FunctionType *FTy = nullptr;
4802 if (CCInfo >> 15 & 1 &&
4803 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4804 return error("Explicit call type is not a function type");
4807 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4808 return error("Invalid record");
4810 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4812 return error("Callee is not a pointer type");
4814 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4816 return error("Callee is not of pointer to function type");
4817 } else if (OpTy->getElementType() != FTy)
4818 return error("Explicit call type does not match pointee type of "
4820 if (Record.size() < FTy->getNumParams() + OpNum)
4821 return error("Insufficient operands to call");
4823 SmallVector<Value*, 16> Args;
4824 // Read the fixed params.
4825 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4826 if (FTy->getParamType(i)->isLabelTy())
4827 Args.push_back(getBasicBlock(Record[OpNum]));
4829 Args.push_back(getValue(Record, OpNum, NextValueNo,
4830 FTy->getParamType(i)));
4832 return error("Invalid record");
4835 // Read type/value pairs for varargs params.
4836 if (!FTy->isVarArg()) {
4837 if (OpNum != Record.size())
4838 return error("Invalid record");
4840 while (OpNum != Record.size()) {
4842 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4843 return error("Invalid record");
4848 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4849 OperandBundles.clear();
4850 InstructionList.push_back(I);
4851 cast<CallInst>(I)->setCallingConv(
4852 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4853 CallInst::TailCallKind TCK = CallInst::TCK_None;
4855 TCK = CallInst::TCK_Tail;
4856 if (CCInfo & (1 << 14))
4857 TCK = CallInst::TCK_MustTail;
4858 cast<CallInst>(I)->setTailCallKind(TCK);
4859 cast<CallInst>(I)->setAttributes(PAL);
4862 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4863 if (Record.size() < 3)
4864 return error("Invalid record");
4865 Type *OpTy = getTypeByID(Record[0]);
4866 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4867 Type *ResTy = getTypeByID(Record[2]);
4868 if (!OpTy || !Op || !ResTy)
4869 return error("Invalid record");
4870 I = new VAArgInst(Op, ResTy);
4871 InstructionList.push_back(I);
4875 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4876 // A call or an invoke can be optionally prefixed with some variable
4877 // number of operand bundle blocks. These blocks are read into
4878 // OperandBundles and consumed at the next call or invoke instruction.
4880 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4881 return error("Invalid record");
4883 OperandBundles.emplace_back();
4884 OperandBundles.back().Tag = BundleTags[Record[0]];
4886 std::vector<Value *> &Inputs = OperandBundles.back().Inputs;
4889 while (OpNum != Record.size()) {
4891 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4892 return error("Invalid record");
4893 Inputs.push_back(Op);
4900 // Add instruction to end of current BB. If there is no current BB, reject
4904 return error("Invalid instruction with no BB");
4906 if (!OperandBundles.empty()) {
4908 return error("Operand bundles found with no consumer");
4910 CurBB->getInstList().push_back(I);
4912 // If this was a terminator instruction, move to the next block.
4913 if (isa<TerminatorInst>(I)) {
4915 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4918 // Non-void values get registered in the value table for future use.
4919 if (I && !I->getType()->isVoidTy())
4920 if (ValueList.assignValue(I, NextValueNo++))
4921 return error("Invalid forward reference");
4926 if (!OperandBundles.empty())
4927 return error("Operand bundles found with no consumer");
4929 // Check the function list for unresolved values.
4930 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4931 if (!A->getParent()) {
4932 // We found at least one unresolved value. Nuke them all to avoid leaks.
4933 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4934 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4935 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4939 return error("Never resolved value found in function");
4943 // FIXME: Check for unresolved forward-declared metadata references
4944 // and clean up leaks.
4946 // Trim the value list down to the size it was before we parsed this function.
4947 ValueList.shrinkTo(ModuleValueListSize);
4948 MDValueList.shrinkTo(ModuleMDValueListSize);
4949 std::vector<BasicBlock*>().swap(FunctionBBs);
4950 return std::error_code();
4953 /// Find the function body in the bitcode stream
4954 std::error_code BitcodeReader::findFunctionInStream(
4956 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4957 while (DeferredFunctionInfoIterator->second == 0) {
4958 // This is the fallback handling for the old format bitcode that
4959 // didn't contain the function index in the VST. Assert if we end up
4960 // here for the new format (which is the only time the VSTOffset would
4962 assert(VSTOffset == 0);
4963 if (Stream.AtEndOfStream())
4964 return error("Could not find function in stream");
4965 // ParseModule will parse the next body in the stream and set its
4966 // position in the DeferredFunctionInfo map.
4967 if (std::error_code EC = parseModule(true))
4970 return std::error_code();
4973 //===----------------------------------------------------------------------===//
4974 // GVMaterializer implementation
4975 //===----------------------------------------------------------------------===//
4977 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4979 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4980 if (std::error_code EC = materializeMetadata())
4983 Function *F = dyn_cast<Function>(GV);
4984 // If it's not a function or is already material, ignore the request.
4985 if (!F || !F->isMaterializable())
4986 return std::error_code();
4988 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4989 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4990 // If its position is recorded as 0, its body is somewhere in the stream
4991 // but we haven't seen it yet.
4992 if (DFII->second == 0)
4993 if (std::error_code EC = findFunctionInStream(F, DFII))
4996 // Move the bit stream to the saved position of the deferred function body.
4997 Stream.JumpToBit(DFII->second);
4999 if (std::error_code EC = parseFunctionBody(F))
5001 F->setIsMaterializable(false);
5006 // Upgrade any old intrinsic calls in the function.
5007 for (auto &I : UpgradedIntrinsics) {
5008 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5011 if (CallInst *CI = dyn_cast<CallInst>(U))
5012 UpgradeIntrinsicCall(CI, I.second);
5016 // Bring in any functions that this function forward-referenced via
5018 return materializeForwardReferencedFunctions();
5021 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5022 const Function *F = dyn_cast<Function>(GV);
5023 if (!F || F->isDeclaration())
5026 // Dematerializing F would leave dangling references that wouldn't be
5027 // reconnected on re-materialization.
5028 if (BlockAddressesTaken.count(F))
5031 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5034 void BitcodeReader::dematerialize(GlobalValue *GV) {
5035 Function *F = dyn_cast<Function>(GV);
5036 // If this function isn't dematerializable, this is a noop.
5037 if (!F || !isDematerializable(F))
5040 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5042 // Just forget the function body, we can remat it later.
5043 F->dropAllReferences();
5044 F->setIsMaterializable(true);
5047 std::error_code BitcodeReader::materializeModule(Module *M) {
5048 assert(M == TheModule &&
5049 "Can only Materialize the Module this BitcodeReader is attached to.");
5051 if (std::error_code EC = materializeMetadata())
5054 // Promise to materialize all forward references.
5055 WillMaterializeAllForwardRefs = true;
5057 // Iterate over the module, deserializing any functions that are still on
5059 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
5061 if (std::error_code EC = materialize(F))
5064 // At this point, if there are any function bodies, the current bit is
5065 // pointing to the END_BLOCK record after them. Now make sure the rest
5066 // of the bits in the module have been read.
5070 // Check that all block address forward references got resolved (as we
5072 if (!BasicBlockFwdRefs.empty())
5073 return error("Never resolved function from blockaddress");
5075 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5076 // delete the old functions to clean up. We can't do this unless the entire
5077 // module is materialized because there could always be another function body
5078 // with calls to the old function.
5079 for (auto &I : UpgradedIntrinsics) {
5080 for (auto *U : I.first->users()) {
5081 if (CallInst *CI = dyn_cast<CallInst>(U))
5082 UpgradeIntrinsicCall(CI, I.second);
5084 if (!I.first->use_empty())
5085 I.first->replaceAllUsesWith(I.second);
5086 I.first->eraseFromParent();
5088 UpgradedIntrinsics.clear();
5090 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5091 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5093 UpgradeDebugInfo(*M);
5094 return std::error_code();
5097 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5098 return IdentifiedStructTypes;
5102 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5104 return initLazyStream(std::move(Streamer));
5105 return initStreamFromBuffer();
5108 std::error_code BitcodeReader::initStreamFromBuffer() {
5109 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5110 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5112 if (Buffer->getBufferSize() & 3)
5113 return error("Invalid bitcode signature");
5115 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5116 // The magic number is 0x0B17C0DE stored in little endian.
5117 if (isBitcodeWrapper(BufPtr, BufEnd))
5118 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5119 return error("Invalid bitcode wrapper header");
5121 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5122 Stream.init(&*StreamFile);
5124 return std::error_code();
5128 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5129 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5132 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5133 StreamingMemoryObject &Bytes = *OwnedBytes;
5134 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5135 Stream.init(&*StreamFile);
5137 unsigned char buf[16];
5138 if (Bytes.readBytes(buf, 16, 0) != 16)
5139 return error("Invalid bitcode signature");
5141 if (!isBitcode(buf, buf + 16))
5142 return error("Invalid bitcode signature");
5144 if (isBitcodeWrapper(buf, buf + 4)) {
5145 const unsigned char *bitcodeStart = buf;
5146 const unsigned char *bitcodeEnd = buf + 16;
5147 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5148 Bytes.dropLeadingBytes(bitcodeStart - buf);
5149 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5151 return std::error_code();
5154 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5155 const Twine &Message) {
5156 return ::error(DiagnosticHandler, make_error_code(E), Message);
5159 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5160 return ::error(DiagnosticHandler,
5161 make_error_code(BitcodeError::CorruptedBitcode), Message);
5164 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5165 return ::error(DiagnosticHandler, make_error_code(E));
5168 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5169 MemoryBuffer *Buffer, LLVMContext &Context,
5170 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5171 bool CheckFuncSummaryPresenceOnly)
5172 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5175 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5177 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5178 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler,
5179 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5180 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5183 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5185 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5187 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5189 // Specialized value symbol table parser used when reading function index
5190 // blocks where we don't actually create global values.
5191 // At the end of this routine the function index is populated with a map
5192 // from function name to FunctionInfo. The function info contains
5193 // the function block's bitcode offset as well as the offset into the
5194 // function summary section.
5195 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5196 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5197 return error("Invalid record");
5199 SmallVector<uint64_t, 64> Record;
5201 // Read all the records for this value table.
5202 SmallString<128> ValueName;
5204 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5206 switch (Entry.Kind) {
5207 case BitstreamEntry::SubBlock: // Handled for us already.
5208 case BitstreamEntry::Error:
5209 return error("Malformed block");
5210 case BitstreamEntry::EndBlock:
5211 return std::error_code();
5212 case BitstreamEntry::Record:
5213 // The interesting case.
5219 switch (Stream.readRecord(Entry.ID, Record)) {
5220 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5222 case bitc::VST_CODE_FNENTRY: {
5223 // VST_FNENTRY: [valueid, offset, namechar x N]
5224 if (convertToString(Record, 2, ValueName))
5225 return error("Invalid record");
5226 unsigned ValueID = Record[0];
5227 uint64_t FuncOffset = Record[1];
5228 std::unique_ptr<FunctionInfo> FuncInfo =
5229 llvm::make_unique<FunctionInfo>(FuncOffset);
5230 if (foundFuncSummary() && !IsLazy) {
5231 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5232 SummaryMap.find(ValueID);
5233 assert(SMI != SummaryMap.end() && "Summary info not found");
5234 FuncInfo->setFunctionSummary(std::move(SMI->second));
5236 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5241 case bitc::VST_CODE_COMBINED_FNENTRY: {
5242 // VST_FNENTRY: [offset, namechar x N]
5243 if (convertToString(Record, 1, ValueName))
5244 return error("Invalid record");
5245 uint64_t FuncSummaryOffset = Record[0];
5246 std::unique_ptr<FunctionInfo> FuncInfo =
5247 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5248 if (foundFuncSummary() && !IsLazy) {
5249 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5250 SummaryMap.find(FuncSummaryOffset);
5251 assert(SMI != SummaryMap.end() && "Summary info not found");
5252 FuncInfo->setFunctionSummary(std::move(SMI->second));
5254 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5263 // Parse just the blocks needed for function index building out of the module.
5264 // At the end of this routine the function Index is populated with a map
5265 // from function name to FunctionInfo. The function info contains
5266 // either the parsed function summary information (when parsing summaries
5267 // eagerly), or just to the function summary record's offset
5268 // if parsing lazily (IsLazy).
5269 std::error_code FunctionIndexBitcodeReader::parseModule() {
5270 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5271 return error("Invalid record");
5273 // Read the function index for this module.
5275 BitstreamEntry Entry = Stream.advance();
5277 switch (Entry.Kind) {
5278 case BitstreamEntry::Error:
5279 return error("Malformed block");
5280 case BitstreamEntry::EndBlock:
5281 return std::error_code();
5283 case BitstreamEntry::SubBlock:
5284 if (CheckFuncSummaryPresenceOnly) {
5285 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5286 SeenFuncSummary = true;
5287 if (Stream.SkipBlock()) return error("Invalid record");
5288 // No need to parse the rest since we found the summary.
5289 return std::error_code();
5292 default: // Skip unknown content.
5293 if (Stream.SkipBlock()) return error("Invalid record");
5295 case bitc::BLOCKINFO_BLOCK_ID:
5296 // Need to parse these to get abbrev ids (e.g. for VST)
5297 if (Stream.ReadBlockInfoBlock()) return error("Malformed block");
5299 case bitc::VALUE_SYMTAB_BLOCK_ID:
5300 if (std::error_code EC = parseValueSymbolTable()) return EC;
5302 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5303 SeenFuncSummary = true;
5305 // Lazy parsing of summary info, skip it.
5306 if (Stream.SkipBlock()) return error("Invalid record");
5307 } else if (std::error_code EC = parseEntireSummary())
5310 case bitc::MODULE_STRTAB_BLOCK_ID:
5311 if (std::error_code EC = parseModuleStringTable()) return EC;
5316 case BitstreamEntry::Record:
5317 Stream.skipRecord(Entry.ID);
5323 // Eagerly parse the entire function summary block (i.e. for all functions
5324 // in the index). This populates the FunctionSummary objects in
5326 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5327 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5328 return error("Invalid record");
5330 SmallVector<uint64_t, 64> Record;
5333 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5335 switch (Entry.Kind) {
5336 case BitstreamEntry::SubBlock: // Handled for us already.
5337 case BitstreamEntry::Error:
5338 return error("Malformed block");
5339 case BitstreamEntry::EndBlock:
5340 return std::error_code();
5341 case BitstreamEntry::Record:
5342 // The interesting case.
5346 // Read a record. The record format depends on whether this
5347 // is a per-module index or a combined index file. In the per-module
5348 // case the records contain the associated value's ID for correlation
5349 // with VST entries. In the combined index the correlation is done
5350 // via the bitcode offset of the summary records (which were saved
5351 // in the combined index VST entries). The records also contain
5352 // information used for ThinLTO renaming and importing.
5354 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5355 switch (Stream.readRecord(Entry.ID, Record)) {
5356 default: // Default behavior: ignore.
5358 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5359 case bitc::FS_CODE_PERMODULE_ENTRY: {
5360 unsigned ValueID = Record[0];
5361 bool IsLocal = Record[1];
5362 unsigned InstCount = Record[2];
5363 std::unique_ptr<FunctionSummary> FS =
5364 llvm::make_unique<FunctionSummary>(InstCount);
5365 FS->setLocalFunction(IsLocal);
5366 // The module path string ref set in the summary must be owned by the
5367 // index's module string table. Since we don't have a module path
5368 // string table section in the per-module index, we create a single
5369 // module path string table entry with an empty (0) ID to take
5372 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5373 SummaryMap[ValueID] = std::move(FS);
5375 // FS_COMBINED_ENTRY: [modid, instcount]
5376 case bitc::FS_CODE_COMBINED_ENTRY: {
5377 uint64_t ModuleId = Record[0];
5378 unsigned InstCount = Record[1];
5379 std::unique_ptr<FunctionSummary> FS =
5380 llvm::make_unique<FunctionSummary>(InstCount);
5381 FS->setModulePath(ModuleIdMap[ModuleId]);
5382 SummaryMap[CurRecordBit] = std::move(FS);
5386 llvm_unreachable("Exit infinite loop");
5389 // Parse the module string table block into the Index.
5390 // This populates the ModulePathStringTable map in the index.
5391 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5392 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5393 return error("Invalid record");
5395 SmallVector<uint64_t, 64> Record;
5397 SmallString<128> ModulePath;
5399 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5401 switch (Entry.Kind) {
5402 case BitstreamEntry::SubBlock: // Handled for us already.
5403 case BitstreamEntry::Error:
5404 return error("Malformed block");
5405 case BitstreamEntry::EndBlock:
5406 return std::error_code();
5407 case BitstreamEntry::Record:
5408 // The interesting case.
5413 switch (Stream.readRecord(Entry.ID, Record)) {
5414 default: // Default behavior: ignore.
5416 case bitc::MST_CODE_ENTRY: {
5417 // MST_ENTRY: [modid, namechar x N]
5418 if (convertToString(Record, 1, ModulePath))
5419 return error("Invalid record");
5420 uint64_t ModuleId = Record[0];
5421 StringRef ModulePathInMap =
5422 TheIndex->addModulePath(ModulePath, ModuleId);
5423 ModuleIdMap[ModuleId] = ModulePathInMap;
5429 llvm_unreachable("Exit infinite loop");
5432 // Parse the function info index from the bitcode streamer into the given index.
5433 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5434 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5437 if (std::error_code EC = initStream(std::move(Streamer))) return EC;
5439 // Sniff for the signature.
5440 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
5442 // We expect a number of well-defined blocks, though we don't necessarily
5443 // need to understand them all.
5445 if (Stream.AtEndOfStream()) {
5446 // We didn't really read a proper Module block.
5447 return error("Malformed block");
5450 BitstreamEntry Entry =
5451 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5453 if (Entry.Kind != BitstreamEntry::SubBlock) return error("Malformed block");
5455 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5456 // building the function summary index.
5457 if (Entry.ID == bitc::MODULE_BLOCK_ID) return parseModule();
5459 if (Stream.SkipBlock()) return error("Invalid record");
5463 // Parse the function information at the given offset in the buffer into
5464 // the index. Used to support lazy parsing of function summaries from the
5465 // combined index during importing.
5466 // TODO: This function is not yet complete as it won't have a consumer
5467 // until ThinLTO function importing is added.
5468 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5469 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5470 size_t FunctionSummaryOffset) {
5473 if (std::error_code EC = initStream(std::move(Streamer))) return EC;
5475 // Sniff for the signature.
5476 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
5478 Stream.JumpToBit(FunctionSummaryOffset);
5480 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5482 switch (Entry.Kind) {
5484 return error("Malformed block");
5485 case BitstreamEntry::Record:
5486 // The expected case.
5490 // TODO: Read a record. This interface will be completed when ThinLTO
5491 // importing is added so that it can be tested.
5492 SmallVector<uint64_t, 64> Record;
5493 switch (Stream.readRecord(Entry.ID, Record)) {
5495 return error("Invalid record");
5498 return std::error_code();
5501 std::error_code FunctionIndexBitcodeReader::initStream(
5502 std::unique_ptr<DataStreamer> Streamer) {
5503 if (Streamer) return initLazyStream(std::move(Streamer));
5504 return initStreamFromBuffer();
5507 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5508 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5509 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5511 if (Buffer->getBufferSize() & 3) return error("Invalid bitcode signature");
5513 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5514 // The magic number is 0x0B17C0DE stored in little endian.
5515 if (isBitcodeWrapper(BufPtr, BufEnd))
5516 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5517 return error("Invalid bitcode wrapper header");
5519 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5520 Stream.init(&*StreamFile);
5522 return std::error_code();
5525 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5526 std::unique_ptr<DataStreamer> Streamer) {
5527 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5530 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5531 StreamingMemoryObject &Bytes = *OwnedBytes;
5532 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5533 Stream.init(&*StreamFile);
5535 unsigned char buf[16];
5536 if (Bytes.readBytes(buf, 16, 0) != 16)
5537 return error("Invalid bitcode signature");
5539 if (!isBitcode(buf, buf + 16)) return error("Invalid bitcode signature");
5541 if (isBitcodeWrapper(buf, buf + 4)) {
5542 const unsigned char *bitcodeStart = buf;
5543 const unsigned char *bitcodeEnd = buf + 16;
5544 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5545 Bytes.dropLeadingBytes(bitcodeStart - buf);
5546 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5548 return std::error_code();
5552 class BitcodeErrorCategoryType : public std::error_category {
5553 const char *name() const LLVM_NOEXCEPT override {
5554 return "llvm.bitcode";
5556 std::string message(int IE) const override {
5557 BitcodeError E = static_cast<BitcodeError>(IE);
5559 case BitcodeError::InvalidBitcodeSignature:
5560 return "Invalid bitcode signature";
5561 case BitcodeError::CorruptedBitcode:
5562 return "Corrupted bitcode";
5564 llvm_unreachable("Unknown error type!");
5569 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5571 const std::error_category &llvm::BitcodeErrorCategory() {
5572 return *ErrorCategory;
5575 //===----------------------------------------------------------------------===//
5576 // External interface
5577 //===----------------------------------------------------------------------===//
5579 static ErrorOr<std::unique_ptr<Module>>
5580 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5581 BitcodeReader *R, LLVMContext &Context,
5582 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5583 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5584 M->setMaterializer(R);
5586 auto cleanupOnError = [&](std::error_code EC) {
5587 R->releaseBuffer(); // Never take ownership on error.
5591 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5592 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5593 ShouldLazyLoadMetadata))
5594 return cleanupOnError(EC);
5596 if (MaterializeAll) {
5597 // Read in the entire module, and destroy the BitcodeReader.
5598 if (std::error_code EC = M->materializeAllPermanently())
5599 return cleanupOnError(EC);
5601 // Resolve forward references from blockaddresses.
5602 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5603 return cleanupOnError(EC);
5605 return std::move(M);
5608 /// \brief Get a lazy one-at-time loading module from bitcode.
5610 /// This isn't always used in a lazy context. In particular, it's also used by
5611 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5612 /// in forward-referenced functions from block address references.
5614 /// \param[in] MaterializeAll Set to \c true if we should materialize
5616 static ErrorOr<std::unique_ptr<Module>>
5617 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5618 LLVMContext &Context, bool MaterializeAll,
5619 DiagnosticHandlerFunction DiagnosticHandler,
5620 bool ShouldLazyLoadMetadata = false) {
5622 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5624 ErrorOr<std::unique_ptr<Module>> Ret =
5625 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5626 MaterializeAll, ShouldLazyLoadMetadata);
5630 Buffer.release(); // The BitcodeReader owns it now.
5634 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5635 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5636 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5637 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5638 DiagnosticHandler, ShouldLazyLoadMetadata);
5641 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5642 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5643 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5644 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5645 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5647 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5651 ErrorOr<std::unique_ptr<Module>>
5652 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5653 DiagnosticHandlerFunction DiagnosticHandler) {
5654 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5655 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5657 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5658 // written. We must defer until the Module has been fully materialized.
5662 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5663 DiagnosticHandlerFunction DiagnosticHandler) {
5664 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5665 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5667 ErrorOr<std::string> Triple = R->parseTriple();
5668 if (Triple.getError())
5670 return Triple.get();
5673 // Parse the specified bitcode buffer, returning the function info index.
5674 // If IsLazy is false, parse the entire function summary into
5675 // the index. Otherwise skip the function summary section, and only create
5676 // an index object with a map from function name to function summary offset.
5677 // The index is used to perform lazy function summary reading later.
5678 ErrorOr<std::unique_ptr<FunctionInfoIndex>> llvm::getFunctionInfoIndex(
5679 MemoryBufferRef Buffer, LLVMContext &Context,
5680 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy) {
5681 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5682 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, IsLazy);
5684 std::unique_ptr<FunctionInfoIndex> Index =
5685 llvm::make_unique<FunctionInfoIndex>();
5687 auto cleanupOnError = [&](std::error_code EC) {
5688 R.releaseBuffer(); // Never take ownership on error.
5692 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5693 return cleanupOnError(EC);
5695 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5696 return std::move(Index);
5699 // Check if the given bitcode buffer contains a function summary block.
5700 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5701 DiagnosticHandlerFunction DiagnosticHandler) {
5702 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5703 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, false,
5706 auto cleanupOnError = [&](std::error_code EC) {
5707 R.releaseBuffer(); // Never take ownership on error.
5711 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5712 return cleanupOnError(EC);
5714 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5715 return R.foundFuncSummary();
5718 // This method supports lazy reading of function summary data from the combined
5719 // index during ThinLTO function importing. When reading the combined index
5720 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5721 // Then this method is called for each function considered for importing,
5722 // to parse the summary information for the given function name into
5724 std::error_code llvm::readFunctionSummary(
5725 MemoryBufferRef Buffer, LLVMContext &Context,
5726 DiagnosticHandlerFunction DiagnosticHandler, StringRef FunctionName,
5727 std::unique_ptr<FunctionInfoIndex> Index) {
5728 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5729 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler);
5731 auto cleanupOnError = [&](std::error_code EC) {
5732 R.releaseBuffer(); // Never take ownership on error.
5736 // Lookup the given function name in the FunctionMap, which may
5737 // contain a list of function infos in the case of a COMDAT. Walk through
5738 // and parse each function summary info at the function summary offset
5739 // recorded when parsing the value symbol table.
5740 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5741 size_t FunctionSummaryOffset = FI->bitcodeIndex();
5742 if (std::error_code EC =
5743 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5744 return cleanupOnError(EC);
5747 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5748 return std::error_code();