1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/FunctionInfo.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/DataStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
42 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
45 /// Indicates which operator an operand allows (for the few operands that may
46 /// only reference a certain operator).
47 enum OperatorConstraint {
48 OC_None = 0, // No constraint
49 OC_CatchPad, // Must be CatchPadInst
50 OC_CleanupPad // Must be CleanupPadInst
53 class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
56 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
59 /// ResolveConstantForwardRefs for more information about this.
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
75 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
78 assert(ResolveConstants.empty() && "Constants not resolved?");
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
87 Value *back() const { return ValuePtrs.back(); }
88 void pop_back() { ValuePtrs.pop_back(); }
89 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
96 Value *getValueFwdRef(unsigned Idx, Type *Ty,
97 OperatorConstraint OC = OC_None);
99 bool assignValue(Value *V, unsigned Idx);
101 /// Once all constants are read, this method bulk resolves any forward
103 void resolveConstantForwardRefs();
106 class BitcodeReaderMDValueList {
111 std::vector<TrackingMDRef> MDValuePtrs;
113 LLVMContext &Context;
115 BitcodeReaderMDValueList(LLVMContext &C)
116 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
118 // vector compatibility methods
119 unsigned size() const { return MDValuePtrs.size(); }
120 void resize(unsigned N) { MDValuePtrs.resize(N); }
121 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
122 void clear() { MDValuePtrs.clear(); }
123 Metadata *back() const { return MDValuePtrs.back(); }
124 void pop_back() { MDValuePtrs.pop_back(); }
125 bool empty() const { return MDValuePtrs.empty(); }
127 Metadata *operator[](unsigned i) const {
128 assert(i < MDValuePtrs.size());
129 return MDValuePtrs[i];
132 void shrinkTo(unsigned N) {
133 assert(N <= size() && "Invalid shrinkTo request!");
134 MDValuePtrs.resize(N);
137 Metadata *getValueFwdRef(unsigned Idx);
138 void assignValue(Metadata *MD, unsigned Idx);
139 void tryToResolveCycles();
142 class BitcodeReader : public GVMaterializer {
143 LLVMContext &Context;
144 DiagnosticHandlerFunction DiagnosticHandler;
145 Module *TheModule = nullptr;
146 std::unique_ptr<MemoryBuffer> Buffer;
147 std::unique_ptr<BitstreamReader> StreamFile;
148 BitstreamCursor Stream;
149 // Next offset to start scanning for lazy parsing of function bodies.
150 uint64_t NextUnreadBit = 0;
151 // Last function offset found in the VST.
152 uint64_t LastFunctionBlockBit = 0;
153 bool SeenValueSymbolTable = false;
154 unsigned VSTOffset = 0;
156 std::vector<Type*> TypeList;
157 BitcodeReaderValueList ValueList;
158 BitcodeReaderMDValueList MDValueList;
159 std::vector<Comdat *> ComdatList;
160 SmallVector<Instruction *, 64> InstructionList;
162 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
163 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
164 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
165 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
166 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
168 SmallVector<Instruction*, 64> InstsWithTBAATag;
170 /// The set of attributes by index. Index zero in the file is for null, and
171 /// is thus not represented here. As such all indices are off by one.
172 std::vector<AttributeSet> MAttributes;
174 /// The set of attribute groups.
175 std::map<unsigned, AttributeSet> MAttributeGroups;
177 /// While parsing a function body, this is a list of the basic blocks for the
179 std::vector<BasicBlock*> FunctionBBs;
181 // When reading the module header, this list is populated with functions that
182 // have bodies later in the file.
183 std::vector<Function*> FunctionsWithBodies;
185 // When intrinsic functions are encountered which require upgrading they are
186 // stored here with their replacement function.
187 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
188 UpgradedIntrinsicMap UpgradedIntrinsics;
190 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
191 DenseMap<unsigned, unsigned> MDKindMap;
193 // Several operations happen after the module header has been read, but
194 // before function bodies are processed. This keeps track of whether
195 // we've done this yet.
196 bool SeenFirstFunctionBody = false;
198 /// When function bodies are initially scanned, this map contains info about
199 /// where to find deferred function body in the stream.
200 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
202 /// When Metadata block is initially scanned when parsing the module, we may
203 /// choose to defer parsing of the metadata. This vector contains info about
204 /// which Metadata blocks are deferred.
205 std::vector<uint64_t> DeferredMetadataInfo;
207 /// These are basic blocks forward-referenced by block addresses. They are
208 /// inserted lazily into functions when they're loaded. The basic block ID is
209 /// its index into the vector.
210 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
211 std::deque<Function *> BasicBlockFwdRefQueue;
213 /// Indicates that we are using a new encoding for instruction operands where
214 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
215 /// instruction number, for a more compact encoding. Some instruction
216 /// operands are not relative to the instruction ID: basic block numbers, and
217 /// types. Once the old style function blocks have been phased out, we would
218 /// not need this flag.
219 bool UseRelativeIDs = false;
221 /// True if all functions will be materialized, negating the need to process
222 /// (e.g.) blockaddress forward references.
223 bool WillMaterializeAllForwardRefs = false;
225 /// Functions that have block addresses taken. This is usually empty.
226 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
228 /// True if any Metadata block has been materialized.
229 bool IsMetadataMaterialized = false;
231 bool StripDebugInfo = false;
233 std::vector<std::string> BundleTags;
236 std::error_code error(BitcodeError E, const Twine &Message);
237 std::error_code error(BitcodeError E);
238 std::error_code error(const Twine &Message);
240 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
241 DiagnosticHandlerFunction DiagnosticHandler);
242 BitcodeReader(LLVMContext &Context,
243 DiagnosticHandlerFunction DiagnosticHandler);
244 ~BitcodeReader() override { freeState(); }
246 std::error_code materializeForwardReferencedFunctions();
250 void releaseBuffer();
252 bool isDematerializable(const GlobalValue *GV) const override;
253 std::error_code materialize(GlobalValue *GV) override;
254 std::error_code materializeModule(Module *M) override;
255 std::vector<StructType *> getIdentifiedStructTypes() const override;
256 void dematerialize(GlobalValue *GV) override;
258 /// \brief Main interface to parsing a bitcode buffer.
259 /// \returns true if an error occurred.
260 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
262 bool ShouldLazyLoadMetadata = false);
264 /// \brief Cheap mechanism to just extract module triple
265 /// \returns true if an error occurred.
266 ErrorOr<std::string> parseTriple();
268 static uint64_t decodeSignRotatedValue(uint64_t V);
270 /// Materialize any deferred Metadata block.
271 std::error_code materializeMetadata() override;
273 void setStripDebugInfo() override;
276 std::vector<StructType *> IdentifiedStructTypes;
277 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
278 StructType *createIdentifiedStructType(LLVMContext &Context);
280 Type *getTypeByID(unsigned ID);
281 Value *getFnValueByID(unsigned ID, Type *Ty,
282 OperatorConstraint OC = OC_None) {
283 if (Ty && Ty->isMetadataTy())
284 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
285 return ValueList.getValueFwdRef(ID, Ty, OC);
287 Metadata *getFnMetadataByID(unsigned ID) {
288 return MDValueList.getValueFwdRef(ID);
290 BasicBlock *getBasicBlock(unsigned ID) const {
291 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
292 return FunctionBBs[ID];
294 AttributeSet getAttributes(unsigned i) const {
295 if (i-1 < MAttributes.size())
296 return MAttributes[i-1];
297 return AttributeSet();
300 /// Read a value/type pair out of the specified record from slot 'Slot'.
301 /// Increment Slot past the number of slots used in the record. Return true on
303 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
304 unsigned InstNum, Value *&ResVal) {
305 if (Slot == Record.size()) return true;
306 unsigned ValNo = (unsigned)Record[Slot++];
307 // Adjust the ValNo, if it was encoded relative to the InstNum.
309 ValNo = InstNum - ValNo;
310 if (ValNo < InstNum) {
311 // If this is not a forward reference, just return the value we already
313 ResVal = getFnValueByID(ValNo, nullptr);
314 return ResVal == nullptr;
316 if (Slot == Record.size())
319 unsigned TypeNo = (unsigned)Record[Slot++];
320 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
321 return ResVal == nullptr;
324 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
325 /// past the number of slots used by the value in the record. Return true if
326 /// there is an error.
327 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
328 unsigned InstNum, Type *Ty, Value *&ResVal,
329 OperatorConstraint OC = OC_None) {
330 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
332 // All values currently take a single record slot.
337 /// Like popValue, but does not increment the Slot number.
338 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
339 unsigned InstNum, Type *Ty, Value *&ResVal,
340 OperatorConstraint OC = OC_None) {
341 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
342 return ResVal == nullptr;
345 /// Version of getValue that returns ResVal directly, or 0 if there is an
347 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
348 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
349 if (Slot == Record.size()) return nullptr;
350 unsigned ValNo = (unsigned)Record[Slot];
351 // Adjust the ValNo, if it was encoded relative to the InstNum.
353 ValNo = InstNum - ValNo;
354 return getFnValueByID(ValNo, Ty, OC);
357 /// Like getValue, but decodes signed VBRs.
358 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
359 unsigned InstNum, Type *Ty,
360 OperatorConstraint OC = OC_None) {
361 if (Slot == Record.size()) return nullptr;
362 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
363 // Adjust the ValNo, if it was encoded relative to the InstNum.
365 ValNo = InstNum - ValNo;
366 return getFnValueByID(ValNo, Ty, OC);
369 /// Converts alignment exponent (i.e. power of two (or zero)) to the
370 /// corresponding alignment to use. If alignment is too large, returns
371 /// a corresponding error code.
372 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
373 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
374 std::error_code parseModule(uint64_t ResumeBit,
375 bool ShouldLazyLoadMetadata = false);
376 std::error_code parseAttributeBlock();
377 std::error_code parseAttributeGroupBlock();
378 std::error_code parseTypeTable();
379 std::error_code parseTypeTableBody();
380 std::error_code parseOperandBundleTags();
382 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
383 unsigned NameIndex, Triple &TT);
384 std::error_code parseValueSymbolTable(unsigned Offset = 0);
385 std::error_code parseConstants();
386 std::error_code rememberAndSkipFunctionBodies();
387 std::error_code rememberAndSkipFunctionBody();
388 /// Save the positions of the Metadata blocks and skip parsing the blocks.
389 std::error_code rememberAndSkipMetadata();
390 std::error_code parseFunctionBody(Function *F);
391 std::error_code globalCleanup();
392 std::error_code resolveGlobalAndAliasInits();
393 std::error_code parseMetadata();
394 std::error_code parseMetadataAttachment(Function &F);
395 ErrorOr<std::string> parseModuleTriple();
396 std::error_code parseUseLists();
397 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
398 std::error_code initStreamFromBuffer();
399 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
400 std::error_code findFunctionInStream(
402 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
405 /// Class to manage reading and parsing function summary index bitcode
407 class FunctionIndexBitcodeReader {
408 DiagnosticHandlerFunction DiagnosticHandler;
410 /// Eventually points to the function index built during parsing.
411 FunctionInfoIndex *TheIndex = nullptr;
413 std::unique_ptr<MemoryBuffer> Buffer;
414 std::unique_ptr<BitstreamReader> StreamFile;
415 BitstreamCursor Stream;
417 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
419 /// If false, the summary section is fully parsed into the index during
420 /// the initial parse. Otherwise, if true, the caller is expected to
421 /// invoke \a readFunctionSummary for each summary needed, and the summary
422 /// section is thus parsed lazily.
425 /// Used to indicate whether caller only wants to check for the presence
426 /// of the function summary bitcode section. All blocks are skipped,
427 /// but the SeenFuncSummary boolean is set.
428 bool CheckFuncSummaryPresenceOnly = false;
430 /// Indicates whether we have encountered a function summary section
431 /// yet during parsing, used when checking if file contains function
433 bool SeenFuncSummary = false;
435 /// \brief Map populated during function summary section parsing, and
436 /// consumed during ValueSymbolTable parsing.
438 /// Used to correlate summary records with VST entries. For the per-module
439 /// index this maps the ValueID to the parsed function summary, and
440 /// for the combined index this maps the summary record's bitcode
441 /// offset to the function summary (since in the combined index the
442 /// VST records do not hold value IDs but rather hold the function
443 /// summary record offset).
444 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
446 /// Map populated during module path string table parsing, from the
447 /// module ID to a string reference owned by the index's module
448 /// path string table, used to correlate with combined index function
450 DenseMap<uint64_t, StringRef> ModuleIdMap;
453 std::error_code error(BitcodeError E, const Twine &Message);
454 std::error_code error(BitcodeError E);
455 std::error_code error(const Twine &Message);
457 FunctionIndexBitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
458 DiagnosticHandlerFunction DiagnosticHandler,
460 bool CheckFuncSummaryPresenceOnly = false);
461 FunctionIndexBitcodeReader(LLVMContext &Context,
462 DiagnosticHandlerFunction DiagnosticHandler,
464 bool CheckFuncSummaryPresenceOnly = false);
465 ~FunctionIndexBitcodeReader() { freeState(); }
469 void releaseBuffer();
471 /// Check if the parser has encountered a function summary section.
472 bool foundFuncSummary() { return SeenFuncSummary; }
474 /// \brief Main interface to parsing a bitcode buffer.
475 /// \returns true if an error occurred.
476 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
477 FunctionInfoIndex *I);
479 /// \brief Interface for parsing a function summary lazily.
480 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
481 FunctionInfoIndex *I,
482 size_t FunctionSummaryOffset);
485 std::error_code parseModule();
486 std::error_code parseValueSymbolTable();
487 std::error_code parseEntireSummary();
488 std::error_code parseModuleStringTable();
489 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
490 std::error_code initStreamFromBuffer();
491 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
495 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
496 DiagnosticSeverity Severity,
498 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
500 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
502 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
503 std::error_code EC, const Twine &Message) {
504 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
505 DiagnosticHandler(DI);
509 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
510 std::error_code EC) {
511 return error(DiagnosticHandler, EC, EC.message());
514 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
515 const Twine &Message) {
516 return error(DiagnosticHandler,
517 make_error_code(BitcodeError::CorruptedBitcode), Message);
520 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
521 return ::error(DiagnosticHandler, make_error_code(E), Message);
524 std::error_code BitcodeReader::error(const Twine &Message) {
525 return ::error(DiagnosticHandler,
526 make_error_code(BitcodeError::CorruptedBitcode), Message);
529 std::error_code BitcodeReader::error(BitcodeError E) {
530 return ::error(DiagnosticHandler, make_error_code(E));
533 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
537 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
540 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
541 DiagnosticHandlerFunction DiagnosticHandler)
543 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
544 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
546 BitcodeReader::BitcodeReader(LLVMContext &Context,
547 DiagnosticHandlerFunction DiagnosticHandler)
549 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
550 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
552 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
553 if (WillMaterializeAllForwardRefs)
554 return std::error_code();
556 // Prevent recursion.
557 WillMaterializeAllForwardRefs = true;
559 while (!BasicBlockFwdRefQueue.empty()) {
560 Function *F = BasicBlockFwdRefQueue.front();
561 BasicBlockFwdRefQueue.pop_front();
562 assert(F && "Expected valid function");
563 if (!BasicBlockFwdRefs.count(F))
564 // Already materialized.
567 // Check for a function that isn't materializable to prevent an infinite
568 // loop. When parsing a blockaddress stored in a global variable, there
569 // isn't a trivial way to check if a function will have a body without a
570 // linear search through FunctionsWithBodies, so just check it here.
571 if (!F->isMaterializable())
572 return error("Never resolved function from blockaddress");
574 // Try to materialize F.
575 if (std::error_code EC = materialize(F))
578 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
581 WillMaterializeAllForwardRefs = false;
582 return std::error_code();
585 void BitcodeReader::freeState() {
587 std::vector<Type*>().swap(TypeList);
590 std::vector<Comdat *>().swap(ComdatList);
592 std::vector<AttributeSet>().swap(MAttributes);
593 std::vector<BasicBlock*>().swap(FunctionBBs);
594 std::vector<Function*>().swap(FunctionsWithBodies);
595 DeferredFunctionInfo.clear();
596 DeferredMetadataInfo.clear();
599 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
600 BasicBlockFwdRefQueue.clear();
603 //===----------------------------------------------------------------------===//
604 // Helper functions to implement forward reference resolution, etc.
605 //===----------------------------------------------------------------------===//
607 /// Convert a string from a record into an std::string, return true on failure.
608 template <typename StrTy>
609 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
611 if (Idx > Record.size())
614 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
615 Result += (char)Record[i];
619 static bool hasImplicitComdat(size_t Val) {
623 case 1: // Old WeakAnyLinkage
624 case 4: // Old LinkOnceAnyLinkage
625 case 10: // Old WeakODRLinkage
626 case 11: // Old LinkOnceODRLinkage
631 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
633 default: // Map unknown/new linkages to external
635 return GlobalValue::ExternalLinkage;
637 return GlobalValue::AppendingLinkage;
639 return GlobalValue::InternalLinkage;
641 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
643 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
645 return GlobalValue::ExternalWeakLinkage;
647 return GlobalValue::CommonLinkage;
649 return GlobalValue::PrivateLinkage;
651 return GlobalValue::AvailableExternallyLinkage;
653 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
655 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
657 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
658 case 1: // Old value with implicit comdat.
660 return GlobalValue::WeakAnyLinkage;
661 case 10: // Old value with implicit comdat.
663 return GlobalValue::WeakODRLinkage;
664 case 4: // Old value with implicit comdat.
666 return GlobalValue::LinkOnceAnyLinkage;
667 case 11: // Old value with implicit comdat.
669 return GlobalValue::LinkOnceODRLinkage;
673 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
675 default: // Map unknown visibilities to default.
676 case 0: return GlobalValue::DefaultVisibility;
677 case 1: return GlobalValue::HiddenVisibility;
678 case 2: return GlobalValue::ProtectedVisibility;
682 static GlobalValue::DLLStorageClassTypes
683 getDecodedDLLStorageClass(unsigned Val) {
685 default: // Map unknown values to default.
686 case 0: return GlobalValue::DefaultStorageClass;
687 case 1: return GlobalValue::DLLImportStorageClass;
688 case 2: return GlobalValue::DLLExportStorageClass;
692 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
694 case 0: return GlobalVariable::NotThreadLocal;
695 default: // Map unknown non-zero value to general dynamic.
696 case 1: return GlobalVariable::GeneralDynamicTLSModel;
697 case 2: return GlobalVariable::LocalDynamicTLSModel;
698 case 3: return GlobalVariable::InitialExecTLSModel;
699 case 4: return GlobalVariable::LocalExecTLSModel;
703 static int getDecodedCastOpcode(unsigned Val) {
706 case bitc::CAST_TRUNC : return Instruction::Trunc;
707 case bitc::CAST_ZEXT : return Instruction::ZExt;
708 case bitc::CAST_SEXT : return Instruction::SExt;
709 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
710 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
711 case bitc::CAST_UITOFP : return Instruction::UIToFP;
712 case bitc::CAST_SITOFP : return Instruction::SIToFP;
713 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
714 case bitc::CAST_FPEXT : return Instruction::FPExt;
715 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
716 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
717 case bitc::CAST_BITCAST : return Instruction::BitCast;
718 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
722 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
723 bool IsFP = Ty->isFPOrFPVectorTy();
724 // BinOps are only valid for int/fp or vector of int/fp types
725 if (!IsFP && !Ty->isIntOrIntVectorTy())
731 case bitc::BINOP_ADD:
732 return IsFP ? Instruction::FAdd : Instruction::Add;
733 case bitc::BINOP_SUB:
734 return IsFP ? Instruction::FSub : Instruction::Sub;
735 case bitc::BINOP_MUL:
736 return IsFP ? Instruction::FMul : Instruction::Mul;
737 case bitc::BINOP_UDIV:
738 return IsFP ? -1 : Instruction::UDiv;
739 case bitc::BINOP_SDIV:
740 return IsFP ? Instruction::FDiv : Instruction::SDiv;
741 case bitc::BINOP_UREM:
742 return IsFP ? -1 : Instruction::URem;
743 case bitc::BINOP_SREM:
744 return IsFP ? Instruction::FRem : Instruction::SRem;
745 case bitc::BINOP_SHL:
746 return IsFP ? -1 : Instruction::Shl;
747 case bitc::BINOP_LSHR:
748 return IsFP ? -1 : Instruction::LShr;
749 case bitc::BINOP_ASHR:
750 return IsFP ? -1 : Instruction::AShr;
751 case bitc::BINOP_AND:
752 return IsFP ? -1 : Instruction::And;
754 return IsFP ? -1 : Instruction::Or;
755 case bitc::BINOP_XOR:
756 return IsFP ? -1 : Instruction::Xor;
760 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
762 default: return AtomicRMWInst::BAD_BINOP;
763 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
764 case bitc::RMW_ADD: return AtomicRMWInst::Add;
765 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
766 case bitc::RMW_AND: return AtomicRMWInst::And;
767 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
768 case bitc::RMW_OR: return AtomicRMWInst::Or;
769 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
770 case bitc::RMW_MAX: return AtomicRMWInst::Max;
771 case bitc::RMW_MIN: return AtomicRMWInst::Min;
772 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
773 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
777 static AtomicOrdering getDecodedOrdering(unsigned Val) {
779 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
780 case bitc::ORDERING_UNORDERED: return Unordered;
781 case bitc::ORDERING_MONOTONIC: return Monotonic;
782 case bitc::ORDERING_ACQUIRE: return Acquire;
783 case bitc::ORDERING_RELEASE: return Release;
784 case bitc::ORDERING_ACQREL: return AcquireRelease;
785 default: // Map unknown orderings to sequentially-consistent.
786 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
790 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
792 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
793 default: // Map unknown scopes to cross-thread.
794 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
798 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
800 default: // Map unknown selection kinds to any.
801 case bitc::COMDAT_SELECTION_KIND_ANY:
803 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
804 return Comdat::ExactMatch;
805 case bitc::COMDAT_SELECTION_KIND_LARGEST:
806 return Comdat::Largest;
807 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
808 return Comdat::NoDuplicates;
809 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
810 return Comdat::SameSize;
814 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
816 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
817 FMF.setUnsafeAlgebra();
818 if (0 != (Val & FastMathFlags::NoNaNs))
820 if (0 != (Val & FastMathFlags::NoInfs))
822 if (0 != (Val & FastMathFlags::NoSignedZeros))
823 FMF.setNoSignedZeros();
824 if (0 != (Val & FastMathFlags::AllowReciprocal))
825 FMF.setAllowReciprocal();
829 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
831 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
832 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
838 /// \brief A class for maintaining the slot number definition
839 /// as a placeholder for the actual definition for forward constants defs.
840 class ConstantPlaceHolder : public ConstantExpr {
841 void operator=(const ConstantPlaceHolder &) = delete;
844 // allocate space for exactly one operand
845 void *operator new(size_t s) { return User::operator new(s, 1); }
846 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
847 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
848 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
851 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
852 static bool classof(const Value *V) {
853 return isa<ConstantExpr>(V) &&
854 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
857 /// Provide fast operand accessors
858 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
862 // FIXME: can we inherit this from ConstantExpr?
864 struct OperandTraits<ConstantPlaceHolder> :
865 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
867 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
870 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
879 WeakVH &OldV = ValuePtrs[Idx];
885 // Handle constants and non-constants (e.g. instrs) differently for
887 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
888 ResolveConstants.push_back(std::make_pair(PHC, Idx));
891 // If there was a forward reference to this value, replace it.
892 Value *PrevVal = OldV;
893 // Check operator constraints. We only put cleanuppads or catchpads in
894 // the forward value map if the value is constrained to match.
895 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
896 if (!isa<CatchPadInst>(V))
898 // Delete the dummy basic block that was created with the sentinel
900 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
901 assert(DummyBlock == CatchPad->getNormalDest());
902 CatchPad->dropAllReferences();
904 } else if (isa<CleanupPadInst>(PrevVal)) {
905 if (!isa<CleanupPadInst>(V))
908 OldV->replaceAllUsesWith(V);
916 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
921 if (Value *V = ValuePtrs[Idx]) {
922 if (Ty != V->getType())
923 report_fatal_error("Type mismatch in constant table!");
924 return cast<Constant>(V);
927 // Create and return a placeholder, which will later be RAUW'd.
928 Constant *C = new ConstantPlaceHolder(Ty, Context);
933 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
934 OperatorConstraint OC) {
935 // Bail out for a clearly invalid value. This would make us call resize(0)
942 if (Value *V = ValuePtrs[Idx]) {
943 // If the types don't match, it's invalid.
944 if (Ty && Ty != V->getType())
948 // Use dyn_cast to enforce operator constraints
951 return dyn_cast<CatchPadInst>(V);
953 return dyn_cast<CleanupPadInst>(V);
955 llvm_unreachable("Unexpected operator constraint");
959 // No type specified, must be invalid reference.
960 if (!Ty) return nullptr;
962 // Create and return a placeholder, which will later be RAUW'd.
966 V = new Argument(Ty);
969 BasicBlock *BB = BasicBlock::Create(Context);
970 V = CatchPadInst::Create(BB, BB, {});
974 assert(OC == OC_CleanupPad && "unexpected operator constraint");
975 V = CleanupPadInst::Create(Context, {});
983 /// Once all constants are read, this method bulk resolves any forward
984 /// references. The idea behind this is that we sometimes get constants (such
985 /// as large arrays) which reference *many* forward ref constants. Replacing
986 /// each of these causes a lot of thrashing when building/reuniquing the
987 /// constant. Instead of doing this, we look at all the uses and rewrite all
988 /// the place holders at once for any constant that uses a placeholder.
989 void BitcodeReaderValueList::resolveConstantForwardRefs() {
990 // Sort the values by-pointer so that they are efficient to look up with a
992 std::sort(ResolveConstants.begin(), ResolveConstants.end());
994 SmallVector<Constant*, 64> NewOps;
996 while (!ResolveConstants.empty()) {
997 Value *RealVal = operator[](ResolveConstants.back().second);
998 Constant *Placeholder = ResolveConstants.back().first;
999 ResolveConstants.pop_back();
1001 // Loop over all users of the placeholder, updating them to reference the
1002 // new value. If they reference more than one placeholder, update them all
1004 while (!Placeholder->use_empty()) {
1005 auto UI = Placeholder->user_begin();
1008 // If the using object isn't uniqued, just update the operands. This
1009 // handles instructions and initializers for global variables.
1010 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1011 UI.getUse().set(RealVal);
1015 // Otherwise, we have a constant that uses the placeholder. Replace that
1016 // constant with a new constant that has *all* placeholder uses updated.
1017 Constant *UserC = cast<Constant>(U);
1018 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1021 if (!isa<ConstantPlaceHolder>(*I)) {
1022 // Not a placeholder reference.
1024 } else if (*I == Placeholder) {
1025 // Common case is that it just references this one placeholder.
1028 // Otherwise, look up the placeholder in ResolveConstants.
1029 ResolveConstantsTy::iterator It =
1030 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1031 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1033 assert(It != ResolveConstants.end() && It->first == *I);
1034 NewOp = operator[](It->second);
1037 NewOps.push_back(cast<Constant>(NewOp));
1040 // Make the new constant.
1042 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1043 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1044 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1045 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1046 } else if (isa<ConstantVector>(UserC)) {
1047 NewC = ConstantVector::get(NewOps);
1049 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1050 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1053 UserC->replaceAllUsesWith(NewC);
1054 UserC->destroyConstant();
1058 // Update all ValueHandles, they should be the only users at this point.
1059 Placeholder->replaceAllUsesWith(RealVal);
1064 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1065 if (Idx == size()) {
1073 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1079 // If there was a forward reference to this value, replace it.
1080 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1081 PrevMD->replaceAllUsesWith(MD);
1085 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1089 if (Metadata *MD = MDValuePtrs[Idx])
1092 // Track forward refs to be resolved later.
1094 MinFwdRef = std::min(MinFwdRef, Idx);
1095 MaxFwdRef = std::max(MaxFwdRef, Idx);
1098 MinFwdRef = MaxFwdRef = Idx;
1102 // Create and return a placeholder, which will later be RAUW'd.
1103 Metadata *MD = MDNode::getTemporary(Context, None).release();
1104 MDValuePtrs[Idx].reset(MD);
1108 void BitcodeReaderMDValueList::tryToResolveCycles() {
1114 // Still forward references... can't resolve cycles.
1117 // Resolve any cycles.
1118 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1119 auto &MD = MDValuePtrs[I];
1120 auto *N = dyn_cast_or_null<MDNode>(MD);
1124 assert(!N->isTemporary() && "Unexpected forward reference");
1128 // Make sure we return early again until there's another forward ref.
1132 Type *BitcodeReader::getTypeByID(unsigned ID) {
1133 // The type table size is always specified correctly.
1134 if (ID >= TypeList.size())
1137 if (Type *Ty = TypeList[ID])
1140 // If we have a forward reference, the only possible case is when it is to a
1141 // named struct. Just create a placeholder for now.
1142 return TypeList[ID] = createIdentifiedStructType(Context);
1145 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1147 auto *Ret = StructType::create(Context, Name);
1148 IdentifiedStructTypes.push_back(Ret);
1152 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1153 auto *Ret = StructType::create(Context);
1154 IdentifiedStructTypes.push_back(Ret);
1159 //===----------------------------------------------------------------------===//
1160 // Functions for parsing blocks from the bitcode file
1161 //===----------------------------------------------------------------------===//
1164 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1165 /// been decoded from the given integer. This function must stay in sync with
1166 /// 'encodeLLVMAttributesForBitcode'.
1167 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1168 uint64_t EncodedAttrs) {
1169 // FIXME: Remove in 4.0.
1171 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1172 // the bits above 31 down by 11 bits.
1173 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1174 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1175 "Alignment must be a power of two.");
1178 B.addAlignmentAttr(Alignment);
1179 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1180 (EncodedAttrs & 0xffff));
1183 std::error_code BitcodeReader::parseAttributeBlock() {
1184 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1185 return error("Invalid record");
1187 if (!MAttributes.empty())
1188 return error("Invalid multiple blocks");
1190 SmallVector<uint64_t, 64> Record;
1192 SmallVector<AttributeSet, 8> Attrs;
1194 // Read all the records.
1196 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1198 switch (Entry.Kind) {
1199 case BitstreamEntry::SubBlock: // Handled for us already.
1200 case BitstreamEntry::Error:
1201 return error("Malformed block");
1202 case BitstreamEntry::EndBlock:
1203 return std::error_code();
1204 case BitstreamEntry::Record:
1205 // The interesting case.
1211 switch (Stream.readRecord(Entry.ID, Record)) {
1212 default: // Default behavior: ignore.
1214 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1215 // FIXME: Remove in 4.0.
1216 if (Record.size() & 1)
1217 return error("Invalid record");
1219 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1221 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1222 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1225 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1229 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1230 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1231 Attrs.push_back(MAttributeGroups[Record[i]]);
1233 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1241 // Returns Attribute::None on unrecognized codes.
1242 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1245 return Attribute::None;
1246 case bitc::ATTR_KIND_ALIGNMENT:
1247 return Attribute::Alignment;
1248 case bitc::ATTR_KIND_ALWAYS_INLINE:
1249 return Attribute::AlwaysInline;
1250 case bitc::ATTR_KIND_ARGMEMONLY:
1251 return Attribute::ArgMemOnly;
1252 case bitc::ATTR_KIND_BUILTIN:
1253 return Attribute::Builtin;
1254 case bitc::ATTR_KIND_BY_VAL:
1255 return Attribute::ByVal;
1256 case bitc::ATTR_KIND_IN_ALLOCA:
1257 return Attribute::InAlloca;
1258 case bitc::ATTR_KIND_COLD:
1259 return Attribute::Cold;
1260 case bitc::ATTR_KIND_CONVERGENT:
1261 return Attribute::Convergent;
1262 case bitc::ATTR_KIND_INLINE_HINT:
1263 return Attribute::InlineHint;
1264 case bitc::ATTR_KIND_IN_REG:
1265 return Attribute::InReg;
1266 case bitc::ATTR_KIND_JUMP_TABLE:
1267 return Attribute::JumpTable;
1268 case bitc::ATTR_KIND_MIN_SIZE:
1269 return Attribute::MinSize;
1270 case bitc::ATTR_KIND_NAKED:
1271 return Attribute::Naked;
1272 case bitc::ATTR_KIND_NEST:
1273 return Attribute::Nest;
1274 case bitc::ATTR_KIND_NO_ALIAS:
1275 return Attribute::NoAlias;
1276 case bitc::ATTR_KIND_NO_BUILTIN:
1277 return Attribute::NoBuiltin;
1278 case bitc::ATTR_KIND_NO_CAPTURE:
1279 return Attribute::NoCapture;
1280 case bitc::ATTR_KIND_NO_DUPLICATE:
1281 return Attribute::NoDuplicate;
1282 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1283 return Attribute::NoImplicitFloat;
1284 case bitc::ATTR_KIND_NO_INLINE:
1285 return Attribute::NoInline;
1286 case bitc::ATTR_KIND_NON_LAZY_BIND:
1287 return Attribute::NonLazyBind;
1288 case bitc::ATTR_KIND_NON_NULL:
1289 return Attribute::NonNull;
1290 case bitc::ATTR_KIND_DEREFERENCEABLE:
1291 return Attribute::Dereferenceable;
1292 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1293 return Attribute::DereferenceableOrNull;
1294 case bitc::ATTR_KIND_NO_RED_ZONE:
1295 return Attribute::NoRedZone;
1296 case bitc::ATTR_KIND_NO_RETURN:
1297 return Attribute::NoReturn;
1298 case bitc::ATTR_KIND_NO_UNWIND:
1299 return Attribute::NoUnwind;
1300 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1301 return Attribute::OptimizeForSize;
1302 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1303 return Attribute::OptimizeNone;
1304 case bitc::ATTR_KIND_READ_NONE:
1305 return Attribute::ReadNone;
1306 case bitc::ATTR_KIND_READ_ONLY:
1307 return Attribute::ReadOnly;
1308 case bitc::ATTR_KIND_RETURNED:
1309 return Attribute::Returned;
1310 case bitc::ATTR_KIND_RETURNS_TWICE:
1311 return Attribute::ReturnsTwice;
1312 case bitc::ATTR_KIND_S_EXT:
1313 return Attribute::SExt;
1314 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1315 return Attribute::StackAlignment;
1316 case bitc::ATTR_KIND_STACK_PROTECT:
1317 return Attribute::StackProtect;
1318 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1319 return Attribute::StackProtectReq;
1320 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1321 return Attribute::StackProtectStrong;
1322 case bitc::ATTR_KIND_SAFESTACK:
1323 return Attribute::SafeStack;
1324 case bitc::ATTR_KIND_STRUCT_RET:
1325 return Attribute::StructRet;
1326 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1327 return Attribute::SanitizeAddress;
1328 case bitc::ATTR_KIND_SANITIZE_THREAD:
1329 return Attribute::SanitizeThread;
1330 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1331 return Attribute::SanitizeMemory;
1332 case bitc::ATTR_KIND_UW_TABLE:
1333 return Attribute::UWTable;
1334 case bitc::ATTR_KIND_Z_EXT:
1335 return Attribute::ZExt;
1339 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1340 unsigned &Alignment) {
1341 // Note: Alignment in bitcode files is incremented by 1, so that zero
1342 // can be used for default alignment.
1343 if (Exponent > Value::MaxAlignmentExponent + 1)
1344 return error("Invalid alignment value");
1345 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1346 return std::error_code();
1349 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1350 Attribute::AttrKind *Kind) {
1351 *Kind = getAttrFromCode(Code);
1352 if (*Kind == Attribute::None)
1353 return error(BitcodeError::CorruptedBitcode,
1354 "Unknown attribute kind (" + Twine(Code) + ")");
1355 return std::error_code();
1358 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1359 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1360 return error("Invalid record");
1362 if (!MAttributeGroups.empty())
1363 return error("Invalid multiple blocks");
1365 SmallVector<uint64_t, 64> Record;
1367 // Read all the records.
1369 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1371 switch (Entry.Kind) {
1372 case BitstreamEntry::SubBlock: // Handled for us already.
1373 case BitstreamEntry::Error:
1374 return error("Malformed block");
1375 case BitstreamEntry::EndBlock:
1376 return std::error_code();
1377 case BitstreamEntry::Record:
1378 // The interesting case.
1384 switch (Stream.readRecord(Entry.ID, Record)) {
1385 default: // Default behavior: ignore.
1387 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1388 if (Record.size() < 3)
1389 return error("Invalid record");
1391 uint64_t GrpID = Record[0];
1392 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1395 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1396 if (Record[i] == 0) { // Enum attribute
1397 Attribute::AttrKind Kind;
1398 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1401 B.addAttribute(Kind);
1402 } else if (Record[i] == 1) { // Integer attribute
1403 Attribute::AttrKind Kind;
1404 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1406 if (Kind == Attribute::Alignment)
1407 B.addAlignmentAttr(Record[++i]);
1408 else if (Kind == Attribute::StackAlignment)
1409 B.addStackAlignmentAttr(Record[++i]);
1410 else if (Kind == Attribute::Dereferenceable)
1411 B.addDereferenceableAttr(Record[++i]);
1412 else if (Kind == Attribute::DereferenceableOrNull)
1413 B.addDereferenceableOrNullAttr(Record[++i]);
1414 } else { // String attribute
1415 assert((Record[i] == 3 || Record[i] == 4) &&
1416 "Invalid attribute group entry");
1417 bool HasValue = (Record[i++] == 4);
1418 SmallString<64> KindStr;
1419 SmallString<64> ValStr;
1421 while (Record[i] != 0 && i != e)
1422 KindStr += Record[i++];
1423 assert(Record[i] == 0 && "Kind string not null terminated");
1426 // Has a value associated with it.
1427 ++i; // Skip the '0' that terminates the "kind" string.
1428 while (Record[i] != 0 && i != e)
1429 ValStr += Record[i++];
1430 assert(Record[i] == 0 && "Value string not null terminated");
1433 B.addAttribute(KindStr.str(), ValStr.str());
1437 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1444 std::error_code BitcodeReader::parseTypeTable() {
1445 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1446 return error("Invalid record");
1448 return parseTypeTableBody();
1451 std::error_code BitcodeReader::parseTypeTableBody() {
1452 if (!TypeList.empty())
1453 return error("Invalid multiple blocks");
1455 SmallVector<uint64_t, 64> Record;
1456 unsigned NumRecords = 0;
1458 SmallString<64> TypeName;
1460 // Read all the records for this type table.
1462 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1464 switch (Entry.Kind) {
1465 case BitstreamEntry::SubBlock: // Handled for us already.
1466 case BitstreamEntry::Error:
1467 return error("Malformed block");
1468 case BitstreamEntry::EndBlock:
1469 if (NumRecords != TypeList.size())
1470 return error("Malformed block");
1471 return std::error_code();
1472 case BitstreamEntry::Record:
1473 // The interesting case.
1479 Type *ResultTy = nullptr;
1480 switch (Stream.readRecord(Entry.ID, Record)) {
1482 return error("Invalid value");
1483 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1484 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1485 // type list. This allows us to reserve space.
1486 if (Record.size() < 1)
1487 return error("Invalid record");
1488 TypeList.resize(Record[0]);
1490 case bitc::TYPE_CODE_VOID: // VOID
1491 ResultTy = Type::getVoidTy(Context);
1493 case bitc::TYPE_CODE_HALF: // HALF
1494 ResultTy = Type::getHalfTy(Context);
1496 case bitc::TYPE_CODE_FLOAT: // FLOAT
1497 ResultTy = Type::getFloatTy(Context);
1499 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1500 ResultTy = Type::getDoubleTy(Context);
1502 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1503 ResultTy = Type::getX86_FP80Ty(Context);
1505 case bitc::TYPE_CODE_FP128: // FP128
1506 ResultTy = Type::getFP128Ty(Context);
1508 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1509 ResultTy = Type::getPPC_FP128Ty(Context);
1511 case bitc::TYPE_CODE_LABEL: // LABEL
1512 ResultTy = Type::getLabelTy(Context);
1514 case bitc::TYPE_CODE_METADATA: // METADATA
1515 ResultTy = Type::getMetadataTy(Context);
1517 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1518 ResultTy = Type::getX86_MMXTy(Context);
1520 case bitc::TYPE_CODE_TOKEN: // TOKEN
1521 ResultTy = Type::getTokenTy(Context);
1523 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1524 if (Record.size() < 1)
1525 return error("Invalid record");
1527 uint64_t NumBits = Record[0];
1528 if (NumBits < IntegerType::MIN_INT_BITS ||
1529 NumBits > IntegerType::MAX_INT_BITS)
1530 return error("Bitwidth for integer type out of range");
1531 ResultTy = IntegerType::get(Context, NumBits);
1534 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1535 // [pointee type, address space]
1536 if (Record.size() < 1)
1537 return error("Invalid record");
1538 unsigned AddressSpace = 0;
1539 if (Record.size() == 2)
1540 AddressSpace = Record[1];
1541 ResultTy = getTypeByID(Record[0]);
1543 !PointerType::isValidElementType(ResultTy))
1544 return error("Invalid type");
1545 ResultTy = PointerType::get(ResultTy, AddressSpace);
1548 case bitc::TYPE_CODE_FUNCTION_OLD: {
1549 // FIXME: attrid is dead, remove it in LLVM 4.0
1550 // FUNCTION: [vararg, attrid, retty, paramty x N]
1551 if (Record.size() < 3)
1552 return error("Invalid record");
1553 SmallVector<Type*, 8> ArgTys;
1554 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1555 if (Type *T = getTypeByID(Record[i]))
1556 ArgTys.push_back(T);
1561 ResultTy = getTypeByID(Record[2]);
1562 if (!ResultTy || ArgTys.size() < Record.size()-3)
1563 return error("Invalid type");
1565 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1568 case bitc::TYPE_CODE_FUNCTION: {
1569 // FUNCTION: [vararg, retty, paramty x N]
1570 if (Record.size() < 2)
1571 return error("Invalid record");
1572 SmallVector<Type*, 8> ArgTys;
1573 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1574 if (Type *T = getTypeByID(Record[i])) {
1575 if (!FunctionType::isValidArgumentType(T))
1576 return error("Invalid function argument type");
1577 ArgTys.push_back(T);
1583 ResultTy = getTypeByID(Record[1]);
1584 if (!ResultTy || ArgTys.size() < Record.size()-2)
1585 return error("Invalid type");
1587 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1590 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1591 if (Record.size() < 1)
1592 return error("Invalid record");
1593 SmallVector<Type*, 8> EltTys;
1594 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1595 if (Type *T = getTypeByID(Record[i]))
1596 EltTys.push_back(T);
1600 if (EltTys.size() != Record.size()-1)
1601 return error("Invalid type");
1602 ResultTy = StructType::get(Context, EltTys, Record[0]);
1605 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1606 if (convertToString(Record, 0, TypeName))
1607 return error("Invalid record");
1610 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1611 if (Record.size() < 1)
1612 return error("Invalid record");
1614 if (NumRecords >= TypeList.size())
1615 return error("Invalid TYPE table");
1617 // Check to see if this was forward referenced, if so fill in the temp.
1618 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1620 Res->setName(TypeName);
1621 TypeList[NumRecords] = nullptr;
1622 } else // Otherwise, create a new struct.
1623 Res = createIdentifiedStructType(Context, TypeName);
1626 SmallVector<Type*, 8> EltTys;
1627 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1628 if (Type *T = getTypeByID(Record[i]))
1629 EltTys.push_back(T);
1633 if (EltTys.size() != Record.size()-1)
1634 return error("Invalid record");
1635 Res->setBody(EltTys, Record[0]);
1639 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1640 if (Record.size() != 1)
1641 return error("Invalid record");
1643 if (NumRecords >= TypeList.size())
1644 return error("Invalid TYPE table");
1646 // Check to see if this was forward referenced, if so fill in the temp.
1647 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1649 Res->setName(TypeName);
1650 TypeList[NumRecords] = nullptr;
1651 } else // Otherwise, create a new struct with no body.
1652 Res = createIdentifiedStructType(Context, TypeName);
1657 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1658 if (Record.size() < 2)
1659 return error("Invalid record");
1660 ResultTy = getTypeByID(Record[1]);
1661 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1662 return error("Invalid type");
1663 ResultTy = ArrayType::get(ResultTy, Record[0]);
1665 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1666 if (Record.size() < 2)
1667 return error("Invalid record");
1669 return error("Invalid vector length");
1670 ResultTy = getTypeByID(Record[1]);
1671 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1672 return error("Invalid type");
1673 ResultTy = VectorType::get(ResultTy, Record[0]);
1677 if (NumRecords >= TypeList.size())
1678 return error("Invalid TYPE table");
1679 if (TypeList[NumRecords])
1681 "Invalid TYPE table: Only named structs can be forward referenced");
1682 assert(ResultTy && "Didn't read a type?");
1683 TypeList[NumRecords++] = ResultTy;
1687 std::error_code BitcodeReader::parseOperandBundleTags() {
1688 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1689 return error("Invalid record");
1691 if (!BundleTags.empty())
1692 return error("Invalid multiple blocks");
1694 SmallVector<uint64_t, 64> Record;
1697 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1699 switch (Entry.Kind) {
1700 case BitstreamEntry::SubBlock: // Handled for us already.
1701 case BitstreamEntry::Error:
1702 return error("Malformed block");
1703 case BitstreamEntry::EndBlock:
1704 return std::error_code();
1705 case BitstreamEntry::Record:
1706 // The interesting case.
1710 // Tags are implicitly mapped to integers by their order.
1712 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1713 return error("Invalid record");
1715 // OPERAND_BUNDLE_TAG: [strchr x N]
1716 BundleTags.emplace_back();
1717 if (convertToString(Record, 0, BundleTags.back()))
1718 return error("Invalid record");
1723 /// Associate a value with its name from the given index in the provided record.
1724 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1725 unsigned NameIndex, Triple &TT) {
1726 SmallString<128> ValueName;
1727 if (convertToString(Record, NameIndex, ValueName))
1728 return error("Invalid record");
1729 unsigned ValueID = Record[0];
1730 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1731 return error("Invalid record");
1732 Value *V = ValueList[ValueID];
1734 V->setName(StringRef(ValueName.data(), ValueName.size()));
1735 auto *GO = dyn_cast<GlobalObject>(V);
1737 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1738 if (TT.isOSBinFormatMachO())
1739 GO->setComdat(nullptr);
1741 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1747 /// Parse the value symbol table at either the current parsing location or
1748 /// at the given bit offset if provided.
1749 std::error_code BitcodeReader::parseValueSymbolTable(unsigned Offset) {
1750 uint64_t CurrentBit;
1751 // Pass in the Offset to distinguish between calling for the module-level
1752 // VST (where we want to jump to the VST offset) and the function-level
1753 // VST (where we don't).
1755 // Save the current parsing location so we can jump back at the end
1757 CurrentBit = Stream.GetCurrentBitNo();
1758 Stream.JumpToBit(Offset * 32);
1760 // Do some checking if we are in debug mode.
1761 BitstreamEntry Entry = Stream.advance();
1762 assert(Entry.Kind == BitstreamEntry::SubBlock);
1763 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1765 // In NDEBUG mode ignore the output so we don't get an unused variable
1771 // Compute the delta between the bitcode indices in the VST (the word offset
1772 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1773 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1774 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1775 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1776 // just before entering the VST subblock because: 1) the EnterSubBlock
1777 // changes the AbbrevID width; 2) the VST block is nested within the same
1778 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1779 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1780 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1781 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1782 unsigned FuncBitcodeOffsetDelta =
1783 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1785 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1786 return error("Invalid record");
1788 SmallVector<uint64_t, 64> Record;
1790 Triple TT(TheModule->getTargetTriple());
1792 // Read all the records for this value table.
1793 SmallString<128> ValueName;
1795 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1797 switch (Entry.Kind) {
1798 case BitstreamEntry::SubBlock: // Handled for us already.
1799 case BitstreamEntry::Error:
1800 return error("Malformed block");
1801 case BitstreamEntry::EndBlock:
1803 Stream.JumpToBit(CurrentBit);
1804 return std::error_code();
1805 case BitstreamEntry::Record:
1806 // The interesting case.
1812 switch (Stream.readRecord(Entry.ID, Record)) {
1813 default: // Default behavior: unknown type.
1815 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1816 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1817 if (std::error_code EC = ValOrErr.getError())
1822 case bitc::VST_CODE_FNENTRY: {
1823 // VST_FNENTRY: [valueid, offset, namechar x N]
1824 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1825 if (std::error_code EC = ValOrErr.getError())
1827 Value *V = ValOrErr.get();
1829 auto *GO = dyn_cast<GlobalObject>(V);
1831 // If this is an alias, need to get the actual Function object
1832 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1833 auto *GA = dyn_cast<GlobalAlias>(V);
1835 GO = GA->getBaseObject();
1839 uint64_t FuncWordOffset = Record[1];
1840 Function *F = dyn_cast<Function>(GO);
1842 uint64_t FuncBitOffset = FuncWordOffset * 32;
1843 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1844 // Set the LastFunctionBlockBit to point to the last function block.
1845 // Later when parsing is resumed after function materialization,
1846 // we can simply skip that last function block.
1847 if (FuncBitOffset > LastFunctionBlockBit)
1848 LastFunctionBlockBit = FuncBitOffset;
1851 case bitc::VST_CODE_BBENTRY: {
1852 if (convertToString(Record, 1, ValueName))
1853 return error("Invalid record");
1854 BasicBlock *BB = getBasicBlock(Record[0]);
1856 return error("Invalid record");
1858 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1866 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1868 std::error_code BitcodeReader::parseMetadata() {
1869 IsMetadataMaterialized = true;
1870 unsigned NextMDValueNo = MDValueList.size();
1872 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1873 return error("Invalid record");
1875 SmallVector<uint64_t, 64> Record;
1878 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1879 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1881 return getMD(ID - 1);
1884 auto getMDString = [&](unsigned ID) -> MDString *{
1885 // This requires that the ID is not really a forward reference. In
1886 // particular, the MDString must already have been resolved.
1887 return cast_or_null<MDString>(getMDOrNull(ID));
1890 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1891 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1893 // Read all the records.
1895 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1897 switch (Entry.Kind) {
1898 case BitstreamEntry::SubBlock: // Handled for us already.
1899 case BitstreamEntry::Error:
1900 return error("Malformed block");
1901 case BitstreamEntry::EndBlock:
1902 MDValueList.tryToResolveCycles();
1903 return std::error_code();
1904 case BitstreamEntry::Record:
1905 // The interesting case.
1911 unsigned Code = Stream.readRecord(Entry.ID, Record);
1912 bool IsDistinct = false;
1914 default: // Default behavior: ignore.
1916 case bitc::METADATA_NAME: {
1917 // Read name of the named metadata.
1918 SmallString<8> Name(Record.begin(), Record.end());
1920 Code = Stream.ReadCode();
1922 unsigned NextBitCode = Stream.readRecord(Code, Record);
1923 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1924 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1926 // Read named metadata elements.
1927 unsigned Size = Record.size();
1928 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1929 for (unsigned i = 0; i != Size; ++i) {
1930 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1932 return error("Invalid record");
1933 NMD->addOperand(MD);
1937 case bitc::METADATA_OLD_FN_NODE: {
1938 // FIXME: Remove in 4.0.
1939 // This is a LocalAsMetadata record, the only type of function-local
1941 if (Record.size() % 2 == 1)
1942 return error("Invalid record");
1944 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1945 // to be legal, but there's no upgrade path.
1946 auto dropRecord = [&] {
1947 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1949 if (Record.size() != 2) {
1954 Type *Ty = getTypeByID(Record[0]);
1955 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1960 MDValueList.assignValue(
1961 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1965 case bitc::METADATA_OLD_NODE: {
1966 // FIXME: Remove in 4.0.
1967 if (Record.size() % 2 == 1)
1968 return error("Invalid record");
1970 unsigned Size = Record.size();
1971 SmallVector<Metadata *, 8> Elts;
1972 for (unsigned i = 0; i != Size; i += 2) {
1973 Type *Ty = getTypeByID(Record[i]);
1975 return error("Invalid record");
1976 if (Ty->isMetadataTy())
1977 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1978 else if (!Ty->isVoidTy()) {
1980 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1981 assert(isa<ConstantAsMetadata>(MD) &&
1982 "Expected non-function-local metadata");
1985 Elts.push_back(nullptr);
1987 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1990 case bitc::METADATA_VALUE: {
1991 if (Record.size() != 2)
1992 return error("Invalid record");
1994 Type *Ty = getTypeByID(Record[0]);
1995 if (Ty->isMetadataTy() || Ty->isVoidTy())
1996 return error("Invalid record");
1998 MDValueList.assignValue(
1999 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2003 case bitc::METADATA_DISTINCT_NODE:
2006 case bitc::METADATA_NODE: {
2007 SmallVector<Metadata *, 8> Elts;
2008 Elts.reserve(Record.size());
2009 for (unsigned ID : Record)
2010 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2011 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2012 : MDNode::get(Context, Elts),
2016 case bitc::METADATA_LOCATION: {
2017 if (Record.size() != 5)
2018 return error("Invalid record");
2020 unsigned Line = Record[1];
2021 unsigned Column = Record[2];
2022 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2023 Metadata *InlinedAt =
2024 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2025 MDValueList.assignValue(
2026 GET_OR_DISTINCT(DILocation, Record[0],
2027 (Context, Line, Column, Scope, InlinedAt)),
2031 case bitc::METADATA_GENERIC_DEBUG: {
2032 if (Record.size() < 4)
2033 return error("Invalid record");
2035 unsigned Tag = Record[1];
2036 unsigned Version = Record[2];
2038 if (Tag >= 1u << 16 || Version != 0)
2039 return error("Invalid record");
2041 auto *Header = getMDString(Record[3]);
2042 SmallVector<Metadata *, 8> DwarfOps;
2043 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2044 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2046 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2047 (Context, Tag, Header, DwarfOps)),
2051 case bitc::METADATA_SUBRANGE: {
2052 if (Record.size() != 3)
2053 return error("Invalid record");
2055 MDValueList.assignValue(
2056 GET_OR_DISTINCT(DISubrange, Record[0],
2057 (Context, Record[1], unrotateSign(Record[2]))),
2061 case bitc::METADATA_ENUMERATOR: {
2062 if (Record.size() != 3)
2063 return error("Invalid record");
2065 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2066 (Context, unrotateSign(Record[1]),
2067 getMDString(Record[2]))),
2071 case bitc::METADATA_BASIC_TYPE: {
2072 if (Record.size() != 6)
2073 return error("Invalid record");
2075 MDValueList.assignValue(
2076 GET_OR_DISTINCT(DIBasicType, Record[0],
2077 (Context, Record[1], getMDString(Record[2]),
2078 Record[3], Record[4], Record[5])),
2082 case bitc::METADATA_DERIVED_TYPE: {
2083 if (Record.size() != 12)
2084 return error("Invalid record");
2086 MDValueList.assignValue(
2087 GET_OR_DISTINCT(DIDerivedType, Record[0],
2088 (Context, Record[1], getMDString(Record[2]),
2089 getMDOrNull(Record[3]), Record[4],
2090 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2091 Record[7], Record[8], Record[9], Record[10],
2092 getMDOrNull(Record[11]))),
2096 case bitc::METADATA_COMPOSITE_TYPE: {
2097 if (Record.size() != 16)
2098 return error("Invalid record");
2100 MDValueList.assignValue(
2101 GET_OR_DISTINCT(DICompositeType, Record[0],
2102 (Context, Record[1], getMDString(Record[2]),
2103 getMDOrNull(Record[3]), Record[4],
2104 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2105 Record[7], Record[8], Record[9], Record[10],
2106 getMDOrNull(Record[11]), Record[12],
2107 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2108 getMDString(Record[15]))),
2112 case bitc::METADATA_SUBROUTINE_TYPE: {
2113 if (Record.size() != 3)
2114 return error("Invalid record");
2116 MDValueList.assignValue(
2117 GET_OR_DISTINCT(DISubroutineType, Record[0],
2118 (Context, Record[1], getMDOrNull(Record[2]))),
2123 case bitc::METADATA_MODULE: {
2124 if (Record.size() != 6)
2125 return error("Invalid record");
2127 MDValueList.assignValue(
2128 GET_OR_DISTINCT(DIModule, Record[0],
2129 (Context, getMDOrNull(Record[1]),
2130 getMDString(Record[2]), getMDString(Record[3]),
2131 getMDString(Record[4]), getMDString(Record[5]))),
2136 case bitc::METADATA_FILE: {
2137 if (Record.size() != 3)
2138 return error("Invalid record");
2140 MDValueList.assignValue(
2141 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2142 getMDString(Record[2]))),
2146 case bitc::METADATA_COMPILE_UNIT: {
2147 if (Record.size() < 14 || Record.size() > 15)
2148 return error("Invalid record");
2150 // Ignore Record[1], which indicates whether this compile unit is
2151 // distinct. It's always distinct.
2152 MDValueList.assignValue(
2153 DICompileUnit::getDistinct(
2154 Context, Record[1], getMDOrNull(Record[2]),
2155 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2156 Record[6], getMDString(Record[7]), Record[8],
2157 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2158 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2159 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2163 case bitc::METADATA_SUBPROGRAM: {
2164 if (Record.size() != 19)
2165 return error("Invalid record");
2167 MDValueList.assignValue(
2170 Record[0] || Record[8], // All definitions should be distinct.
2171 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2172 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2173 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2174 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2175 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
2176 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
2180 case bitc::METADATA_LEXICAL_BLOCK: {
2181 if (Record.size() != 5)
2182 return error("Invalid record");
2184 MDValueList.assignValue(
2185 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2186 (Context, getMDOrNull(Record[1]),
2187 getMDOrNull(Record[2]), Record[3], Record[4])),
2191 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2192 if (Record.size() != 4)
2193 return error("Invalid record");
2195 MDValueList.assignValue(
2196 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2197 (Context, getMDOrNull(Record[1]),
2198 getMDOrNull(Record[2]), Record[3])),
2202 case bitc::METADATA_NAMESPACE: {
2203 if (Record.size() != 5)
2204 return error("Invalid record");
2206 MDValueList.assignValue(
2207 GET_OR_DISTINCT(DINamespace, Record[0],
2208 (Context, getMDOrNull(Record[1]),
2209 getMDOrNull(Record[2]), getMDString(Record[3]),
2214 case bitc::METADATA_TEMPLATE_TYPE: {
2215 if (Record.size() != 3)
2216 return error("Invalid record");
2218 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2220 (Context, getMDString(Record[1]),
2221 getMDOrNull(Record[2]))),
2225 case bitc::METADATA_TEMPLATE_VALUE: {
2226 if (Record.size() != 5)
2227 return error("Invalid record");
2229 MDValueList.assignValue(
2230 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2231 (Context, Record[1], getMDString(Record[2]),
2232 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2236 case bitc::METADATA_GLOBAL_VAR: {
2237 if (Record.size() != 11)
2238 return error("Invalid record");
2240 MDValueList.assignValue(
2241 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2242 (Context, getMDOrNull(Record[1]),
2243 getMDString(Record[2]), getMDString(Record[3]),
2244 getMDOrNull(Record[4]), Record[5],
2245 getMDOrNull(Record[6]), Record[7], Record[8],
2246 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2250 case bitc::METADATA_LOCAL_VAR: {
2251 // 10th field is for the obseleted 'inlinedAt:' field.
2252 if (Record.size() < 8 || Record.size() > 10)
2253 return error("Invalid record");
2255 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2256 // DW_TAG_arg_variable.
2257 bool HasTag = Record.size() > 8;
2258 MDValueList.assignValue(
2259 GET_OR_DISTINCT(DILocalVariable, Record[0],
2260 (Context, getMDOrNull(Record[1 + HasTag]),
2261 getMDString(Record[2 + HasTag]),
2262 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2263 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2264 Record[7 + HasTag])),
2268 case bitc::METADATA_EXPRESSION: {
2269 if (Record.size() < 1)
2270 return error("Invalid record");
2272 MDValueList.assignValue(
2273 GET_OR_DISTINCT(DIExpression, Record[0],
2274 (Context, makeArrayRef(Record).slice(1))),
2278 case bitc::METADATA_OBJC_PROPERTY: {
2279 if (Record.size() != 8)
2280 return error("Invalid record");
2282 MDValueList.assignValue(
2283 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2284 (Context, getMDString(Record[1]),
2285 getMDOrNull(Record[2]), Record[3],
2286 getMDString(Record[4]), getMDString(Record[5]),
2287 Record[6], getMDOrNull(Record[7]))),
2291 case bitc::METADATA_IMPORTED_ENTITY: {
2292 if (Record.size() != 6)
2293 return error("Invalid record");
2295 MDValueList.assignValue(
2296 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2297 (Context, Record[1], getMDOrNull(Record[2]),
2298 getMDOrNull(Record[3]), Record[4],
2299 getMDString(Record[5]))),
2303 case bitc::METADATA_STRING: {
2304 std::string String(Record.begin(), Record.end());
2305 llvm::UpgradeMDStringConstant(String);
2306 Metadata *MD = MDString::get(Context, String);
2307 MDValueList.assignValue(MD, NextMDValueNo++);
2310 case bitc::METADATA_KIND: {
2311 if (Record.size() < 2)
2312 return error("Invalid record");
2314 unsigned Kind = Record[0];
2315 SmallString<8> Name(Record.begin()+1, Record.end());
2317 unsigned NewKind = TheModule->getMDKindID(Name.str());
2318 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2319 return error("Conflicting METADATA_KIND records");
2324 #undef GET_OR_DISTINCT
2327 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2329 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2334 // There is no such thing as -0 with integers. "-0" really means MININT.
2338 /// Resolve all of the initializers for global values and aliases that we can.
2339 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2340 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2341 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2342 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2343 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2344 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2346 GlobalInitWorklist.swap(GlobalInits);
2347 AliasInitWorklist.swap(AliasInits);
2348 FunctionPrefixWorklist.swap(FunctionPrefixes);
2349 FunctionPrologueWorklist.swap(FunctionPrologues);
2350 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2352 while (!GlobalInitWorklist.empty()) {
2353 unsigned ValID = GlobalInitWorklist.back().second;
2354 if (ValID >= ValueList.size()) {
2355 // Not ready to resolve this yet, it requires something later in the file.
2356 GlobalInits.push_back(GlobalInitWorklist.back());
2358 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2359 GlobalInitWorklist.back().first->setInitializer(C);
2361 return error("Expected a constant");
2363 GlobalInitWorklist.pop_back();
2366 while (!AliasInitWorklist.empty()) {
2367 unsigned ValID = AliasInitWorklist.back().second;
2368 if (ValID >= ValueList.size()) {
2369 AliasInits.push_back(AliasInitWorklist.back());
2371 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2373 return error("Expected a constant");
2374 GlobalAlias *Alias = AliasInitWorklist.back().first;
2375 if (C->getType() != Alias->getType())
2376 return error("Alias and aliasee types don't match");
2377 Alias->setAliasee(C);
2379 AliasInitWorklist.pop_back();
2382 while (!FunctionPrefixWorklist.empty()) {
2383 unsigned ValID = FunctionPrefixWorklist.back().second;
2384 if (ValID >= ValueList.size()) {
2385 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2387 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2388 FunctionPrefixWorklist.back().first->setPrefixData(C);
2390 return error("Expected a constant");
2392 FunctionPrefixWorklist.pop_back();
2395 while (!FunctionPrologueWorklist.empty()) {
2396 unsigned ValID = FunctionPrologueWorklist.back().second;
2397 if (ValID >= ValueList.size()) {
2398 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2400 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2401 FunctionPrologueWorklist.back().first->setPrologueData(C);
2403 return error("Expected a constant");
2405 FunctionPrologueWorklist.pop_back();
2408 while (!FunctionPersonalityFnWorklist.empty()) {
2409 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2410 if (ValID >= ValueList.size()) {
2411 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2413 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2414 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2416 return error("Expected a constant");
2418 FunctionPersonalityFnWorklist.pop_back();
2421 return std::error_code();
2424 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2425 SmallVector<uint64_t, 8> Words(Vals.size());
2426 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2427 BitcodeReader::decodeSignRotatedValue);
2429 return APInt(TypeBits, Words);
2432 std::error_code BitcodeReader::parseConstants() {
2433 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2434 return error("Invalid record");
2436 SmallVector<uint64_t, 64> Record;
2438 // Read all the records for this value table.
2439 Type *CurTy = Type::getInt32Ty(Context);
2440 unsigned NextCstNo = ValueList.size();
2442 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2444 switch (Entry.Kind) {
2445 case BitstreamEntry::SubBlock: // Handled for us already.
2446 case BitstreamEntry::Error:
2447 return error("Malformed block");
2448 case BitstreamEntry::EndBlock:
2449 if (NextCstNo != ValueList.size())
2450 return error("Invalid ronstant reference");
2452 // Once all the constants have been read, go through and resolve forward
2454 ValueList.resolveConstantForwardRefs();
2455 return std::error_code();
2456 case BitstreamEntry::Record:
2457 // The interesting case.
2464 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2466 default: // Default behavior: unknown constant
2467 case bitc::CST_CODE_UNDEF: // UNDEF
2468 V = UndefValue::get(CurTy);
2470 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2472 return error("Invalid record");
2473 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2474 return error("Invalid record");
2475 CurTy = TypeList[Record[0]];
2476 continue; // Skip the ValueList manipulation.
2477 case bitc::CST_CODE_NULL: // NULL
2478 V = Constant::getNullValue(CurTy);
2480 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2481 if (!CurTy->isIntegerTy() || Record.empty())
2482 return error("Invalid record");
2483 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2485 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2486 if (!CurTy->isIntegerTy() || Record.empty())
2487 return error("Invalid record");
2490 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2491 V = ConstantInt::get(Context, VInt);
2495 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2497 return error("Invalid record");
2498 if (CurTy->isHalfTy())
2499 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2500 APInt(16, (uint16_t)Record[0])));
2501 else if (CurTy->isFloatTy())
2502 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2503 APInt(32, (uint32_t)Record[0])));
2504 else if (CurTy->isDoubleTy())
2505 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2506 APInt(64, Record[0])));
2507 else if (CurTy->isX86_FP80Ty()) {
2508 // Bits are not stored the same way as a normal i80 APInt, compensate.
2509 uint64_t Rearrange[2];
2510 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2511 Rearrange[1] = Record[0] >> 48;
2512 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2513 APInt(80, Rearrange)));
2514 } else if (CurTy->isFP128Ty())
2515 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2516 APInt(128, Record)));
2517 else if (CurTy->isPPC_FP128Ty())
2518 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2519 APInt(128, Record)));
2521 V = UndefValue::get(CurTy);
2525 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2527 return error("Invalid record");
2529 unsigned Size = Record.size();
2530 SmallVector<Constant*, 16> Elts;
2532 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2533 for (unsigned i = 0; i != Size; ++i)
2534 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2535 STy->getElementType(i)));
2536 V = ConstantStruct::get(STy, Elts);
2537 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2538 Type *EltTy = ATy->getElementType();
2539 for (unsigned i = 0; i != Size; ++i)
2540 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2541 V = ConstantArray::get(ATy, Elts);
2542 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2543 Type *EltTy = VTy->getElementType();
2544 for (unsigned i = 0; i != Size; ++i)
2545 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2546 V = ConstantVector::get(Elts);
2548 V = UndefValue::get(CurTy);
2552 case bitc::CST_CODE_STRING: // STRING: [values]
2553 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2555 return error("Invalid record");
2557 SmallString<16> Elts(Record.begin(), Record.end());
2558 V = ConstantDataArray::getString(Context, Elts,
2559 BitCode == bitc::CST_CODE_CSTRING);
2562 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2564 return error("Invalid record");
2566 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2567 unsigned Size = Record.size();
2569 if (EltTy->isIntegerTy(8)) {
2570 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2571 if (isa<VectorType>(CurTy))
2572 V = ConstantDataVector::get(Context, Elts);
2574 V = ConstantDataArray::get(Context, Elts);
2575 } else if (EltTy->isIntegerTy(16)) {
2576 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2577 if (isa<VectorType>(CurTy))
2578 V = ConstantDataVector::get(Context, Elts);
2580 V = ConstantDataArray::get(Context, Elts);
2581 } else if (EltTy->isIntegerTy(32)) {
2582 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2583 if (isa<VectorType>(CurTy))
2584 V = ConstantDataVector::get(Context, Elts);
2586 V = ConstantDataArray::get(Context, Elts);
2587 } else if (EltTy->isIntegerTy(64)) {
2588 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2589 if (isa<VectorType>(CurTy))
2590 V = ConstantDataVector::get(Context, Elts);
2592 V = ConstantDataArray::get(Context, Elts);
2593 } else if (EltTy->isFloatTy()) {
2594 SmallVector<float, 16> Elts(Size);
2595 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2596 if (isa<VectorType>(CurTy))
2597 V = ConstantDataVector::get(Context, Elts);
2599 V = ConstantDataArray::get(Context, Elts);
2600 } else if (EltTy->isDoubleTy()) {
2601 SmallVector<double, 16> Elts(Size);
2602 std::transform(Record.begin(), Record.end(), Elts.begin(),
2604 if (isa<VectorType>(CurTy))
2605 V = ConstantDataVector::get(Context, Elts);
2607 V = ConstantDataArray::get(Context, Elts);
2609 return error("Invalid type for value");
2614 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2615 if (Record.size() < 3)
2616 return error("Invalid record");
2617 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2619 V = UndefValue::get(CurTy); // Unknown binop.
2621 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2622 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2624 if (Record.size() >= 4) {
2625 if (Opc == Instruction::Add ||
2626 Opc == Instruction::Sub ||
2627 Opc == Instruction::Mul ||
2628 Opc == Instruction::Shl) {
2629 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2630 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2631 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2632 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2633 } else if (Opc == Instruction::SDiv ||
2634 Opc == Instruction::UDiv ||
2635 Opc == Instruction::LShr ||
2636 Opc == Instruction::AShr) {
2637 if (Record[3] & (1 << bitc::PEO_EXACT))
2638 Flags |= SDivOperator::IsExact;
2641 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2645 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2646 if (Record.size() < 3)
2647 return error("Invalid record");
2648 int Opc = getDecodedCastOpcode(Record[0]);
2650 V = UndefValue::get(CurTy); // Unknown cast.
2652 Type *OpTy = getTypeByID(Record[1]);
2654 return error("Invalid record");
2655 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2656 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2657 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2661 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2662 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2664 Type *PointeeType = nullptr;
2665 if (Record.size() % 2)
2666 PointeeType = getTypeByID(Record[OpNum++]);
2667 SmallVector<Constant*, 16> Elts;
2668 while (OpNum != Record.size()) {
2669 Type *ElTy = getTypeByID(Record[OpNum++]);
2671 return error("Invalid record");
2672 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2677 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2679 return error("Explicit gep operator type does not match pointee type "
2680 "of pointer operand");
2682 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2683 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2685 bitc::CST_CODE_CE_INBOUNDS_GEP);
2688 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2689 if (Record.size() < 3)
2690 return error("Invalid record");
2692 Type *SelectorTy = Type::getInt1Ty(Context);
2694 // The selector might be an i1 or an <n x i1>
2695 // Get the type from the ValueList before getting a forward ref.
2696 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2697 if (Value *V = ValueList[Record[0]])
2698 if (SelectorTy != V->getType())
2699 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2701 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2703 ValueList.getConstantFwdRef(Record[1],CurTy),
2704 ValueList.getConstantFwdRef(Record[2],CurTy));
2707 case bitc::CST_CODE_CE_EXTRACTELT
2708 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2709 if (Record.size() < 3)
2710 return error("Invalid record");
2712 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2714 return error("Invalid record");
2715 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2716 Constant *Op1 = nullptr;
2717 if (Record.size() == 4) {
2718 Type *IdxTy = getTypeByID(Record[2]);
2720 return error("Invalid record");
2721 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2722 } else // TODO: Remove with llvm 4.0
2723 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2725 return error("Invalid record");
2726 V = ConstantExpr::getExtractElement(Op0, Op1);
2729 case bitc::CST_CODE_CE_INSERTELT
2730 : { // CE_INSERTELT: [opval, opval, opty, opval]
2731 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2732 if (Record.size() < 3 || !OpTy)
2733 return error("Invalid record");
2734 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2735 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2736 OpTy->getElementType());
2737 Constant *Op2 = nullptr;
2738 if (Record.size() == 4) {
2739 Type *IdxTy = getTypeByID(Record[2]);
2741 return error("Invalid record");
2742 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2743 } else // TODO: Remove with llvm 4.0
2744 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2746 return error("Invalid record");
2747 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2750 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2751 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2752 if (Record.size() < 3 || !OpTy)
2753 return error("Invalid record");
2754 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2755 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2756 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2757 OpTy->getNumElements());
2758 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2759 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2762 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2763 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2765 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2766 if (Record.size() < 4 || !RTy || !OpTy)
2767 return error("Invalid record");
2768 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2769 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2770 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2771 RTy->getNumElements());
2772 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2773 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2776 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2777 if (Record.size() < 4)
2778 return error("Invalid record");
2779 Type *OpTy = getTypeByID(Record[0]);
2781 return error("Invalid record");
2782 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2783 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2785 if (OpTy->isFPOrFPVectorTy())
2786 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2788 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2791 // This maintains backward compatibility, pre-asm dialect keywords.
2792 // FIXME: Remove with the 4.0 release.
2793 case bitc::CST_CODE_INLINEASM_OLD: {
2794 if (Record.size() < 2)
2795 return error("Invalid record");
2796 std::string AsmStr, ConstrStr;
2797 bool HasSideEffects = Record[0] & 1;
2798 bool IsAlignStack = Record[0] >> 1;
2799 unsigned AsmStrSize = Record[1];
2800 if (2+AsmStrSize >= Record.size())
2801 return error("Invalid record");
2802 unsigned ConstStrSize = Record[2+AsmStrSize];
2803 if (3+AsmStrSize+ConstStrSize > Record.size())
2804 return error("Invalid record");
2806 for (unsigned i = 0; i != AsmStrSize; ++i)
2807 AsmStr += (char)Record[2+i];
2808 for (unsigned i = 0; i != ConstStrSize; ++i)
2809 ConstrStr += (char)Record[3+AsmStrSize+i];
2810 PointerType *PTy = cast<PointerType>(CurTy);
2811 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2812 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2815 // This version adds support for the asm dialect keywords (e.g.,
2817 case bitc::CST_CODE_INLINEASM: {
2818 if (Record.size() < 2)
2819 return error("Invalid record");
2820 std::string AsmStr, ConstrStr;
2821 bool HasSideEffects = Record[0] & 1;
2822 bool IsAlignStack = (Record[0] >> 1) & 1;
2823 unsigned AsmDialect = Record[0] >> 2;
2824 unsigned AsmStrSize = Record[1];
2825 if (2+AsmStrSize >= Record.size())
2826 return error("Invalid record");
2827 unsigned ConstStrSize = Record[2+AsmStrSize];
2828 if (3+AsmStrSize+ConstStrSize > Record.size())
2829 return error("Invalid record");
2831 for (unsigned i = 0; i != AsmStrSize; ++i)
2832 AsmStr += (char)Record[2+i];
2833 for (unsigned i = 0; i != ConstStrSize; ++i)
2834 ConstrStr += (char)Record[3+AsmStrSize+i];
2835 PointerType *PTy = cast<PointerType>(CurTy);
2836 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2837 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2838 InlineAsm::AsmDialect(AsmDialect));
2841 case bitc::CST_CODE_BLOCKADDRESS:{
2842 if (Record.size() < 3)
2843 return error("Invalid record");
2844 Type *FnTy = getTypeByID(Record[0]);
2846 return error("Invalid record");
2848 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2850 return error("Invalid record");
2852 // Don't let Fn get dematerialized.
2853 BlockAddressesTaken.insert(Fn);
2855 // If the function is already parsed we can insert the block address right
2858 unsigned BBID = Record[2];
2860 // Invalid reference to entry block.
2861 return error("Invalid ID");
2863 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2864 for (size_t I = 0, E = BBID; I != E; ++I) {
2866 return error("Invalid ID");
2871 // Otherwise insert a placeholder and remember it so it can be inserted
2872 // when the function is parsed.
2873 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2875 BasicBlockFwdRefQueue.push_back(Fn);
2876 if (FwdBBs.size() < BBID + 1)
2877 FwdBBs.resize(BBID + 1);
2879 FwdBBs[BBID] = BasicBlock::Create(Context);
2882 V = BlockAddress::get(Fn, BB);
2887 if (ValueList.assignValue(V, NextCstNo))
2888 return error("Invalid forward reference");
2893 std::error_code BitcodeReader::parseUseLists() {
2894 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2895 return error("Invalid record");
2897 // Read all the records.
2898 SmallVector<uint64_t, 64> Record;
2900 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2902 switch (Entry.Kind) {
2903 case BitstreamEntry::SubBlock: // Handled for us already.
2904 case BitstreamEntry::Error:
2905 return error("Malformed block");
2906 case BitstreamEntry::EndBlock:
2907 return std::error_code();
2908 case BitstreamEntry::Record:
2909 // The interesting case.
2913 // Read a use list record.
2916 switch (Stream.readRecord(Entry.ID, Record)) {
2917 default: // Default behavior: unknown type.
2919 case bitc::USELIST_CODE_BB:
2922 case bitc::USELIST_CODE_DEFAULT: {
2923 unsigned RecordLength = Record.size();
2924 if (RecordLength < 3)
2925 // Records should have at least an ID and two indexes.
2926 return error("Invalid record");
2927 unsigned ID = Record.back();
2932 assert(ID < FunctionBBs.size() && "Basic block not found");
2933 V = FunctionBBs[ID];
2936 unsigned NumUses = 0;
2937 SmallDenseMap<const Use *, unsigned, 16> Order;
2938 for (const Use &U : V->uses()) {
2939 if (++NumUses > Record.size())
2941 Order[&U] = Record[NumUses - 1];
2943 if (Order.size() != Record.size() || NumUses > Record.size())
2944 // Mismatches can happen if the functions are being materialized lazily
2945 // (out-of-order), or a value has been upgraded.
2948 V->sortUseList([&](const Use &L, const Use &R) {
2949 return Order.lookup(&L) < Order.lookup(&R);
2957 /// When we see the block for metadata, remember where it is and then skip it.
2958 /// This lets us lazily deserialize the metadata.
2959 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2960 // Save the current stream state.
2961 uint64_t CurBit = Stream.GetCurrentBitNo();
2962 DeferredMetadataInfo.push_back(CurBit);
2964 // Skip over the block for now.
2965 if (Stream.SkipBlock())
2966 return error("Invalid record");
2967 return std::error_code();
2970 std::error_code BitcodeReader::materializeMetadata() {
2971 for (uint64_t BitPos : DeferredMetadataInfo) {
2972 // Move the bit stream to the saved position.
2973 Stream.JumpToBit(BitPos);
2974 if (std::error_code EC = parseMetadata())
2977 DeferredMetadataInfo.clear();
2978 return std::error_code();
2981 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2983 /// When we see the block for a function body, remember where it is and then
2984 /// skip it. This lets us lazily deserialize the functions.
2985 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2986 // Get the function we are talking about.
2987 if (FunctionsWithBodies.empty())
2988 return error("Insufficient function protos");
2990 Function *Fn = FunctionsWithBodies.back();
2991 FunctionsWithBodies.pop_back();
2993 // Save the current stream state.
2994 uint64_t CurBit = Stream.GetCurrentBitNo();
2996 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2997 "Mismatch between VST and scanned function offsets");
2998 DeferredFunctionInfo[Fn] = CurBit;
3000 // Skip over the function block for now.
3001 if (Stream.SkipBlock())
3002 return error("Invalid record");
3003 return std::error_code();
3006 std::error_code BitcodeReader::globalCleanup() {
3007 // Patch the initializers for globals and aliases up.
3008 resolveGlobalAndAliasInits();
3009 if (!GlobalInits.empty() || !AliasInits.empty())
3010 return error("Malformed global initializer set");
3012 // Look for intrinsic functions which need to be upgraded at some point
3013 for (Function &F : *TheModule) {
3015 if (UpgradeIntrinsicFunction(&F, NewFn))
3016 UpgradedIntrinsics[&F] = NewFn;
3019 // Look for global variables which need to be renamed.
3020 for (GlobalVariable &GV : TheModule->globals())
3021 UpgradeGlobalVariable(&GV);
3023 // Force deallocation of memory for these vectors to favor the client that
3024 // want lazy deserialization.
3025 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3026 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3027 return std::error_code();
3030 /// Support for lazy parsing of function bodies. This is required if we
3031 /// either have an old bitcode file without a VST forward declaration record,
3032 /// or if we have an anonymous function being materialized, since anonymous
3033 /// functions do not have a name and are therefore not in the VST.
3034 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3035 Stream.JumpToBit(NextUnreadBit);
3037 if (Stream.AtEndOfStream()) return error("Could not find function in stream");
3039 assert(SeenFirstFunctionBody);
3040 // An old bitcode file with the symbol table at the end would have
3041 // finished the parse greedily.
3042 assert(SeenValueSymbolTable);
3044 SmallVector<uint64_t, 64> Record;
3047 BitstreamEntry Entry = Stream.advance();
3048 switch (Entry.Kind) {
3050 return error("Expect SubBlock");
3051 case BitstreamEntry::SubBlock:
3054 return error("Expect function block");
3055 case bitc::FUNCTION_BLOCK_ID:
3056 if (std::error_code EC = rememberAndSkipFunctionBody()) return EC;
3057 NextUnreadBit = Stream.GetCurrentBitNo();
3058 return std::error_code();
3064 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3065 bool ShouldLazyLoadMetadata) {
3067 Stream.JumpToBit(ResumeBit);
3068 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3069 return error("Invalid record");
3071 SmallVector<uint64_t, 64> Record;
3072 std::vector<std::string> SectionTable;
3073 std::vector<std::string> GCTable;
3075 // Read all the records for this module.
3077 BitstreamEntry Entry = Stream.advance();
3079 switch (Entry.Kind) {
3080 case BitstreamEntry::Error:
3081 return error("Malformed block");
3082 case BitstreamEntry::EndBlock:
3083 return globalCleanup();
3085 case BitstreamEntry::SubBlock:
3087 default: // Skip unknown content.
3088 if (Stream.SkipBlock())
3089 return error("Invalid record");
3091 case bitc::BLOCKINFO_BLOCK_ID:
3092 if (Stream.ReadBlockInfoBlock())
3093 return error("Malformed block");
3095 case bitc::PARAMATTR_BLOCK_ID:
3096 if (std::error_code EC = parseAttributeBlock())
3099 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3100 if (std::error_code EC = parseAttributeGroupBlock())
3103 case bitc::TYPE_BLOCK_ID_NEW:
3104 if (std::error_code EC = parseTypeTable())
3107 case bitc::VALUE_SYMTAB_BLOCK_ID:
3108 if (!SeenValueSymbolTable) {
3109 // Either this is an old form VST without function index and an
3110 // associated VST forward declaration record (which would have caused
3111 // the VST to be jumped to and parsed before it was encountered
3112 // normally in the stream), or there were no function blocks to
3113 // trigger an earlier parsing of the VST.
3114 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3115 if (std::error_code EC = parseValueSymbolTable())
3117 SeenValueSymbolTable = true;
3119 // We must have had a VST forward declaration record, which caused
3120 // the parser to jump to and parse the VST earlier.
3121 assert(VSTOffset > 0);
3122 if (Stream.SkipBlock())
3123 return error("Invalid record");
3126 case bitc::CONSTANTS_BLOCK_ID:
3127 if (std::error_code EC = parseConstants())
3129 if (std::error_code EC = resolveGlobalAndAliasInits())
3132 case bitc::METADATA_BLOCK_ID:
3133 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3134 if (std::error_code EC = rememberAndSkipMetadata())
3138 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3139 if (std::error_code EC = parseMetadata())
3142 case bitc::FUNCTION_BLOCK_ID:
3143 // If this is the first function body we've seen, reverse the
3144 // FunctionsWithBodies list.
3145 if (!SeenFirstFunctionBody) {
3146 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3147 if (std::error_code EC = globalCleanup())
3149 SeenFirstFunctionBody = true;
3152 if (VSTOffset > 0) {
3153 // If we have a VST forward declaration record, make sure we
3154 // parse the VST now if we haven't already. It is needed to
3155 // set up the DeferredFunctionInfo vector for lazy reading.
3156 if (!SeenValueSymbolTable) {
3157 if (std::error_code EC =
3158 BitcodeReader::parseValueSymbolTable(VSTOffset))
3160 SeenValueSymbolTable = true;
3161 // Fall through so that we record the NextUnreadBit below.
3162 // This is necessary in case we have an anonymous function that
3163 // is later materialized. Since it will not have a VST entry we
3164 // need to fall back to the lazy parse to find its offset.
3166 // If we have a VST forward declaration record, but have already
3167 // parsed the VST (just above, when the first function body was
3168 // encountered here), then we are resuming the parse after
3169 // materializing functions. The ResumeBit points to the
3170 // start of the last function block recorded in the
3171 // DeferredFunctionInfo map. Skip it.
3172 if (Stream.SkipBlock())
3173 return error("Invalid record");
3178 // Support older bitcode files that did not have the function
3179 // index in the VST, nor a VST forward declaration record, as
3180 // well as anonymous functions that do not have VST entries.
3181 // Build the DeferredFunctionInfo vector on the fly.
3182 if (std::error_code EC = rememberAndSkipFunctionBody())
3185 // Suspend parsing when we reach the function bodies. Subsequent
3186 // materialization calls will resume it when necessary. If the bitcode
3187 // file is old, the symbol table will be at the end instead and will not
3188 // have been seen yet. In this case, just finish the parse now.
3189 if (SeenValueSymbolTable) {
3190 NextUnreadBit = Stream.GetCurrentBitNo();
3191 return std::error_code();
3194 case bitc::USELIST_BLOCK_ID:
3195 if (std::error_code EC = parseUseLists())
3198 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3199 if (std::error_code EC = parseOperandBundleTags())
3205 case BitstreamEntry::Record:
3206 // The interesting case.
3212 auto BitCode = Stream.readRecord(Entry.ID, Record);
3214 default: break; // Default behavior, ignore unknown content.
3215 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3216 if (Record.size() < 1)
3217 return error("Invalid record");
3218 // Only version #0 and #1 are supported so far.
3219 unsigned module_version = Record[0];
3220 switch (module_version) {
3222 return error("Invalid value");
3224 UseRelativeIDs = false;
3227 UseRelativeIDs = true;
3232 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3234 if (convertToString(Record, 0, S))
3235 return error("Invalid record");
3236 TheModule->setTargetTriple(S);
3239 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3241 if (convertToString(Record, 0, S))
3242 return error("Invalid record");
3243 TheModule->setDataLayout(S);
3246 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3248 if (convertToString(Record, 0, S))
3249 return error("Invalid record");
3250 TheModule->setModuleInlineAsm(S);
3253 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3254 // FIXME: Remove in 4.0.
3256 if (convertToString(Record, 0, S))
3257 return error("Invalid record");
3261 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3263 if (convertToString(Record, 0, S))
3264 return error("Invalid record");
3265 SectionTable.push_back(S);
3268 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3270 if (convertToString(Record, 0, S))
3271 return error("Invalid record");
3272 GCTable.push_back(S);
3275 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3276 if (Record.size() < 2)
3277 return error("Invalid record");
3278 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3279 unsigned ComdatNameSize = Record[1];
3280 std::string ComdatName;
3281 ComdatName.reserve(ComdatNameSize);
3282 for (unsigned i = 0; i != ComdatNameSize; ++i)
3283 ComdatName += (char)Record[2 + i];
3284 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3285 C->setSelectionKind(SK);
3286 ComdatList.push_back(C);
3289 // GLOBALVAR: [pointer type, isconst, initid,
3290 // linkage, alignment, section, visibility, threadlocal,
3291 // unnamed_addr, externally_initialized, dllstorageclass,
3293 case bitc::MODULE_CODE_GLOBALVAR: {
3294 if (Record.size() < 6)
3295 return error("Invalid record");
3296 Type *Ty = getTypeByID(Record[0]);
3298 return error("Invalid record");
3299 bool isConstant = Record[1] & 1;
3300 bool explicitType = Record[1] & 2;
3301 unsigned AddressSpace;
3303 AddressSpace = Record[1] >> 2;
3305 if (!Ty->isPointerTy())
3306 return error("Invalid type for value");
3307 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3308 Ty = cast<PointerType>(Ty)->getElementType();
3311 uint64_t RawLinkage = Record[3];
3312 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3314 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3316 std::string Section;
3318 if (Record[5]-1 >= SectionTable.size())
3319 return error("Invalid ID");
3320 Section = SectionTable[Record[5]-1];
3322 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3323 // Local linkage must have default visibility.
3324 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3325 // FIXME: Change to an error if non-default in 4.0.
3326 Visibility = getDecodedVisibility(Record[6]);
3328 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3329 if (Record.size() > 7)
3330 TLM = getDecodedThreadLocalMode(Record[7]);
3332 bool UnnamedAddr = false;
3333 if (Record.size() > 8)
3334 UnnamedAddr = Record[8];
3336 bool ExternallyInitialized = false;
3337 if (Record.size() > 9)
3338 ExternallyInitialized = Record[9];
3340 GlobalVariable *NewGV =
3341 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3342 TLM, AddressSpace, ExternallyInitialized);
3343 NewGV->setAlignment(Alignment);
3344 if (!Section.empty())
3345 NewGV->setSection(Section);
3346 NewGV->setVisibility(Visibility);
3347 NewGV->setUnnamedAddr(UnnamedAddr);
3349 if (Record.size() > 10)
3350 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3352 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3354 ValueList.push_back(NewGV);
3356 // Remember which value to use for the global initializer.
3357 if (unsigned InitID = Record[2])
3358 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3360 if (Record.size() > 11) {
3361 if (unsigned ComdatID = Record[11]) {
3362 if (ComdatID > ComdatList.size())
3363 return error("Invalid global variable comdat ID");
3364 NewGV->setComdat(ComdatList[ComdatID - 1]);
3366 } else if (hasImplicitComdat(RawLinkage)) {
3367 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3371 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3372 // alignment, section, visibility, gc, unnamed_addr,
3373 // prologuedata, dllstorageclass, comdat, prefixdata]
3374 case bitc::MODULE_CODE_FUNCTION: {
3375 if (Record.size() < 8)
3376 return error("Invalid record");
3377 Type *Ty = getTypeByID(Record[0]);
3379 return error("Invalid record");
3380 if (auto *PTy = dyn_cast<PointerType>(Ty))
3381 Ty = PTy->getElementType();
3382 auto *FTy = dyn_cast<FunctionType>(Ty);
3384 return error("Invalid type for value");
3386 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3389 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
3390 bool isProto = Record[2];
3391 uint64_t RawLinkage = Record[3];
3392 Func->setLinkage(getDecodedLinkage(RawLinkage));
3393 Func->setAttributes(getAttributes(Record[4]));
3396 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3398 Func->setAlignment(Alignment);
3400 if (Record[6]-1 >= SectionTable.size())
3401 return error("Invalid ID");
3402 Func->setSection(SectionTable[Record[6]-1]);
3404 // Local linkage must have default visibility.
3405 if (!Func->hasLocalLinkage())
3406 // FIXME: Change to an error if non-default in 4.0.
3407 Func->setVisibility(getDecodedVisibility(Record[7]));
3408 if (Record.size() > 8 && Record[8]) {
3409 if (Record[8]-1 >= GCTable.size())
3410 return error("Invalid ID");
3411 Func->setGC(GCTable[Record[8]-1].c_str());
3413 bool UnnamedAddr = false;
3414 if (Record.size() > 9)
3415 UnnamedAddr = Record[9];
3416 Func->setUnnamedAddr(UnnamedAddr);
3417 if (Record.size() > 10 && Record[10] != 0)
3418 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3420 if (Record.size() > 11)
3421 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3423 upgradeDLLImportExportLinkage(Func, RawLinkage);
3425 if (Record.size() > 12) {
3426 if (unsigned ComdatID = Record[12]) {
3427 if (ComdatID > ComdatList.size())
3428 return error("Invalid function comdat ID");
3429 Func->setComdat(ComdatList[ComdatID - 1]);
3431 } else if (hasImplicitComdat(RawLinkage)) {
3432 Func->setComdat(reinterpret_cast<Comdat *>(1));
3435 if (Record.size() > 13 && Record[13] != 0)
3436 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3438 if (Record.size() > 14 && Record[14] != 0)
3439 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3441 ValueList.push_back(Func);
3443 // If this is a function with a body, remember the prototype we are
3444 // creating now, so that we can match up the body with them later.
3446 Func->setIsMaterializable(true);
3447 FunctionsWithBodies.push_back(Func);
3448 DeferredFunctionInfo[Func] = 0;
3452 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3453 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3454 case bitc::MODULE_CODE_ALIAS:
3455 case bitc::MODULE_CODE_ALIAS_OLD: {
3456 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3457 if (Record.size() < (3 + (unsigned)NewRecord))
3458 return error("Invalid record");
3460 Type *Ty = getTypeByID(Record[OpNum++]);
3462 return error("Invalid record");
3466 auto *PTy = dyn_cast<PointerType>(Ty);
3468 return error("Invalid type for value");
3469 Ty = PTy->getElementType();
3470 AddrSpace = PTy->getAddressSpace();
3472 AddrSpace = Record[OpNum++];
3475 auto Val = Record[OpNum++];
3476 auto Linkage = Record[OpNum++];
3477 auto *NewGA = GlobalAlias::create(
3478 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3479 // Old bitcode files didn't have visibility field.
3480 // Local linkage must have default visibility.
3481 if (OpNum != Record.size()) {
3482 auto VisInd = OpNum++;
3483 if (!NewGA->hasLocalLinkage())
3484 // FIXME: Change to an error if non-default in 4.0.
3485 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3487 if (OpNum != Record.size())
3488 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3490 upgradeDLLImportExportLinkage(NewGA, Linkage);
3491 if (OpNum != Record.size())
3492 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3493 if (OpNum != Record.size())
3494 NewGA->setUnnamedAddr(Record[OpNum++]);
3495 ValueList.push_back(NewGA);
3496 AliasInits.push_back(std::make_pair(NewGA, Val));
3499 /// MODULE_CODE_PURGEVALS: [numvals]
3500 case bitc::MODULE_CODE_PURGEVALS:
3501 // Trim down the value list to the specified size.
3502 if (Record.size() < 1 || Record[0] > ValueList.size())
3503 return error("Invalid record");
3504 ValueList.shrinkTo(Record[0]);
3506 /// MODULE_CODE_VSTOFFSET: [offset]
3507 case bitc::MODULE_CODE_VSTOFFSET:
3508 if (Record.size() < 1)
3509 return error("Invalid record");
3510 VSTOffset = Record[0];
3517 /// Helper to read the header common to all bitcode files.
3518 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3519 // Sniff for the signature.
3520 if (Stream.Read(8) != 'B' ||
3521 Stream.Read(8) != 'C' ||
3522 Stream.Read(4) != 0x0 ||
3523 Stream.Read(4) != 0xC ||
3524 Stream.Read(4) != 0xE ||
3525 Stream.Read(4) != 0xD)
3531 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3532 Module *M, bool ShouldLazyLoadMetadata) {
3535 if (std::error_code EC = initStream(std::move(Streamer)))
3538 // Sniff for the signature.
3539 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
3541 // We expect a number of well-defined blocks, though we don't necessarily
3542 // need to understand them all.
3544 if (Stream.AtEndOfStream()) {
3545 // We didn't really read a proper Module.
3546 return error("Malformed IR file");
3549 BitstreamEntry Entry =
3550 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3552 if (Entry.Kind != BitstreamEntry::SubBlock)
3553 return error("Malformed block");
3555 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3556 return parseModule(0, ShouldLazyLoadMetadata);
3558 if (Stream.SkipBlock())
3559 return error("Invalid record");
3563 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3564 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3565 return error("Invalid record");
3567 SmallVector<uint64_t, 64> Record;
3570 // Read all the records for this module.
3572 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3574 switch (Entry.Kind) {
3575 case BitstreamEntry::SubBlock: // Handled for us already.
3576 case BitstreamEntry::Error:
3577 return error("Malformed block");
3578 case BitstreamEntry::EndBlock:
3580 case BitstreamEntry::Record:
3581 // The interesting case.
3586 switch (Stream.readRecord(Entry.ID, Record)) {
3587 default: break; // Default behavior, ignore unknown content.
3588 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3590 if (convertToString(Record, 0, S))
3591 return error("Invalid record");
3598 llvm_unreachable("Exit infinite loop");
3601 ErrorOr<std::string> BitcodeReader::parseTriple() {
3602 if (std::error_code EC = initStream(nullptr))
3605 // Sniff for the signature.
3606 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
3608 // We expect a number of well-defined blocks, though we don't necessarily
3609 // need to understand them all.
3611 BitstreamEntry Entry = Stream.advance();
3613 switch (Entry.Kind) {
3614 case BitstreamEntry::Error:
3615 return error("Malformed block");
3616 case BitstreamEntry::EndBlock:
3617 return std::error_code();
3619 case BitstreamEntry::SubBlock:
3620 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3621 return parseModuleTriple();
3623 // Ignore other sub-blocks.
3624 if (Stream.SkipBlock())
3625 return error("Malformed block");
3628 case BitstreamEntry::Record:
3629 Stream.skipRecord(Entry.ID);
3635 /// Parse metadata attachments.
3636 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3637 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3638 return error("Invalid record");
3640 SmallVector<uint64_t, 64> Record;
3642 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3644 switch (Entry.Kind) {
3645 case BitstreamEntry::SubBlock: // Handled for us already.
3646 case BitstreamEntry::Error:
3647 return error("Malformed block");
3648 case BitstreamEntry::EndBlock:
3649 return std::error_code();
3650 case BitstreamEntry::Record:
3651 // The interesting case.
3655 // Read a metadata attachment record.
3657 switch (Stream.readRecord(Entry.ID, Record)) {
3658 default: // Default behavior: ignore.
3660 case bitc::METADATA_ATTACHMENT: {
3661 unsigned RecordLength = Record.size();
3663 return error("Invalid record");
3664 if (RecordLength % 2 == 0) {
3665 // A function attachment.
3666 for (unsigned I = 0; I != RecordLength; I += 2) {
3667 auto K = MDKindMap.find(Record[I]);
3668 if (K == MDKindMap.end())
3669 return error("Invalid ID");
3670 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3671 F.setMetadata(K->second, cast<MDNode>(MD));
3676 // An instruction attachment.
3677 Instruction *Inst = InstructionList[Record[0]];
3678 for (unsigned i = 1; i != RecordLength; i = i+2) {
3679 unsigned Kind = Record[i];
3680 DenseMap<unsigned, unsigned>::iterator I =
3681 MDKindMap.find(Kind);
3682 if (I == MDKindMap.end())
3683 return error("Invalid ID");
3684 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3685 if (isa<LocalAsMetadata>(Node))
3686 // Drop the attachment. This used to be legal, but there's no
3689 Inst->setMetadata(I->second, cast<MDNode>(Node));
3690 if (I->second == LLVMContext::MD_tbaa)
3691 InstsWithTBAATag.push_back(Inst);
3699 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3700 Type *ValType, Type *PtrType) {
3701 if (!isa<PointerType>(PtrType))
3702 return error(DH, "Load/Store operand is not a pointer type");
3703 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3705 if (ValType && ValType != ElemType)
3706 return error(DH, "Explicit load/store type does not match pointee type of "
3708 if (!PointerType::isLoadableOrStorableType(ElemType))
3709 return error(DH, "Cannot load/store from pointer");
3710 return std::error_code();
3713 /// Lazily parse the specified function body block.
3714 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3715 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3716 return error("Invalid record");
3718 InstructionList.clear();
3719 unsigned ModuleValueListSize = ValueList.size();
3720 unsigned ModuleMDValueListSize = MDValueList.size();
3722 // Add all the function arguments to the value table.
3723 for (Argument &I : F->args())
3724 ValueList.push_back(&I);
3726 unsigned NextValueNo = ValueList.size();
3727 BasicBlock *CurBB = nullptr;
3728 unsigned CurBBNo = 0;
3731 auto getLastInstruction = [&]() -> Instruction * {
3732 if (CurBB && !CurBB->empty())
3733 return &CurBB->back();
3734 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3735 !FunctionBBs[CurBBNo - 1]->empty())
3736 return &FunctionBBs[CurBBNo - 1]->back();
3740 std::vector<OperandBundleDef> OperandBundles;
3742 // Read all the records.
3743 SmallVector<uint64_t, 64> Record;
3745 BitstreamEntry Entry = Stream.advance();
3747 switch (Entry.Kind) {
3748 case BitstreamEntry::Error:
3749 return error("Malformed block");
3750 case BitstreamEntry::EndBlock:
3751 goto OutOfRecordLoop;
3753 case BitstreamEntry::SubBlock:
3755 default: // Skip unknown content.
3756 if (Stream.SkipBlock())
3757 return error("Invalid record");
3759 case bitc::CONSTANTS_BLOCK_ID:
3760 if (std::error_code EC = parseConstants())
3762 NextValueNo = ValueList.size();
3764 case bitc::VALUE_SYMTAB_BLOCK_ID:
3765 if (std::error_code EC = parseValueSymbolTable())
3768 case bitc::METADATA_ATTACHMENT_ID:
3769 if (std::error_code EC = parseMetadataAttachment(*F))
3772 case bitc::METADATA_BLOCK_ID:
3773 if (std::error_code EC = parseMetadata())
3776 case bitc::USELIST_BLOCK_ID:
3777 if (std::error_code EC = parseUseLists())
3783 case BitstreamEntry::Record:
3784 // The interesting case.
3790 Instruction *I = nullptr;
3791 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3793 default: // Default behavior: reject
3794 return error("Invalid value");
3795 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3796 if (Record.size() < 1 || Record[0] == 0)
3797 return error("Invalid record");
3798 // Create all the basic blocks for the function.
3799 FunctionBBs.resize(Record[0]);
3801 // See if anything took the address of blocks in this function.
3802 auto BBFRI = BasicBlockFwdRefs.find(F);
3803 if (BBFRI == BasicBlockFwdRefs.end()) {
3804 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3805 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3807 auto &BBRefs = BBFRI->second;
3808 // Check for invalid basic block references.
3809 if (BBRefs.size() > FunctionBBs.size())
3810 return error("Invalid ID");
3811 assert(!BBRefs.empty() && "Unexpected empty array");
3812 assert(!BBRefs.front() && "Invalid reference to entry block");
3813 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3815 if (I < RE && BBRefs[I]) {
3816 BBRefs[I]->insertInto(F);
3817 FunctionBBs[I] = BBRefs[I];
3819 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3822 // Erase from the table.
3823 BasicBlockFwdRefs.erase(BBFRI);
3826 CurBB = FunctionBBs[0];
3830 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3831 // This record indicates that the last instruction is at the same
3832 // location as the previous instruction with a location.
3833 I = getLastInstruction();
3836 return error("Invalid record");
3837 I->setDebugLoc(LastLoc);
3841 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3842 I = getLastInstruction();
3843 if (!I || Record.size() < 4)
3844 return error("Invalid record");
3846 unsigned Line = Record[0], Col = Record[1];
3847 unsigned ScopeID = Record[2], IAID = Record[3];
3849 MDNode *Scope = nullptr, *IA = nullptr;
3850 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3851 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3852 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3853 I->setDebugLoc(LastLoc);
3858 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3861 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3862 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3863 OpNum+1 > Record.size())
3864 return error("Invalid record");
3866 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3868 return error("Invalid record");
3869 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3870 InstructionList.push_back(I);
3871 if (OpNum < Record.size()) {
3872 if (Opc == Instruction::Add ||
3873 Opc == Instruction::Sub ||
3874 Opc == Instruction::Mul ||
3875 Opc == Instruction::Shl) {
3876 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3877 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3878 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3879 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3880 } else if (Opc == Instruction::SDiv ||
3881 Opc == Instruction::UDiv ||
3882 Opc == Instruction::LShr ||
3883 Opc == Instruction::AShr) {
3884 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3885 cast<BinaryOperator>(I)->setIsExact(true);
3886 } else if (isa<FPMathOperator>(I)) {
3887 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3889 I->setFastMathFlags(FMF);
3895 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3898 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3899 OpNum+2 != Record.size())
3900 return error("Invalid record");
3902 Type *ResTy = getTypeByID(Record[OpNum]);
3903 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3904 if (Opc == -1 || !ResTy)
3905 return error("Invalid record");
3906 Instruction *Temp = nullptr;
3907 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3909 InstructionList.push_back(Temp);
3910 CurBB->getInstList().push_back(Temp);
3913 auto CastOp = (Instruction::CastOps)Opc;
3914 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3915 return error("Invalid cast");
3916 I = CastInst::Create(CastOp, Op, ResTy);
3918 InstructionList.push_back(I);
3921 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3922 case bitc::FUNC_CODE_INST_GEP_OLD:
3923 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3929 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3930 InBounds = Record[OpNum++];
3931 Ty = getTypeByID(Record[OpNum++]);
3933 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3938 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3939 return error("Invalid record");
3942 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3945 cast<SequentialType>(BasePtr->getType()->getScalarType())
3948 "Explicit gep type does not match pointee type of pointer operand");
3950 SmallVector<Value*, 16> GEPIdx;
3951 while (OpNum != Record.size()) {
3953 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3954 return error("Invalid record");
3955 GEPIdx.push_back(Op);
3958 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3960 InstructionList.push_back(I);
3962 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3966 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3967 // EXTRACTVAL: [opty, opval, n x indices]
3970 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3971 return error("Invalid record");
3973 unsigned RecSize = Record.size();
3974 if (OpNum == RecSize)
3975 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3977 SmallVector<unsigned, 4> EXTRACTVALIdx;
3978 Type *CurTy = Agg->getType();
3979 for (; OpNum != RecSize; ++OpNum) {
3980 bool IsArray = CurTy->isArrayTy();
3981 bool IsStruct = CurTy->isStructTy();
3982 uint64_t Index = Record[OpNum];
3984 if (!IsStruct && !IsArray)
3985 return error("EXTRACTVAL: Invalid type");
3986 if ((unsigned)Index != Index)
3987 return error("Invalid value");
3988 if (IsStruct && Index >= CurTy->subtypes().size())
3989 return error("EXTRACTVAL: Invalid struct index");
3990 if (IsArray && Index >= CurTy->getArrayNumElements())
3991 return error("EXTRACTVAL: Invalid array index");
3992 EXTRACTVALIdx.push_back((unsigned)Index);
3995 CurTy = CurTy->subtypes()[Index];
3997 CurTy = CurTy->subtypes()[0];
4000 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4001 InstructionList.push_back(I);
4005 case bitc::FUNC_CODE_INST_INSERTVAL: {
4006 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4009 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4010 return error("Invalid record");
4012 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4013 return error("Invalid record");
4015 unsigned RecSize = Record.size();
4016 if (OpNum == RecSize)
4017 return error("INSERTVAL: Invalid instruction with 0 indices");
4019 SmallVector<unsigned, 4> INSERTVALIdx;
4020 Type *CurTy = Agg->getType();
4021 for (; OpNum != RecSize; ++OpNum) {
4022 bool IsArray = CurTy->isArrayTy();
4023 bool IsStruct = CurTy->isStructTy();
4024 uint64_t Index = Record[OpNum];
4026 if (!IsStruct && !IsArray)
4027 return error("INSERTVAL: Invalid type");
4028 if ((unsigned)Index != Index)
4029 return error("Invalid value");
4030 if (IsStruct && Index >= CurTy->subtypes().size())
4031 return error("INSERTVAL: Invalid struct index");
4032 if (IsArray && Index >= CurTy->getArrayNumElements())
4033 return error("INSERTVAL: Invalid array index");
4035 INSERTVALIdx.push_back((unsigned)Index);
4037 CurTy = CurTy->subtypes()[Index];
4039 CurTy = CurTy->subtypes()[0];
4042 if (CurTy != Val->getType())
4043 return error("Inserted value type doesn't match aggregate type");
4045 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4046 InstructionList.push_back(I);
4050 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4051 // obsolete form of select
4052 // handles select i1 ... in old bitcode
4054 Value *TrueVal, *FalseVal, *Cond;
4055 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4056 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4057 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4058 return error("Invalid record");
4060 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4061 InstructionList.push_back(I);
4065 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4066 // new form of select
4067 // handles select i1 or select [N x i1]
4069 Value *TrueVal, *FalseVal, *Cond;
4070 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4071 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4072 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4073 return error("Invalid record");
4075 // select condition can be either i1 or [N x i1]
4076 if (VectorType* vector_type =
4077 dyn_cast<VectorType>(Cond->getType())) {
4079 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4080 return error("Invalid type for value");
4083 if (Cond->getType() != Type::getInt1Ty(Context))
4084 return error("Invalid type for value");
4087 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4088 InstructionList.push_back(I);
4092 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4095 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4096 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4097 return error("Invalid record");
4098 if (!Vec->getType()->isVectorTy())
4099 return error("Invalid type for value");
4100 I = ExtractElementInst::Create(Vec, Idx);
4101 InstructionList.push_back(I);
4105 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4107 Value *Vec, *Elt, *Idx;
4108 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4109 return error("Invalid record");
4110 if (!Vec->getType()->isVectorTy())
4111 return error("Invalid type for value");
4112 if (popValue(Record, OpNum, NextValueNo,
4113 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4114 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4115 return error("Invalid record");
4116 I = InsertElementInst::Create(Vec, Elt, Idx);
4117 InstructionList.push_back(I);
4121 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4123 Value *Vec1, *Vec2, *Mask;
4124 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4125 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4126 return error("Invalid record");
4128 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4129 return error("Invalid record");
4130 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4131 return error("Invalid type for value");
4132 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4133 InstructionList.push_back(I);
4137 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4138 // Old form of ICmp/FCmp returning bool
4139 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4140 // both legal on vectors but had different behaviour.
4141 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4142 // FCmp/ICmp returning bool or vector of bool
4146 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4147 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4148 return error("Invalid record");
4150 unsigned PredVal = Record[OpNum];
4151 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4153 if (IsFP && Record.size() > OpNum+1)
4154 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4156 if (OpNum+1 != Record.size())
4157 return error("Invalid record");
4159 if (LHS->getType()->isFPOrFPVectorTy())
4160 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4162 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4165 I->setFastMathFlags(FMF);
4166 InstructionList.push_back(I);
4170 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4172 unsigned Size = Record.size();
4174 I = ReturnInst::Create(Context);
4175 InstructionList.push_back(I);
4180 Value *Op = nullptr;
4181 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4182 return error("Invalid record");
4183 if (OpNum != Record.size())
4184 return error("Invalid record");
4186 I = ReturnInst::Create(Context, Op);
4187 InstructionList.push_back(I);
4190 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4191 if (Record.size() != 1 && Record.size() != 3)
4192 return error("Invalid record");
4193 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4195 return error("Invalid record");
4197 if (Record.size() == 1) {
4198 I = BranchInst::Create(TrueDest);
4199 InstructionList.push_back(I);
4202 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4203 Value *Cond = getValue(Record, 2, NextValueNo,
4204 Type::getInt1Ty(Context));
4205 if (!FalseDest || !Cond)
4206 return error("Invalid record");
4207 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4208 InstructionList.push_back(I);
4212 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4213 if (Record.size() != 1 && Record.size() != 2)
4214 return error("Invalid record");
4216 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4217 Type::getTokenTy(Context), OC_CleanupPad);
4219 return error("Invalid record");
4220 BasicBlock *UnwindDest = nullptr;
4221 if (Record.size() == 2) {
4222 UnwindDest = getBasicBlock(Record[Idx++]);
4224 return error("Invalid record");
4227 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4229 InstructionList.push_back(I);
4232 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4233 if (Record.size() != 2)
4234 return error("Invalid record");
4236 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4237 Type::getTokenTy(Context), OC_CatchPad);
4239 return error("Invalid record");
4240 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4242 return error("Invalid record");
4244 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4245 InstructionList.push_back(I);
4248 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4249 if (Record.size() < 3)
4250 return error("Invalid record");
4252 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4254 return error("Invalid record");
4255 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4257 return error("Invalid record");
4258 unsigned NumArgOperands = Record[Idx++];
4259 SmallVector<Value *, 2> Args;
4260 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4262 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4263 return error("Invalid record");
4264 Args.push_back(Val);
4266 if (Record.size() != Idx)
4267 return error("Invalid record");
4269 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4270 InstructionList.push_back(I);
4273 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4274 if (Record.size() < 1)
4275 return error("Invalid record");
4277 bool HasUnwindDest = !!Record[Idx++];
4278 BasicBlock *UnwindDest = nullptr;
4279 if (HasUnwindDest) {
4280 if (Idx == Record.size())
4281 return error("Invalid record");
4282 UnwindDest = getBasicBlock(Record[Idx++]);
4284 return error("Invalid record");
4286 unsigned NumArgOperands = Record[Idx++];
4287 SmallVector<Value *, 2> Args;
4288 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4290 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4291 return error("Invalid record");
4292 Args.push_back(Val);
4294 if (Record.size() != Idx)
4295 return error("Invalid record");
4297 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4298 InstructionList.push_back(I);
4301 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4302 if (Record.size() < 1)
4303 return error("Invalid record");
4305 unsigned NumArgOperands = Record[Idx++];
4306 SmallVector<Value *, 2> Args;
4307 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4309 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4310 return error("Invalid record");
4311 Args.push_back(Val);
4313 if (Record.size() != Idx)
4314 return error("Invalid record");
4316 I = CleanupPadInst::Create(Context, Args);
4317 InstructionList.push_back(I);
4320 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4321 if (Record.size() > 1)
4322 return error("Invalid record");
4323 BasicBlock *BB = nullptr;
4324 if (Record.size() == 1) {
4325 BB = getBasicBlock(Record[0]);
4327 return error("Invalid record");
4329 I = CatchEndPadInst::Create(Context, BB);
4330 InstructionList.push_back(I);
4333 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4334 if (Record.size() != 1 && Record.size() != 2)
4335 return error("Invalid record");
4337 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4338 Type::getTokenTy(Context), OC_CleanupPad);
4340 return error("Invalid record");
4342 BasicBlock *BB = nullptr;
4343 if (Record.size() == 2) {
4344 BB = getBasicBlock(Record[Idx++]);
4346 return error("Invalid record");
4348 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4349 InstructionList.push_back(I);
4352 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4354 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4355 // "New" SwitchInst format with case ranges. The changes to write this
4356 // format were reverted but we still recognize bitcode that uses it.
4357 // Hopefully someday we will have support for case ranges and can use
4358 // this format again.
4360 Type *OpTy = getTypeByID(Record[1]);
4361 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4363 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4364 BasicBlock *Default = getBasicBlock(Record[3]);
4365 if (!OpTy || !Cond || !Default)
4366 return error("Invalid record");
4368 unsigned NumCases = Record[4];
4370 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4371 InstructionList.push_back(SI);
4373 unsigned CurIdx = 5;
4374 for (unsigned i = 0; i != NumCases; ++i) {
4375 SmallVector<ConstantInt*, 1> CaseVals;
4376 unsigned NumItems = Record[CurIdx++];
4377 for (unsigned ci = 0; ci != NumItems; ++ci) {
4378 bool isSingleNumber = Record[CurIdx++];
4381 unsigned ActiveWords = 1;
4382 if (ValueBitWidth > 64)
4383 ActiveWords = Record[CurIdx++];
4384 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4386 CurIdx += ActiveWords;
4388 if (!isSingleNumber) {
4390 if (ValueBitWidth > 64)
4391 ActiveWords = Record[CurIdx++];
4392 APInt High = readWideAPInt(
4393 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4394 CurIdx += ActiveWords;
4396 // FIXME: It is not clear whether values in the range should be
4397 // compared as signed or unsigned values. The partially
4398 // implemented changes that used this format in the past used
4399 // unsigned comparisons.
4400 for ( ; Low.ule(High); ++Low)
4401 CaseVals.push_back(ConstantInt::get(Context, Low));
4403 CaseVals.push_back(ConstantInt::get(Context, Low));
4405 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4406 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4407 cve = CaseVals.end(); cvi != cve; ++cvi)
4408 SI->addCase(*cvi, DestBB);
4414 // Old SwitchInst format without case ranges.
4416 if (Record.size() < 3 || (Record.size() & 1) == 0)
4417 return error("Invalid record");
4418 Type *OpTy = getTypeByID(Record[0]);
4419 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4420 BasicBlock *Default = getBasicBlock(Record[2]);
4421 if (!OpTy || !Cond || !Default)
4422 return error("Invalid record");
4423 unsigned NumCases = (Record.size()-3)/2;
4424 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4425 InstructionList.push_back(SI);
4426 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4427 ConstantInt *CaseVal =
4428 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4429 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4430 if (!CaseVal || !DestBB) {
4432 return error("Invalid record");
4434 SI->addCase(CaseVal, DestBB);
4439 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4440 if (Record.size() < 2)
4441 return error("Invalid record");
4442 Type *OpTy = getTypeByID(Record[0]);
4443 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4444 if (!OpTy || !Address)
4445 return error("Invalid record");
4446 unsigned NumDests = Record.size()-2;
4447 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4448 InstructionList.push_back(IBI);
4449 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4450 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4451 IBI->addDestination(DestBB);
4454 return error("Invalid record");
4461 case bitc::FUNC_CODE_INST_INVOKE: {
4462 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4463 if (Record.size() < 4)
4464 return error("Invalid record");
4466 AttributeSet PAL = getAttributes(Record[OpNum++]);
4467 unsigned CCInfo = Record[OpNum++];
4468 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4469 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4471 FunctionType *FTy = nullptr;
4472 if (CCInfo >> 13 & 1 &&
4473 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4474 return error("Explicit invoke type is not a function type");
4477 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4478 return error("Invalid record");
4480 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4482 return error("Callee is not a pointer");
4484 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4486 return error("Callee is not of pointer to function type");
4487 } else if (CalleeTy->getElementType() != FTy)
4488 return error("Explicit invoke type does not match pointee type of "
4490 if (Record.size() < FTy->getNumParams() + OpNum)
4491 return error("Insufficient operands to call");
4493 SmallVector<Value*, 16> Ops;
4494 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4495 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4496 FTy->getParamType(i)));
4498 return error("Invalid record");
4501 if (!FTy->isVarArg()) {
4502 if (Record.size() != OpNum)
4503 return error("Invalid record");
4505 // Read type/value pairs for varargs params.
4506 while (OpNum != Record.size()) {
4508 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4509 return error("Invalid record");
4514 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4515 OperandBundles.clear();
4516 InstructionList.push_back(I);
4518 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
4519 cast<InvokeInst>(I)->setAttributes(PAL);
4522 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4524 Value *Val = nullptr;
4525 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4526 return error("Invalid record");
4527 I = ResumeInst::Create(Val);
4528 InstructionList.push_back(I);
4531 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4532 I = new UnreachableInst(Context);
4533 InstructionList.push_back(I);
4535 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4536 if (Record.size() < 1 || ((Record.size()-1)&1))
4537 return error("Invalid record");
4538 Type *Ty = getTypeByID(Record[0]);
4540 return error("Invalid record");
4542 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4543 InstructionList.push_back(PN);
4545 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4547 // With the new function encoding, it is possible that operands have
4548 // negative IDs (for forward references). Use a signed VBR
4549 // representation to keep the encoding small.
4551 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4553 V = getValue(Record, 1+i, NextValueNo, Ty);
4554 BasicBlock *BB = getBasicBlock(Record[2+i]);
4556 return error("Invalid record");
4557 PN->addIncoming(V, BB);
4563 case bitc::FUNC_CODE_INST_LANDINGPAD:
4564 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4565 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4567 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4568 if (Record.size() < 3)
4569 return error("Invalid record");
4571 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4572 if (Record.size() < 4)
4573 return error("Invalid record");
4575 Type *Ty = getTypeByID(Record[Idx++]);
4577 return error("Invalid record");
4578 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4579 Value *PersFn = nullptr;
4580 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4581 return error("Invalid record");
4583 if (!F->hasPersonalityFn())
4584 F->setPersonalityFn(cast<Constant>(PersFn));
4585 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4586 return error("Personality function mismatch");
4589 bool IsCleanup = !!Record[Idx++];
4590 unsigned NumClauses = Record[Idx++];
4591 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4592 LP->setCleanup(IsCleanup);
4593 for (unsigned J = 0; J != NumClauses; ++J) {
4594 LandingPadInst::ClauseType CT =
4595 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4598 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4600 return error("Invalid record");
4603 assert((CT != LandingPadInst::Catch ||
4604 !isa<ArrayType>(Val->getType())) &&
4605 "Catch clause has a invalid type!");
4606 assert((CT != LandingPadInst::Filter ||
4607 isa<ArrayType>(Val->getType())) &&
4608 "Filter clause has invalid type!");
4609 LP->addClause(cast<Constant>(Val));
4613 InstructionList.push_back(I);
4617 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4618 if (Record.size() != 4)
4619 return error("Invalid record");
4620 uint64_t AlignRecord = Record[3];
4621 const uint64_t InAllocaMask = uint64_t(1) << 5;
4622 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4623 // Reserve bit 7 for SwiftError flag.
4624 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4625 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4626 bool InAlloca = AlignRecord & InAllocaMask;
4627 Type *Ty = getTypeByID(Record[0]);
4628 if ((AlignRecord & ExplicitTypeMask) == 0) {
4629 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4631 return error("Old-style alloca with a non-pointer type");
4632 Ty = PTy->getElementType();
4634 Type *OpTy = getTypeByID(Record[1]);
4635 Value *Size = getFnValueByID(Record[2], OpTy);
4637 if (std::error_code EC =
4638 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4642 return error("Invalid record");
4643 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4644 AI->setUsedWithInAlloca(InAlloca);
4646 InstructionList.push_back(I);
4649 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4652 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4653 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4654 return error("Invalid record");
4657 if (OpNum + 3 == Record.size())
4658 Ty = getTypeByID(Record[OpNum++]);
4659 if (std::error_code EC =
4660 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4663 Ty = cast<PointerType>(Op->getType())->getElementType();
4666 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4668 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4670 InstructionList.push_back(I);
4673 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4674 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4677 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4678 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4679 return error("Invalid record");
4682 if (OpNum + 5 == Record.size())
4683 Ty = getTypeByID(Record[OpNum++]);
4684 if (std::error_code EC =
4685 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4688 Ty = cast<PointerType>(Op->getType())->getElementType();
4690 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4691 if (Ordering == NotAtomic || Ordering == Release ||
4692 Ordering == AcquireRelease)
4693 return error("Invalid record");
4694 if (Ordering != NotAtomic && Record[OpNum] == 0)
4695 return error("Invalid record");
4696 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4699 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4701 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4703 InstructionList.push_back(I);
4706 case bitc::FUNC_CODE_INST_STORE:
4707 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4710 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4711 (BitCode == bitc::FUNC_CODE_INST_STORE
4712 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4713 : popValue(Record, OpNum, NextValueNo,
4714 cast<PointerType>(Ptr->getType())->getElementType(),
4716 OpNum + 2 != Record.size())
4717 return error("Invalid record");
4719 if (std::error_code EC = typeCheckLoadStoreInst(
4720 DiagnosticHandler, Val->getType(), Ptr->getType()))
4723 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4725 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4726 InstructionList.push_back(I);
4729 case bitc::FUNC_CODE_INST_STOREATOMIC:
4730 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4731 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4734 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4735 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4736 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4737 : popValue(Record, OpNum, NextValueNo,
4738 cast<PointerType>(Ptr->getType())->getElementType(),
4740 OpNum + 4 != Record.size())
4741 return error("Invalid record");
4743 if (std::error_code EC = typeCheckLoadStoreInst(
4744 DiagnosticHandler, Val->getType(), Ptr->getType()))
4746 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4747 if (Ordering == NotAtomic || Ordering == Acquire ||
4748 Ordering == AcquireRelease)
4749 return error("Invalid record");
4750 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4751 if (Ordering != NotAtomic && Record[OpNum] == 0)
4752 return error("Invalid record");
4755 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4757 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4758 InstructionList.push_back(I);
4761 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4762 case bitc::FUNC_CODE_INST_CMPXCHG: {
4763 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4764 // failureordering?, isweak?]
4766 Value *Ptr, *Cmp, *New;
4767 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4768 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4769 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4770 : popValue(Record, OpNum, NextValueNo,
4771 cast<PointerType>(Ptr->getType())->getElementType(),
4773 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4774 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4775 return error("Invalid record");
4776 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4777 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4778 return error("Invalid record");
4779 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4781 if (std::error_code EC = typeCheckLoadStoreInst(
4782 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4784 AtomicOrdering FailureOrdering;
4785 if (Record.size() < 7)
4787 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4789 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4791 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4793 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4795 if (Record.size() < 8) {
4796 // Before weak cmpxchgs existed, the instruction simply returned the
4797 // value loaded from memory, so bitcode files from that era will be
4798 // expecting the first component of a modern cmpxchg.
4799 CurBB->getInstList().push_back(I);
4800 I = ExtractValueInst::Create(I, 0);
4802 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4805 InstructionList.push_back(I);
4808 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4809 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4812 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4813 popValue(Record, OpNum, NextValueNo,
4814 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4815 OpNum+4 != Record.size())
4816 return error("Invalid record");
4817 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4818 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4819 Operation > AtomicRMWInst::LAST_BINOP)
4820 return error("Invalid record");
4821 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4822 if (Ordering == NotAtomic || Ordering == Unordered)
4823 return error("Invalid record");
4824 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4825 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4826 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4827 InstructionList.push_back(I);
4830 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4831 if (2 != Record.size())
4832 return error("Invalid record");
4833 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4834 if (Ordering == NotAtomic || Ordering == Unordered ||
4835 Ordering == Monotonic)
4836 return error("Invalid record");
4837 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4838 I = new FenceInst(Context, Ordering, SynchScope);
4839 InstructionList.push_back(I);
4842 case bitc::FUNC_CODE_INST_CALL: {
4843 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4844 if (Record.size() < 3)
4845 return error("Invalid record");
4848 AttributeSet PAL = getAttributes(Record[OpNum++]);
4849 unsigned CCInfo = Record[OpNum++];
4851 FunctionType *FTy = nullptr;
4852 if (CCInfo >> 15 & 1 &&
4853 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4854 return error("Explicit call type is not a function type");
4857 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4858 return error("Invalid record");
4860 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4862 return error("Callee is not a pointer type");
4864 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4866 return error("Callee is not of pointer to function type");
4867 } else if (OpTy->getElementType() != FTy)
4868 return error("Explicit call type does not match pointee type of "
4870 if (Record.size() < FTy->getNumParams() + OpNum)
4871 return error("Insufficient operands to call");
4873 SmallVector<Value*, 16> Args;
4874 // Read the fixed params.
4875 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4876 if (FTy->getParamType(i)->isLabelTy())
4877 Args.push_back(getBasicBlock(Record[OpNum]));
4879 Args.push_back(getValue(Record, OpNum, NextValueNo,
4880 FTy->getParamType(i)));
4882 return error("Invalid record");
4885 // Read type/value pairs for varargs params.
4886 if (!FTy->isVarArg()) {
4887 if (OpNum != Record.size())
4888 return error("Invalid record");
4890 while (OpNum != Record.size()) {
4892 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4893 return error("Invalid record");
4898 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4899 OperandBundles.clear();
4900 InstructionList.push_back(I);
4901 cast<CallInst>(I)->setCallingConv(
4902 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4903 CallInst::TailCallKind TCK = CallInst::TCK_None;
4905 TCK = CallInst::TCK_Tail;
4906 if (CCInfo & (1 << 14))
4907 TCK = CallInst::TCK_MustTail;
4908 cast<CallInst>(I)->setTailCallKind(TCK);
4909 cast<CallInst>(I)->setAttributes(PAL);
4912 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4913 if (Record.size() < 3)
4914 return error("Invalid record");
4915 Type *OpTy = getTypeByID(Record[0]);
4916 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4917 Type *ResTy = getTypeByID(Record[2]);
4918 if (!OpTy || !Op || !ResTy)
4919 return error("Invalid record");
4920 I = new VAArgInst(Op, ResTy);
4921 InstructionList.push_back(I);
4925 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4926 // A call or an invoke can be optionally prefixed with some variable
4927 // number of operand bundle blocks. These blocks are read into
4928 // OperandBundles and consumed at the next call or invoke instruction.
4930 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4931 return error("Invalid record");
4933 OperandBundles.emplace_back();
4934 OperandBundles.back().Tag = BundleTags[Record[0]];
4936 std::vector<Value *> &Inputs = OperandBundles.back().Inputs;
4939 while (OpNum != Record.size()) {
4941 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4942 return error("Invalid record");
4943 Inputs.push_back(Op);
4950 // Add instruction to end of current BB. If there is no current BB, reject
4954 return error("Invalid instruction with no BB");
4956 if (!OperandBundles.empty()) {
4958 return error("Operand bundles found with no consumer");
4960 CurBB->getInstList().push_back(I);
4962 // If this was a terminator instruction, move to the next block.
4963 if (isa<TerminatorInst>(I)) {
4965 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4968 // Non-void values get registered in the value table for future use.
4969 if (I && !I->getType()->isVoidTy())
4970 if (ValueList.assignValue(I, NextValueNo++))
4971 return error("Invalid forward reference");
4976 if (!OperandBundles.empty())
4977 return error("Operand bundles found with no consumer");
4979 // Check the function list for unresolved values.
4980 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4981 if (!A->getParent()) {
4982 // We found at least one unresolved value. Nuke them all to avoid leaks.
4983 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4984 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4985 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4989 return error("Never resolved value found in function");
4993 // FIXME: Check for unresolved forward-declared metadata references
4994 // and clean up leaks.
4996 // Trim the value list down to the size it was before we parsed this function.
4997 ValueList.shrinkTo(ModuleValueListSize);
4998 MDValueList.shrinkTo(ModuleMDValueListSize);
4999 std::vector<BasicBlock*>().swap(FunctionBBs);
5000 return std::error_code();
5003 /// Find the function body in the bitcode stream
5004 std::error_code BitcodeReader::findFunctionInStream(
5006 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5007 while (DeferredFunctionInfoIterator->second == 0) {
5008 // This is the fallback handling for the old format bitcode that
5009 // didn't contain the function index in the VST, or when we have
5010 // an anonymous function which would not have a VST entry.
5011 // Assert that we have one of those two cases.
5012 assert(VSTOffset == 0 || !F->hasName());
5013 // Parse the next body in the stream and set its position in the
5014 // DeferredFunctionInfo map.
5015 if (std::error_code EC = rememberAndSkipFunctionBodies()) return EC;
5017 return std::error_code();
5020 //===----------------------------------------------------------------------===//
5021 // GVMaterializer implementation
5022 //===----------------------------------------------------------------------===//
5024 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5026 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5027 if (std::error_code EC = materializeMetadata())
5030 Function *F = dyn_cast<Function>(GV);
5031 // If it's not a function or is already material, ignore the request.
5032 if (!F || !F->isMaterializable())
5033 return std::error_code();
5035 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5036 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5037 // If its position is recorded as 0, its body is somewhere in the stream
5038 // but we haven't seen it yet.
5039 if (DFII->second == 0)
5040 if (std::error_code EC = findFunctionInStream(F, DFII))
5043 // Move the bit stream to the saved position of the deferred function body.
5044 Stream.JumpToBit(DFII->second);
5046 if (std::error_code EC = parseFunctionBody(F))
5048 F->setIsMaterializable(false);
5053 // Upgrade any old intrinsic calls in the function.
5054 for (auto &I : UpgradedIntrinsics) {
5055 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5058 if (CallInst *CI = dyn_cast<CallInst>(U))
5059 UpgradeIntrinsicCall(CI, I.second);
5063 // Bring in any functions that this function forward-referenced via
5065 return materializeForwardReferencedFunctions();
5068 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5069 const Function *F = dyn_cast<Function>(GV);
5070 if (!F || F->isDeclaration())
5073 // Dematerializing F would leave dangling references that wouldn't be
5074 // reconnected on re-materialization.
5075 if (BlockAddressesTaken.count(F))
5078 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5081 void BitcodeReader::dematerialize(GlobalValue *GV) {
5082 Function *F = dyn_cast<Function>(GV);
5083 // If this function isn't dematerializable, this is a noop.
5084 if (!F || !isDematerializable(F))
5087 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5089 // Just forget the function body, we can remat it later.
5090 F->dropAllReferences();
5091 F->setIsMaterializable(true);
5094 std::error_code BitcodeReader::materializeModule(Module *M) {
5095 assert(M == TheModule &&
5096 "Can only Materialize the Module this BitcodeReader is attached to.");
5098 if (std::error_code EC = materializeMetadata())
5101 // Promise to materialize all forward references.
5102 WillMaterializeAllForwardRefs = true;
5104 // Iterate over the module, deserializing any functions that are still on
5106 for (Function &F : *TheModule) {
5107 if (std::error_code EC = materialize(&F))
5110 // At this point, if there are any function bodies, parse the rest of
5111 // the bits in the module past the last function block we have recorded
5112 // through either lazy scanning or the VST.
5113 if (LastFunctionBlockBit || NextUnreadBit)
5114 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5117 // Check that all block address forward references got resolved (as we
5119 if (!BasicBlockFwdRefs.empty())
5120 return error("Never resolved function from blockaddress");
5122 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5123 // delete the old functions to clean up. We can't do this unless the entire
5124 // module is materialized because there could always be another function body
5125 // with calls to the old function.
5126 for (auto &I : UpgradedIntrinsics) {
5127 for (auto *U : I.first->users()) {
5128 if (CallInst *CI = dyn_cast<CallInst>(U))
5129 UpgradeIntrinsicCall(CI, I.second);
5131 if (!I.first->use_empty())
5132 I.first->replaceAllUsesWith(I.second);
5133 I.first->eraseFromParent();
5135 UpgradedIntrinsics.clear();
5137 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5138 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5140 UpgradeDebugInfo(*M);
5141 return std::error_code();
5144 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5145 return IdentifiedStructTypes;
5149 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5151 return initLazyStream(std::move(Streamer));
5152 return initStreamFromBuffer();
5155 std::error_code BitcodeReader::initStreamFromBuffer() {
5156 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5157 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5159 if (Buffer->getBufferSize() & 3)
5160 return error("Invalid bitcode signature");
5162 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5163 // The magic number is 0x0B17C0DE stored in little endian.
5164 if (isBitcodeWrapper(BufPtr, BufEnd))
5165 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5166 return error("Invalid bitcode wrapper header");
5168 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5169 Stream.init(&*StreamFile);
5171 return std::error_code();
5175 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5176 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5179 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5180 StreamingMemoryObject &Bytes = *OwnedBytes;
5181 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5182 Stream.init(&*StreamFile);
5184 unsigned char buf[16];
5185 if (Bytes.readBytes(buf, 16, 0) != 16)
5186 return error("Invalid bitcode signature");
5188 if (!isBitcode(buf, buf + 16))
5189 return error("Invalid bitcode signature");
5191 if (isBitcodeWrapper(buf, buf + 4)) {
5192 const unsigned char *bitcodeStart = buf;
5193 const unsigned char *bitcodeEnd = buf + 16;
5194 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5195 Bytes.dropLeadingBytes(bitcodeStart - buf);
5196 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5198 return std::error_code();
5201 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5202 const Twine &Message) {
5203 return ::error(DiagnosticHandler, make_error_code(E), Message);
5206 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5207 return ::error(DiagnosticHandler,
5208 make_error_code(BitcodeError::CorruptedBitcode), Message);
5211 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5212 return ::error(DiagnosticHandler, make_error_code(E));
5215 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5216 MemoryBuffer *Buffer, LLVMContext &Context,
5217 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5218 bool CheckFuncSummaryPresenceOnly)
5219 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5222 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5224 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5225 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler,
5226 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5227 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5230 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5232 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5234 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5236 // Specialized value symbol table parser used when reading function index
5237 // blocks where we don't actually create global values.
5238 // At the end of this routine the function index is populated with a map
5239 // from function name to FunctionInfo. The function info contains
5240 // the function block's bitcode offset as well as the offset into the
5241 // function summary section.
5242 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5243 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5244 return error("Invalid record");
5246 SmallVector<uint64_t, 64> Record;
5248 // Read all the records for this value table.
5249 SmallString<128> ValueName;
5251 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5253 switch (Entry.Kind) {
5254 case BitstreamEntry::SubBlock: // Handled for us already.
5255 case BitstreamEntry::Error:
5256 return error("Malformed block");
5257 case BitstreamEntry::EndBlock:
5258 return std::error_code();
5259 case BitstreamEntry::Record:
5260 // The interesting case.
5266 switch (Stream.readRecord(Entry.ID, Record)) {
5267 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5269 case bitc::VST_CODE_FNENTRY: {
5270 // VST_FNENTRY: [valueid, offset, namechar x N]
5271 if (convertToString(Record, 2, ValueName))
5272 return error("Invalid record");
5273 unsigned ValueID = Record[0];
5274 uint64_t FuncOffset = Record[1];
5275 std::unique_ptr<FunctionInfo> FuncInfo =
5276 llvm::make_unique<FunctionInfo>(FuncOffset);
5277 if (foundFuncSummary() && !IsLazy) {
5278 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5279 SummaryMap.find(ValueID);
5280 assert(SMI != SummaryMap.end() && "Summary info not found");
5281 FuncInfo->setFunctionSummary(std::move(SMI->second));
5283 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5288 case bitc::VST_CODE_COMBINED_FNENTRY: {
5289 // VST_FNENTRY: [offset, namechar x N]
5290 if (convertToString(Record, 1, ValueName))
5291 return error("Invalid record");
5292 uint64_t FuncSummaryOffset = Record[0];
5293 std::unique_ptr<FunctionInfo> FuncInfo =
5294 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5295 if (foundFuncSummary() && !IsLazy) {
5296 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5297 SummaryMap.find(FuncSummaryOffset);
5298 assert(SMI != SummaryMap.end() && "Summary info not found");
5299 FuncInfo->setFunctionSummary(std::move(SMI->second));
5301 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5310 // Parse just the blocks needed for function index building out of the module.
5311 // At the end of this routine the function Index is populated with a map
5312 // from function name to FunctionInfo. The function info contains
5313 // either the parsed function summary information (when parsing summaries
5314 // eagerly), or just to the function summary record's offset
5315 // if parsing lazily (IsLazy).
5316 std::error_code FunctionIndexBitcodeReader::parseModule() {
5317 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5318 return error("Invalid record");
5320 // Read the function index for this module.
5322 BitstreamEntry Entry = Stream.advance();
5324 switch (Entry.Kind) {
5325 case BitstreamEntry::Error:
5326 return error("Malformed block");
5327 case BitstreamEntry::EndBlock:
5328 return std::error_code();
5330 case BitstreamEntry::SubBlock:
5331 if (CheckFuncSummaryPresenceOnly) {
5332 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5333 SeenFuncSummary = true;
5334 if (Stream.SkipBlock()) return error("Invalid record");
5335 // No need to parse the rest since we found the summary.
5336 return std::error_code();
5339 default: // Skip unknown content.
5340 if (Stream.SkipBlock()) return error("Invalid record");
5342 case bitc::BLOCKINFO_BLOCK_ID:
5343 // Need to parse these to get abbrev ids (e.g. for VST)
5344 if (Stream.ReadBlockInfoBlock()) return error("Malformed block");
5346 case bitc::VALUE_SYMTAB_BLOCK_ID:
5347 if (std::error_code EC = parseValueSymbolTable()) return EC;
5349 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5350 SeenFuncSummary = true;
5352 // Lazy parsing of summary info, skip it.
5353 if (Stream.SkipBlock()) return error("Invalid record");
5354 } else if (std::error_code EC = parseEntireSummary())
5357 case bitc::MODULE_STRTAB_BLOCK_ID:
5358 if (std::error_code EC = parseModuleStringTable()) return EC;
5363 case BitstreamEntry::Record:
5364 Stream.skipRecord(Entry.ID);
5370 // Eagerly parse the entire function summary block (i.e. for all functions
5371 // in the index). This populates the FunctionSummary objects in
5373 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5374 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5375 return error("Invalid record");
5377 SmallVector<uint64_t, 64> Record;
5380 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5382 switch (Entry.Kind) {
5383 case BitstreamEntry::SubBlock: // Handled for us already.
5384 case BitstreamEntry::Error:
5385 return error("Malformed block");
5386 case BitstreamEntry::EndBlock:
5387 return std::error_code();
5388 case BitstreamEntry::Record:
5389 // The interesting case.
5393 // Read a record. The record format depends on whether this
5394 // is a per-module index or a combined index file. In the per-module
5395 // case the records contain the associated value's ID for correlation
5396 // with VST entries. In the combined index the correlation is done
5397 // via the bitcode offset of the summary records (which were saved
5398 // in the combined index VST entries). The records also contain
5399 // information used for ThinLTO renaming and importing.
5401 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5402 switch (Stream.readRecord(Entry.ID, Record)) {
5403 default: // Default behavior: ignore.
5405 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5406 case bitc::FS_CODE_PERMODULE_ENTRY: {
5407 unsigned ValueID = Record[0];
5408 bool IsLocal = Record[1];
5409 unsigned InstCount = Record[2];
5410 std::unique_ptr<FunctionSummary> FS =
5411 llvm::make_unique<FunctionSummary>(InstCount);
5412 FS->setLocalFunction(IsLocal);
5413 // The module path string ref set in the summary must be owned by the
5414 // index's module string table. Since we don't have a module path
5415 // string table section in the per-module index, we create a single
5416 // module path string table entry with an empty (0) ID to take
5419 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5420 SummaryMap[ValueID] = std::move(FS);
5422 // FS_COMBINED_ENTRY: [modid, instcount]
5423 case bitc::FS_CODE_COMBINED_ENTRY: {
5424 uint64_t ModuleId = Record[0];
5425 unsigned InstCount = Record[1];
5426 std::unique_ptr<FunctionSummary> FS =
5427 llvm::make_unique<FunctionSummary>(InstCount);
5428 FS->setModulePath(ModuleIdMap[ModuleId]);
5429 SummaryMap[CurRecordBit] = std::move(FS);
5433 llvm_unreachable("Exit infinite loop");
5436 // Parse the module string table block into the Index.
5437 // This populates the ModulePathStringTable map in the index.
5438 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5439 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5440 return error("Invalid record");
5442 SmallVector<uint64_t, 64> Record;
5444 SmallString<128> ModulePath;
5446 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5448 switch (Entry.Kind) {
5449 case BitstreamEntry::SubBlock: // Handled for us already.
5450 case BitstreamEntry::Error:
5451 return error("Malformed block");
5452 case BitstreamEntry::EndBlock:
5453 return std::error_code();
5454 case BitstreamEntry::Record:
5455 // The interesting case.
5460 switch (Stream.readRecord(Entry.ID, Record)) {
5461 default: // Default behavior: ignore.
5463 case bitc::MST_CODE_ENTRY: {
5464 // MST_ENTRY: [modid, namechar x N]
5465 if (convertToString(Record, 1, ModulePath))
5466 return error("Invalid record");
5467 uint64_t ModuleId = Record[0];
5468 StringRef ModulePathInMap =
5469 TheIndex->addModulePath(ModulePath, ModuleId);
5470 ModuleIdMap[ModuleId] = ModulePathInMap;
5476 llvm_unreachable("Exit infinite loop");
5479 // Parse the function info index from the bitcode streamer into the given index.
5480 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5481 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5484 if (std::error_code EC = initStream(std::move(Streamer))) return EC;
5486 // Sniff for the signature.
5487 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
5489 // We expect a number of well-defined blocks, though we don't necessarily
5490 // need to understand them all.
5492 if (Stream.AtEndOfStream()) {
5493 // We didn't really read a proper Module block.
5494 return error("Malformed block");
5497 BitstreamEntry Entry =
5498 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5500 if (Entry.Kind != BitstreamEntry::SubBlock) return error("Malformed block");
5502 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5503 // building the function summary index.
5504 if (Entry.ID == bitc::MODULE_BLOCK_ID) return parseModule();
5506 if (Stream.SkipBlock()) return error("Invalid record");
5510 // Parse the function information at the given offset in the buffer into
5511 // the index. Used to support lazy parsing of function summaries from the
5512 // combined index during importing.
5513 // TODO: This function is not yet complete as it won't have a consumer
5514 // until ThinLTO function importing is added.
5515 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5516 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5517 size_t FunctionSummaryOffset) {
5520 if (std::error_code EC = initStream(std::move(Streamer))) return EC;
5522 // Sniff for the signature.
5523 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
5525 Stream.JumpToBit(FunctionSummaryOffset);
5527 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5529 switch (Entry.Kind) {
5531 return error("Malformed block");
5532 case BitstreamEntry::Record:
5533 // The expected case.
5537 // TODO: Read a record. This interface will be completed when ThinLTO
5538 // importing is added so that it can be tested.
5539 SmallVector<uint64_t, 64> Record;
5540 switch (Stream.readRecord(Entry.ID, Record)) {
5541 case bitc::FS_CODE_COMBINED_ENTRY:
5543 return error("Invalid record");
5546 return std::error_code();
5549 std::error_code FunctionIndexBitcodeReader::initStream(
5550 std::unique_ptr<DataStreamer> Streamer) {
5551 if (Streamer) return initLazyStream(std::move(Streamer));
5552 return initStreamFromBuffer();
5555 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5556 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5557 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5559 if (Buffer->getBufferSize() & 3) return error("Invalid bitcode signature");
5561 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5562 // The magic number is 0x0B17C0DE stored in little endian.
5563 if (isBitcodeWrapper(BufPtr, BufEnd))
5564 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5565 return error("Invalid bitcode wrapper header");
5567 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5568 Stream.init(&*StreamFile);
5570 return std::error_code();
5573 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5574 std::unique_ptr<DataStreamer> Streamer) {
5575 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5578 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5579 StreamingMemoryObject &Bytes = *OwnedBytes;
5580 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5581 Stream.init(&*StreamFile);
5583 unsigned char buf[16];
5584 if (Bytes.readBytes(buf, 16, 0) != 16)
5585 return error("Invalid bitcode signature");
5587 if (!isBitcode(buf, buf + 16)) return error("Invalid bitcode signature");
5589 if (isBitcodeWrapper(buf, buf + 4)) {
5590 const unsigned char *bitcodeStart = buf;
5591 const unsigned char *bitcodeEnd = buf + 16;
5592 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5593 Bytes.dropLeadingBytes(bitcodeStart - buf);
5594 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5596 return std::error_code();
5600 class BitcodeErrorCategoryType : public std::error_category {
5601 const char *name() const LLVM_NOEXCEPT override {
5602 return "llvm.bitcode";
5604 std::string message(int IE) const override {
5605 BitcodeError E = static_cast<BitcodeError>(IE);
5607 case BitcodeError::InvalidBitcodeSignature:
5608 return "Invalid bitcode signature";
5609 case BitcodeError::CorruptedBitcode:
5610 return "Corrupted bitcode";
5612 llvm_unreachable("Unknown error type!");
5617 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5619 const std::error_category &llvm::BitcodeErrorCategory() {
5620 return *ErrorCategory;
5623 //===----------------------------------------------------------------------===//
5624 // External interface
5625 //===----------------------------------------------------------------------===//
5627 static ErrorOr<std::unique_ptr<Module>>
5628 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5629 BitcodeReader *R, LLVMContext &Context,
5630 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5631 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5632 M->setMaterializer(R);
5634 auto cleanupOnError = [&](std::error_code EC) {
5635 R->releaseBuffer(); // Never take ownership on error.
5639 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5640 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5641 ShouldLazyLoadMetadata))
5642 return cleanupOnError(EC);
5644 if (MaterializeAll) {
5645 // Read in the entire module, and destroy the BitcodeReader.
5646 if (std::error_code EC = M->materializeAllPermanently())
5647 return cleanupOnError(EC);
5649 // Resolve forward references from blockaddresses.
5650 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5651 return cleanupOnError(EC);
5653 return std::move(M);
5656 /// \brief Get a lazy one-at-time loading module from bitcode.
5658 /// This isn't always used in a lazy context. In particular, it's also used by
5659 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5660 /// in forward-referenced functions from block address references.
5662 /// \param[in] MaterializeAll Set to \c true if we should materialize
5664 static ErrorOr<std::unique_ptr<Module>>
5665 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5666 LLVMContext &Context, bool MaterializeAll,
5667 DiagnosticHandlerFunction DiagnosticHandler,
5668 bool ShouldLazyLoadMetadata = false) {
5670 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5672 ErrorOr<std::unique_ptr<Module>> Ret =
5673 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5674 MaterializeAll, ShouldLazyLoadMetadata);
5678 Buffer.release(); // The BitcodeReader owns it now.
5682 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5683 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5684 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5685 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5686 DiagnosticHandler, ShouldLazyLoadMetadata);
5689 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5690 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5691 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5692 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5693 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5695 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5699 ErrorOr<std::unique_ptr<Module>>
5700 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5701 DiagnosticHandlerFunction DiagnosticHandler) {
5702 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5703 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5705 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5706 // written. We must defer until the Module has been fully materialized.
5710 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5711 DiagnosticHandlerFunction DiagnosticHandler) {
5712 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5713 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5715 ErrorOr<std::string> Triple = R->parseTriple();
5716 if (Triple.getError())
5718 return Triple.get();
5721 // Parse the specified bitcode buffer, returning the function info index.
5722 // If IsLazy is false, parse the entire function summary into
5723 // the index. Otherwise skip the function summary section, and only create
5724 // an index object with a map from function name to function summary offset.
5725 // The index is used to perform lazy function summary reading later.
5726 ErrorOr<std::unique_ptr<FunctionInfoIndex>> llvm::getFunctionInfoIndex(
5727 MemoryBufferRef Buffer, LLVMContext &Context,
5728 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy) {
5729 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5730 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, IsLazy);
5732 std::unique_ptr<FunctionInfoIndex> Index =
5733 llvm::make_unique<FunctionInfoIndex>();
5735 auto cleanupOnError = [&](std::error_code EC) {
5736 R.releaseBuffer(); // Never take ownership on error.
5740 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5741 return cleanupOnError(EC);
5743 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5744 return std::move(Index);
5747 // Check if the given bitcode buffer contains a function summary block.
5748 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5749 DiagnosticHandlerFunction DiagnosticHandler) {
5750 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5751 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, false,
5754 auto cleanupOnError = [&](std::error_code EC) {
5755 R.releaseBuffer(); // Never take ownership on error.
5759 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5760 return cleanupOnError(EC);
5762 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5763 return R.foundFuncSummary();
5766 // This method supports lazy reading of function summary data from the combined
5767 // index during ThinLTO function importing. When reading the combined index
5768 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5769 // Then this method is called for each function considered for importing,
5770 // to parse the summary information for the given function name into
5772 std::error_code llvm::readFunctionSummary(
5773 MemoryBufferRef Buffer, LLVMContext &Context,
5774 DiagnosticHandlerFunction DiagnosticHandler, StringRef FunctionName,
5775 std::unique_ptr<FunctionInfoIndex> Index) {
5776 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5777 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler);
5779 auto cleanupOnError = [&](std::error_code EC) {
5780 R.releaseBuffer(); // Never take ownership on error.
5784 // Lookup the given function name in the FunctionMap, which may
5785 // contain a list of function infos in the case of a COMDAT. Walk through
5786 // and parse each function summary info at the function summary offset
5787 // recorded when parsing the value symbol table.
5788 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5789 size_t FunctionSummaryOffset = FI->bitcodeIndex();
5790 if (std::error_code EC =
5791 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5792 return cleanupOnError(EC);
5795 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5796 return std::error_code();