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/ValueHandle.h"
31 #include "llvm/Support/DataStream.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/raw_ostream.h"
41 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
44 /// Indicates which operator an operand allows (for the few operands that may
45 /// only reference a certain operator).
46 enum OperatorConstraint {
47 OC_None = 0, // No constraint
48 OC_CatchPad, // Must be CatchPadInst
49 OC_CleanupPad // Must be CleanupPadInst
52 class BitcodeReaderValueList {
53 std::vector<WeakVH> ValuePtrs;
55 /// As we resolve forward-referenced constants, we add information about them
56 /// to this vector. This allows us to resolve them in bulk instead of
57 /// resolving each reference at a time. See the code in
58 /// ResolveConstantForwardRefs for more information about this.
60 /// The key of this vector is the placeholder constant, the value is the slot
61 /// number that holds the resolved value.
62 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
63 ResolveConstantsTy ResolveConstants;
66 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
67 ~BitcodeReaderValueList() {
68 assert(ResolveConstants.empty() && "Constants not resolved?");
71 // vector compatibility methods
72 unsigned size() const { return ValuePtrs.size(); }
73 void resize(unsigned N) { ValuePtrs.resize(N); }
74 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
77 assert(ResolveConstants.empty() && "Constants not resolved?");
81 Value *operator[](unsigned i) const {
82 assert(i < ValuePtrs.size());
86 Value *back() const { return ValuePtrs.back(); }
87 void pop_back() { ValuePtrs.pop_back(); }
88 bool empty() const { return ValuePtrs.empty(); }
89 void shrinkTo(unsigned N) {
90 assert(N <= size() && "Invalid shrinkTo request!");
94 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
95 Value *getValueFwdRef(unsigned Idx, Type *Ty,
96 OperatorConstraint OC = OC_None);
98 bool assignValue(Value *V, unsigned Idx);
100 /// Once all constants are read, this method bulk resolves any forward
102 void resolveConstantForwardRefs();
105 class BitcodeReaderMDValueList {
110 std::vector<TrackingMDRef> MDValuePtrs;
112 LLVMContext &Context;
114 BitcodeReaderMDValueList(LLVMContext &C)
115 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
117 // vector compatibility methods
118 unsigned size() const { return MDValuePtrs.size(); }
119 void resize(unsigned N) { MDValuePtrs.resize(N); }
120 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
121 void clear() { MDValuePtrs.clear(); }
122 Metadata *back() const { return MDValuePtrs.back(); }
123 void pop_back() { MDValuePtrs.pop_back(); }
124 bool empty() const { return MDValuePtrs.empty(); }
126 Metadata *operator[](unsigned i) const {
127 assert(i < MDValuePtrs.size());
128 return MDValuePtrs[i];
131 void shrinkTo(unsigned N) {
132 assert(N <= size() && "Invalid shrinkTo request!");
133 MDValuePtrs.resize(N);
136 Metadata *getValueFwdRef(unsigned Idx);
137 void assignValue(Metadata *MD, unsigned Idx);
138 void tryToResolveCycles();
141 class BitcodeReader : public GVMaterializer {
142 LLVMContext &Context;
143 DiagnosticHandlerFunction DiagnosticHandler;
144 Module *TheModule = nullptr;
145 std::unique_ptr<MemoryBuffer> Buffer;
146 std::unique_ptr<BitstreamReader> StreamFile;
147 BitstreamCursor Stream;
148 uint64_t NextUnreadBit = 0;
149 bool SeenValueSymbolTable = false;
150 unsigned VSTOffset = 0;
152 std::vector<Type*> TypeList;
153 BitcodeReaderValueList ValueList;
154 BitcodeReaderMDValueList MDValueList;
155 std::vector<Comdat *> ComdatList;
156 SmallVector<Instruction *, 64> InstructionList;
158 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
159 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
160 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
161 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
162 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
164 SmallVector<Instruction*, 64> InstsWithTBAATag;
166 /// The set of attributes by index. Index zero in the file is for null, and
167 /// is thus not represented here. As such all indices are off by one.
168 std::vector<AttributeSet> MAttributes;
170 /// The set of attribute groups.
171 std::map<unsigned, AttributeSet> MAttributeGroups;
173 /// While parsing a function body, this is a list of the basic blocks for the
175 std::vector<BasicBlock*> FunctionBBs;
177 // When reading the module header, this list is populated with functions that
178 // have bodies later in the file.
179 std::vector<Function*> FunctionsWithBodies;
181 // When intrinsic functions are encountered which require upgrading they are
182 // stored here with their replacement function.
183 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
184 UpgradedIntrinsicMap UpgradedIntrinsics;
186 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
187 DenseMap<unsigned, unsigned> MDKindMap;
189 // Several operations happen after the module header has been read, but
190 // before function bodies are processed. This keeps track of whether
191 // we've done this yet.
192 bool SeenFirstFunctionBody = false;
194 /// When function bodies are initially scanned, this map contains info about
195 /// where to find deferred function body in the stream.
196 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
198 /// When Metadata block is initially scanned when parsing the module, we may
199 /// choose to defer parsing of the metadata. This vector contains info about
200 /// which Metadata blocks are deferred.
201 std::vector<uint64_t> DeferredMetadataInfo;
203 /// These are basic blocks forward-referenced by block addresses. They are
204 /// inserted lazily into functions when they're loaded. The basic block ID is
205 /// its index into the vector.
206 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
207 std::deque<Function *> BasicBlockFwdRefQueue;
209 /// Indicates that we are using a new encoding for instruction operands where
210 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
211 /// instruction number, for a more compact encoding. Some instruction
212 /// operands are not relative to the instruction ID: basic block numbers, and
213 /// types. Once the old style function blocks have been phased out, we would
214 /// not need this flag.
215 bool UseRelativeIDs = false;
217 /// True if all functions will be materialized, negating the need to process
218 /// (e.g.) blockaddress forward references.
219 bool WillMaterializeAllForwardRefs = false;
221 /// Functions that have block addresses taken. This is usually empty.
222 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
224 /// True if any Metadata block has been materialized.
225 bool IsMetadataMaterialized = false;
227 bool StripDebugInfo = false;
230 std::error_code error(BitcodeError E, const Twine &Message);
231 std::error_code error(BitcodeError E);
232 std::error_code error(const Twine &Message);
234 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
235 DiagnosticHandlerFunction DiagnosticHandler);
236 BitcodeReader(LLVMContext &Context,
237 DiagnosticHandlerFunction DiagnosticHandler);
238 ~BitcodeReader() override { freeState(); }
240 std::error_code materializeForwardReferencedFunctions();
244 void releaseBuffer();
246 bool isDematerializable(const GlobalValue *GV) const override;
247 std::error_code materialize(GlobalValue *GV) override;
248 std::error_code materializeModule(Module *M) override;
249 std::vector<StructType *> getIdentifiedStructTypes() const override;
250 void dematerialize(GlobalValue *GV) override;
252 /// \brief Main interface to parsing a bitcode buffer.
253 /// \returns true if an error occurred.
254 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
256 bool ShouldLazyLoadMetadata = false);
258 /// \brief Cheap mechanism to just extract module triple
259 /// \returns true if an error occurred.
260 ErrorOr<std::string> parseTriple();
262 static uint64_t decodeSignRotatedValue(uint64_t V);
264 /// Materialize any deferred Metadata block.
265 std::error_code materializeMetadata() override;
267 void setStripDebugInfo() override;
270 std::vector<StructType *> IdentifiedStructTypes;
271 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
272 StructType *createIdentifiedStructType(LLVMContext &Context);
274 Type *getTypeByID(unsigned ID);
275 Value *getFnValueByID(unsigned ID, Type *Ty,
276 OperatorConstraint OC = OC_None) {
277 if (Ty && Ty->isMetadataTy())
278 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
279 return ValueList.getValueFwdRef(ID, Ty, OC);
281 Metadata *getFnMetadataByID(unsigned ID) {
282 return MDValueList.getValueFwdRef(ID);
284 BasicBlock *getBasicBlock(unsigned ID) const {
285 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
286 return FunctionBBs[ID];
288 AttributeSet getAttributes(unsigned i) const {
289 if (i-1 < MAttributes.size())
290 return MAttributes[i-1];
291 return AttributeSet();
294 /// Read a value/type pair out of the specified record from slot 'Slot'.
295 /// Increment Slot past the number of slots used in the record. Return true on
297 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
298 unsigned InstNum, Value *&ResVal) {
299 if (Slot == Record.size()) return true;
300 unsigned ValNo = (unsigned)Record[Slot++];
301 // Adjust the ValNo, if it was encoded relative to the InstNum.
303 ValNo = InstNum - ValNo;
304 if (ValNo < InstNum) {
305 // If this is not a forward reference, just return the value we already
307 ResVal = getFnValueByID(ValNo, nullptr);
308 return ResVal == nullptr;
310 if (Slot == Record.size())
313 unsigned TypeNo = (unsigned)Record[Slot++];
314 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
315 return ResVal == nullptr;
318 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
319 /// past the number of slots used by the value in the record. Return true if
320 /// there is an error.
321 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
322 unsigned InstNum, Type *Ty, Value *&ResVal,
323 OperatorConstraint OC = OC_None) {
324 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
326 // All values currently take a single record slot.
331 /// Like popValue, but does not increment the Slot number.
332 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
333 unsigned InstNum, Type *Ty, Value *&ResVal,
334 OperatorConstraint OC = OC_None) {
335 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
336 return ResVal == nullptr;
339 /// Version of getValue that returns ResVal directly, or 0 if there is an
341 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
342 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
343 if (Slot == Record.size()) return nullptr;
344 unsigned ValNo = (unsigned)Record[Slot];
345 // Adjust the ValNo, if it was encoded relative to the InstNum.
347 ValNo = InstNum - ValNo;
348 return getFnValueByID(ValNo, Ty, OC);
351 /// Like getValue, but decodes signed VBRs.
352 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
353 unsigned InstNum, Type *Ty,
354 OperatorConstraint OC = OC_None) {
355 if (Slot == Record.size()) return nullptr;
356 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
357 // Adjust the ValNo, if it was encoded relative to the InstNum.
359 ValNo = InstNum - ValNo;
360 return getFnValueByID(ValNo, Ty, OC);
363 /// Converts alignment exponent (i.e. power of two (or zero)) to the
364 /// corresponding alignment to use. If alignment is too large, returns
365 /// a corresponding error code.
366 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
367 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
368 std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
369 std::error_code parseAttributeBlock();
370 std::error_code parseAttributeGroupBlock();
371 std::error_code parseTypeTable();
372 std::error_code parseTypeTableBody();
374 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
375 unsigned NameIndex, Triple &TT);
376 std::error_code parseValueSymbolTable(unsigned Offset = 0);
377 std::error_code parseConstants();
378 std::error_code rememberAndSkipFunctionBody();
379 /// Save the positions of the Metadata blocks and skip parsing the blocks.
380 std::error_code rememberAndSkipMetadata();
381 std::error_code parseFunctionBody(Function *F);
382 std::error_code globalCleanup();
383 std::error_code resolveGlobalAndAliasInits();
384 std::error_code parseMetadata();
385 std::error_code parseMetadataAttachment(Function &F);
386 ErrorOr<std::string> parseModuleTriple();
387 std::error_code parseUseLists();
388 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
389 std::error_code initStreamFromBuffer();
390 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
391 std::error_code findFunctionInStream(
393 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
397 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
398 DiagnosticSeverity Severity,
400 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
402 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
404 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
405 std::error_code EC, const Twine &Message) {
406 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
407 DiagnosticHandler(DI);
411 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
412 std::error_code EC) {
413 return error(DiagnosticHandler, EC, EC.message());
416 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
417 const Twine &Message) {
418 return error(DiagnosticHandler,
419 make_error_code(BitcodeError::CorruptedBitcode), Message);
422 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
423 return ::error(DiagnosticHandler, make_error_code(E), Message);
426 std::error_code BitcodeReader::error(const Twine &Message) {
427 return ::error(DiagnosticHandler,
428 make_error_code(BitcodeError::CorruptedBitcode), Message);
431 std::error_code BitcodeReader::error(BitcodeError E) {
432 return ::error(DiagnosticHandler, make_error_code(E));
435 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
439 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
442 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
443 DiagnosticHandlerFunction DiagnosticHandler)
445 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
446 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
448 BitcodeReader::BitcodeReader(LLVMContext &Context,
449 DiagnosticHandlerFunction DiagnosticHandler)
451 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
452 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
454 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
455 if (WillMaterializeAllForwardRefs)
456 return std::error_code();
458 // Prevent recursion.
459 WillMaterializeAllForwardRefs = true;
461 while (!BasicBlockFwdRefQueue.empty()) {
462 Function *F = BasicBlockFwdRefQueue.front();
463 BasicBlockFwdRefQueue.pop_front();
464 assert(F && "Expected valid function");
465 if (!BasicBlockFwdRefs.count(F))
466 // Already materialized.
469 // Check for a function that isn't materializable to prevent an infinite
470 // loop. When parsing a blockaddress stored in a global variable, there
471 // isn't a trivial way to check if a function will have a body without a
472 // linear search through FunctionsWithBodies, so just check it here.
473 if (!F->isMaterializable())
474 return error("Never resolved function from blockaddress");
476 // Try to materialize F.
477 if (std::error_code EC = materialize(F))
480 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
483 WillMaterializeAllForwardRefs = false;
484 return std::error_code();
487 void BitcodeReader::freeState() {
489 std::vector<Type*>().swap(TypeList);
492 std::vector<Comdat *>().swap(ComdatList);
494 std::vector<AttributeSet>().swap(MAttributes);
495 std::vector<BasicBlock*>().swap(FunctionBBs);
496 std::vector<Function*>().swap(FunctionsWithBodies);
497 DeferredFunctionInfo.clear();
498 DeferredMetadataInfo.clear();
501 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
502 BasicBlockFwdRefQueue.clear();
505 //===----------------------------------------------------------------------===//
506 // Helper functions to implement forward reference resolution, etc.
507 //===----------------------------------------------------------------------===//
509 /// Convert a string from a record into an std::string, return true on failure.
510 template <typename StrTy>
511 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
513 if (Idx > Record.size())
516 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
517 Result += (char)Record[i];
521 static bool hasImplicitComdat(size_t Val) {
525 case 1: // Old WeakAnyLinkage
526 case 4: // Old LinkOnceAnyLinkage
527 case 10: // Old WeakODRLinkage
528 case 11: // Old LinkOnceODRLinkage
533 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
535 default: // Map unknown/new linkages to external
537 return GlobalValue::ExternalLinkage;
539 return GlobalValue::AppendingLinkage;
541 return GlobalValue::InternalLinkage;
543 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
545 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
547 return GlobalValue::ExternalWeakLinkage;
549 return GlobalValue::CommonLinkage;
551 return GlobalValue::PrivateLinkage;
553 return GlobalValue::AvailableExternallyLinkage;
555 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
557 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
559 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
560 case 1: // Old value with implicit comdat.
562 return GlobalValue::WeakAnyLinkage;
563 case 10: // Old value with implicit comdat.
565 return GlobalValue::WeakODRLinkage;
566 case 4: // Old value with implicit comdat.
568 return GlobalValue::LinkOnceAnyLinkage;
569 case 11: // Old value with implicit comdat.
571 return GlobalValue::LinkOnceODRLinkage;
575 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
577 default: // Map unknown visibilities to default.
578 case 0: return GlobalValue::DefaultVisibility;
579 case 1: return GlobalValue::HiddenVisibility;
580 case 2: return GlobalValue::ProtectedVisibility;
584 static GlobalValue::DLLStorageClassTypes
585 getDecodedDLLStorageClass(unsigned Val) {
587 default: // Map unknown values to default.
588 case 0: return GlobalValue::DefaultStorageClass;
589 case 1: return GlobalValue::DLLImportStorageClass;
590 case 2: return GlobalValue::DLLExportStorageClass;
594 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
596 case 0: return GlobalVariable::NotThreadLocal;
597 default: // Map unknown non-zero value to general dynamic.
598 case 1: return GlobalVariable::GeneralDynamicTLSModel;
599 case 2: return GlobalVariable::LocalDynamicTLSModel;
600 case 3: return GlobalVariable::InitialExecTLSModel;
601 case 4: return GlobalVariable::LocalExecTLSModel;
605 static int getDecodedCastOpcode(unsigned Val) {
608 case bitc::CAST_TRUNC : return Instruction::Trunc;
609 case bitc::CAST_ZEXT : return Instruction::ZExt;
610 case bitc::CAST_SEXT : return Instruction::SExt;
611 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
612 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
613 case bitc::CAST_UITOFP : return Instruction::UIToFP;
614 case bitc::CAST_SITOFP : return Instruction::SIToFP;
615 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
616 case bitc::CAST_FPEXT : return Instruction::FPExt;
617 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
618 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
619 case bitc::CAST_BITCAST : return Instruction::BitCast;
620 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
624 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
625 bool IsFP = Ty->isFPOrFPVectorTy();
626 // BinOps are only valid for int/fp or vector of int/fp types
627 if (!IsFP && !Ty->isIntOrIntVectorTy())
633 case bitc::BINOP_ADD:
634 return IsFP ? Instruction::FAdd : Instruction::Add;
635 case bitc::BINOP_SUB:
636 return IsFP ? Instruction::FSub : Instruction::Sub;
637 case bitc::BINOP_MUL:
638 return IsFP ? Instruction::FMul : Instruction::Mul;
639 case bitc::BINOP_UDIV:
640 return IsFP ? -1 : Instruction::UDiv;
641 case bitc::BINOP_SDIV:
642 return IsFP ? Instruction::FDiv : Instruction::SDiv;
643 case bitc::BINOP_UREM:
644 return IsFP ? -1 : Instruction::URem;
645 case bitc::BINOP_SREM:
646 return IsFP ? Instruction::FRem : Instruction::SRem;
647 case bitc::BINOP_SHL:
648 return IsFP ? -1 : Instruction::Shl;
649 case bitc::BINOP_LSHR:
650 return IsFP ? -1 : Instruction::LShr;
651 case bitc::BINOP_ASHR:
652 return IsFP ? -1 : Instruction::AShr;
653 case bitc::BINOP_AND:
654 return IsFP ? -1 : Instruction::And;
656 return IsFP ? -1 : Instruction::Or;
657 case bitc::BINOP_XOR:
658 return IsFP ? -1 : Instruction::Xor;
662 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
664 default: return AtomicRMWInst::BAD_BINOP;
665 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
666 case bitc::RMW_ADD: return AtomicRMWInst::Add;
667 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
668 case bitc::RMW_AND: return AtomicRMWInst::And;
669 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
670 case bitc::RMW_OR: return AtomicRMWInst::Or;
671 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
672 case bitc::RMW_MAX: return AtomicRMWInst::Max;
673 case bitc::RMW_MIN: return AtomicRMWInst::Min;
674 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
675 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
679 static AtomicOrdering getDecodedOrdering(unsigned Val) {
681 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
682 case bitc::ORDERING_UNORDERED: return Unordered;
683 case bitc::ORDERING_MONOTONIC: return Monotonic;
684 case bitc::ORDERING_ACQUIRE: return Acquire;
685 case bitc::ORDERING_RELEASE: return Release;
686 case bitc::ORDERING_ACQREL: return AcquireRelease;
687 default: // Map unknown orderings to sequentially-consistent.
688 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
692 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
694 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
695 default: // Map unknown scopes to cross-thread.
696 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
700 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
702 default: // Map unknown selection kinds to any.
703 case bitc::COMDAT_SELECTION_KIND_ANY:
705 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
706 return Comdat::ExactMatch;
707 case bitc::COMDAT_SELECTION_KIND_LARGEST:
708 return Comdat::Largest;
709 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
710 return Comdat::NoDuplicates;
711 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
712 return Comdat::SameSize;
716 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
718 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
719 FMF.setUnsafeAlgebra();
720 if (0 != (Val & FastMathFlags::NoNaNs))
722 if (0 != (Val & FastMathFlags::NoInfs))
724 if (0 != (Val & FastMathFlags::NoSignedZeros))
725 FMF.setNoSignedZeros();
726 if (0 != (Val & FastMathFlags::AllowReciprocal))
727 FMF.setAllowReciprocal();
731 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
733 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
734 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
740 /// \brief A class for maintaining the slot number definition
741 /// as a placeholder for the actual definition for forward constants defs.
742 class ConstantPlaceHolder : public ConstantExpr {
743 void operator=(const ConstantPlaceHolder &) = delete;
746 // allocate space for exactly one operand
747 void *operator new(size_t s) { return User::operator new(s, 1); }
748 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
749 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
750 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
753 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
754 static bool classof(const Value *V) {
755 return isa<ConstantExpr>(V) &&
756 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
759 /// Provide fast operand accessors
760 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
764 // FIXME: can we inherit this from ConstantExpr?
766 struct OperandTraits<ConstantPlaceHolder> :
767 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
769 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
772 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
781 WeakVH &OldV = ValuePtrs[Idx];
787 // Handle constants and non-constants (e.g. instrs) differently for
789 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
790 ResolveConstants.push_back(std::make_pair(PHC, Idx));
793 // If there was a forward reference to this value, replace it.
794 Value *PrevVal = OldV;
795 // Check operator constraints. We only put cleanuppads or catchpads in
796 // the forward value map if the value is constrained to match.
797 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
798 if (!isa<CatchPadInst>(V))
800 // Delete the dummy basic block that was created with the sentinel
802 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
803 assert(DummyBlock == CatchPad->getNormalDest());
804 CatchPad->dropAllReferences();
806 } else if (isa<CleanupPadInst>(PrevVal)) {
807 if (!isa<CleanupPadInst>(V))
810 OldV->replaceAllUsesWith(V);
818 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
823 if (Value *V = ValuePtrs[Idx]) {
824 if (Ty != V->getType())
825 report_fatal_error("Type mismatch in constant table!");
826 return cast<Constant>(V);
829 // Create and return a placeholder, which will later be RAUW'd.
830 Constant *C = new ConstantPlaceHolder(Ty, Context);
835 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
836 OperatorConstraint OC) {
837 // Bail out for a clearly invalid value. This would make us call resize(0)
844 if (Value *V = ValuePtrs[Idx]) {
845 // If the types don't match, it's invalid.
846 if (Ty && Ty != V->getType())
850 // Use dyn_cast to enforce operator constraints
853 return dyn_cast<CatchPadInst>(V);
855 return dyn_cast<CleanupPadInst>(V);
857 llvm_unreachable("Unexpected operator constraint");
861 // No type specified, must be invalid reference.
862 if (!Ty) return nullptr;
864 // Create and return a placeholder, which will later be RAUW'd.
868 V = new Argument(Ty);
871 BasicBlock *BB = BasicBlock::Create(Context);
872 V = CatchPadInst::Create(BB, BB, {});
876 assert(OC == OC_CleanupPad && "unexpected operator constraint");
877 V = CleanupPadInst::Create(Context, {});
885 /// Once all constants are read, this method bulk resolves any forward
886 /// references. The idea behind this is that we sometimes get constants (such
887 /// as large arrays) which reference *many* forward ref constants. Replacing
888 /// each of these causes a lot of thrashing when building/reuniquing the
889 /// constant. Instead of doing this, we look at all the uses and rewrite all
890 /// the place holders at once for any constant that uses a placeholder.
891 void BitcodeReaderValueList::resolveConstantForwardRefs() {
892 // Sort the values by-pointer so that they are efficient to look up with a
894 std::sort(ResolveConstants.begin(), ResolveConstants.end());
896 SmallVector<Constant*, 64> NewOps;
898 while (!ResolveConstants.empty()) {
899 Value *RealVal = operator[](ResolveConstants.back().second);
900 Constant *Placeholder = ResolveConstants.back().first;
901 ResolveConstants.pop_back();
903 // Loop over all users of the placeholder, updating them to reference the
904 // new value. If they reference more than one placeholder, update them all
906 while (!Placeholder->use_empty()) {
907 auto UI = Placeholder->user_begin();
910 // If the using object isn't uniqued, just update the operands. This
911 // handles instructions and initializers for global variables.
912 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
913 UI.getUse().set(RealVal);
917 // Otherwise, we have a constant that uses the placeholder. Replace that
918 // constant with a new constant that has *all* placeholder uses updated.
919 Constant *UserC = cast<Constant>(U);
920 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
923 if (!isa<ConstantPlaceHolder>(*I)) {
924 // Not a placeholder reference.
926 } else if (*I == Placeholder) {
927 // Common case is that it just references this one placeholder.
930 // Otherwise, look up the placeholder in ResolveConstants.
931 ResolveConstantsTy::iterator It =
932 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
933 std::pair<Constant*, unsigned>(cast<Constant>(*I),
935 assert(It != ResolveConstants.end() && It->first == *I);
936 NewOp = operator[](It->second);
939 NewOps.push_back(cast<Constant>(NewOp));
942 // Make the new constant.
944 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
945 NewC = ConstantArray::get(UserCA->getType(), NewOps);
946 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
947 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
948 } else if (isa<ConstantVector>(UserC)) {
949 NewC = ConstantVector::get(NewOps);
951 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
952 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
955 UserC->replaceAllUsesWith(NewC);
956 UserC->destroyConstant();
960 // Update all ValueHandles, they should be the only users at this point.
961 Placeholder->replaceAllUsesWith(RealVal);
966 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
975 TrackingMDRef &OldMD = MDValuePtrs[Idx];
981 // If there was a forward reference to this value, replace it.
982 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
983 PrevMD->replaceAllUsesWith(MD);
987 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
991 if (Metadata *MD = MDValuePtrs[Idx])
994 // Track forward refs to be resolved later.
996 MinFwdRef = std::min(MinFwdRef, Idx);
997 MaxFwdRef = std::max(MaxFwdRef, Idx);
1000 MinFwdRef = MaxFwdRef = Idx;
1004 // Create and return a placeholder, which will later be RAUW'd.
1005 Metadata *MD = MDNode::getTemporary(Context, None).release();
1006 MDValuePtrs[Idx].reset(MD);
1010 void BitcodeReaderMDValueList::tryToResolveCycles() {
1016 // Still forward references... can't resolve cycles.
1019 // Resolve any cycles.
1020 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1021 auto &MD = MDValuePtrs[I];
1022 auto *N = dyn_cast_or_null<MDNode>(MD);
1026 assert(!N->isTemporary() && "Unexpected forward reference");
1030 // Make sure we return early again until there's another forward ref.
1034 Type *BitcodeReader::getTypeByID(unsigned ID) {
1035 // The type table size is always specified correctly.
1036 if (ID >= TypeList.size())
1039 if (Type *Ty = TypeList[ID])
1042 // If we have a forward reference, the only possible case is when it is to a
1043 // named struct. Just create a placeholder for now.
1044 return TypeList[ID] = createIdentifiedStructType(Context);
1047 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1049 auto *Ret = StructType::create(Context, Name);
1050 IdentifiedStructTypes.push_back(Ret);
1054 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1055 auto *Ret = StructType::create(Context);
1056 IdentifiedStructTypes.push_back(Ret);
1061 //===----------------------------------------------------------------------===//
1062 // Functions for parsing blocks from the bitcode file
1063 //===----------------------------------------------------------------------===//
1066 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1067 /// been decoded from the given integer. This function must stay in sync with
1068 /// 'encodeLLVMAttributesForBitcode'.
1069 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1070 uint64_t EncodedAttrs) {
1071 // FIXME: Remove in 4.0.
1073 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1074 // the bits above 31 down by 11 bits.
1075 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1076 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1077 "Alignment must be a power of two.");
1080 B.addAlignmentAttr(Alignment);
1081 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1082 (EncodedAttrs & 0xffff));
1085 std::error_code BitcodeReader::parseAttributeBlock() {
1086 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1087 return error("Invalid record");
1089 if (!MAttributes.empty())
1090 return error("Invalid multiple blocks");
1092 SmallVector<uint64_t, 64> Record;
1094 SmallVector<AttributeSet, 8> Attrs;
1096 // Read all the records.
1098 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1100 switch (Entry.Kind) {
1101 case BitstreamEntry::SubBlock: // Handled for us already.
1102 case BitstreamEntry::Error:
1103 return error("Malformed block");
1104 case BitstreamEntry::EndBlock:
1105 return std::error_code();
1106 case BitstreamEntry::Record:
1107 // The interesting case.
1113 switch (Stream.readRecord(Entry.ID, Record)) {
1114 default: // Default behavior: ignore.
1116 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1117 // FIXME: Remove in 4.0.
1118 if (Record.size() & 1)
1119 return error("Invalid record");
1121 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1123 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1124 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1127 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1131 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1132 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1133 Attrs.push_back(MAttributeGroups[Record[i]]);
1135 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1143 // Returns Attribute::None on unrecognized codes.
1144 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1147 return Attribute::None;
1148 case bitc::ATTR_KIND_ALIGNMENT:
1149 return Attribute::Alignment;
1150 case bitc::ATTR_KIND_ALWAYS_INLINE:
1151 return Attribute::AlwaysInline;
1152 case bitc::ATTR_KIND_ARGMEMONLY:
1153 return Attribute::ArgMemOnly;
1154 case bitc::ATTR_KIND_BUILTIN:
1155 return Attribute::Builtin;
1156 case bitc::ATTR_KIND_BY_VAL:
1157 return Attribute::ByVal;
1158 case bitc::ATTR_KIND_IN_ALLOCA:
1159 return Attribute::InAlloca;
1160 case bitc::ATTR_KIND_COLD:
1161 return Attribute::Cold;
1162 case bitc::ATTR_KIND_CONVERGENT:
1163 return Attribute::Convergent;
1164 case bitc::ATTR_KIND_INLINE_HINT:
1165 return Attribute::InlineHint;
1166 case bitc::ATTR_KIND_IN_REG:
1167 return Attribute::InReg;
1168 case bitc::ATTR_KIND_JUMP_TABLE:
1169 return Attribute::JumpTable;
1170 case bitc::ATTR_KIND_MIN_SIZE:
1171 return Attribute::MinSize;
1172 case bitc::ATTR_KIND_NAKED:
1173 return Attribute::Naked;
1174 case bitc::ATTR_KIND_NEST:
1175 return Attribute::Nest;
1176 case bitc::ATTR_KIND_NO_ALIAS:
1177 return Attribute::NoAlias;
1178 case bitc::ATTR_KIND_NO_BUILTIN:
1179 return Attribute::NoBuiltin;
1180 case bitc::ATTR_KIND_NO_CAPTURE:
1181 return Attribute::NoCapture;
1182 case bitc::ATTR_KIND_NO_DUPLICATE:
1183 return Attribute::NoDuplicate;
1184 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1185 return Attribute::NoImplicitFloat;
1186 case bitc::ATTR_KIND_NO_INLINE:
1187 return Attribute::NoInline;
1188 case bitc::ATTR_KIND_NON_LAZY_BIND:
1189 return Attribute::NonLazyBind;
1190 case bitc::ATTR_KIND_NON_NULL:
1191 return Attribute::NonNull;
1192 case bitc::ATTR_KIND_DEREFERENCEABLE:
1193 return Attribute::Dereferenceable;
1194 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1195 return Attribute::DereferenceableOrNull;
1196 case bitc::ATTR_KIND_NO_RED_ZONE:
1197 return Attribute::NoRedZone;
1198 case bitc::ATTR_KIND_NO_RETURN:
1199 return Attribute::NoReturn;
1200 case bitc::ATTR_KIND_NO_UNWIND:
1201 return Attribute::NoUnwind;
1202 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1203 return Attribute::OptimizeForSize;
1204 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1205 return Attribute::OptimizeNone;
1206 case bitc::ATTR_KIND_READ_NONE:
1207 return Attribute::ReadNone;
1208 case bitc::ATTR_KIND_READ_ONLY:
1209 return Attribute::ReadOnly;
1210 case bitc::ATTR_KIND_RETURNED:
1211 return Attribute::Returned;
1212 case bitc::ATTR_KIND_RETURNS_TWICE:
1213 return Attribute::ReturnsTwice;
1214 case bitc::ATTR_KIND_S_EXT:
1215 return Attribute::SExt;
1216 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1217 return Attribute::StackAlignment;
1218 case bitc::ATTR_KIND_STACK_PROTECT:
1219 return Attribute::StackProtect;
1220 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1221 return Attribute::StackProtectReq;
1222 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1223 return Attribute::StackProtectStrong;
1224 case bitc::ATTR_KIND_SAFESTACK:
1225 return Attribute::SafeStack;
1226 case bitc::ATTR_KIND_STRUCT_RET:
1227 return Attribute::StructRet;
1228 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1229 return Attribute::SanitizeAddress;
1230 case bitc::ATTR_KIND_SANITIZE_THREAD:
1231 return Attribute::SanitizeThread;
1232 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1233 return Attribute::SanitizeMemory;
1234 case bitc::ATTR_KIND_UW_TABLE:
1235 return Attribute::UWTable;
1236 case bitc::ATTR_KIND_Z_EXT:
1237 return Attribute::ZExt;
1241 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1242 unsigned &Alignment) {
1243 // Note: Alignment in bitcode files is incremented by 1, so that zero
1244 // can be used for default alignment.
1245 if (Exponent > Value::MaxAlignmentExponent + 1)
1246 return error("Invalid alignment value");
1247 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1248 return std::error_code();
1251 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1252 Attribute::AttrKind *Kind) {
1253 *Kind = getAttrFromCode(Code);
1254 if (*Kind == Attribute::None)
1255 return error(BitcodeError::CorruptedBitcode,
1256 "Unknown attribute kind (" + Twine(Code) + ")");
1257 return std::error_code();
1260 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1261 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1262 return error("Invalid record");
1264 if (!MAttributeGroups.empty())
1265 return error("Invalid multiple blocks");
1267 SmallVector<uint64_t, 64> Record;
1269 // Read all the records.
1271 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1273 switch (Entry.Kind) {
1274 case BitstreamEntry::SubBlock: // Handled for us already.
1275 case BitstreamEntry::Error:
1276 return error("Malformed block");
1277 case BitstreamEntry::EndBlock:
1278 return std::error_code();
1279 case BitstreamEntry::Record:
1280 // The interesting case.
1286 switch (Stream.readRecord(Entry.ID, Record)) {
1287 default: // Default behavior: ignore.
1289 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1290 if (Record.size() < 3)
1291 return error("Invalid record");
1293 uint64_t GrpID = Record[0];
1294 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1297 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1298 if (Record[i] == 0) { // Enum attribute
1299 Attribute::AttrKind Kind;
1300 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1303 B.addAttribute(Kind);
1304 } else if (Record[i] == 1) { // Integer attribute
1305 Attribute::AttrKind Kind;
1306 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1308 if (Kind == Attribute::Alignment)
1309 B.addAlignmentAttr(Record[++i]);
1310 else if (Kind == Attribute::StackAlignment)
1311 B.addStackAlignmentAttr(Record[++i]);
1312 else if (Kind == Attribute::Dereferenceable)
1313 B.addDereferenceableAttr(Record[++i]);
1314 else if (Kind == Attribute::DereferenceableOrNull)
1315 B.addDereferenceableOrNullAttr(Record[++i]);
1316 } else { // String attribute
1317 assert((Record[i] == 3 || Record[i] == 4) &&
1318 "Invalid attribute group entry");
1319 bool HasValue = (Record[i++] == 4);
1320 SmallString<64> KindStr;
1321 SmallString<64> ValStr;
1323 while (Record[i] != 0 && i != e)
1324 KindStr += Record[i++];
1325 assert(Record[i] == 0 && "Kind string not null terminated");
1328 // Has a value associated with it.
1329 ++i; // Skip the '0' that terminates the "kind" string.
1330 while (Record[i] != 0 && i != e)
1331 ValStr += Record[i++];
1332 assert(Record[i] == 0 && "Value string not null terminated");
1335 B.addAttribute(KindStr.str(), ValStr.str());
1339 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1346 std::error_code BitcodeReader::parseTypeTable() {
1347 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1348 return error("Invalid record");
1350 return parseTypeTableBody();
1353 std::error_code BitcodeReader::parseTypeTableBody() {
1354 if (!TypeList.empty())
1355 return error("Invalid multiple blocks");
1357 SmallVector<uint64_t, 64> Record;
1358 unsigned NumRecords = 0;
1360 SmallString<64> TypeName;
1362 // Read all the records for this type table.
1364 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1366 switch (Entry.Kind) {
1367 case BitstreamEntry::SubBlock: // Handled for us already.
1368 case BitstreamEntry::Error:
1369 return error("Malformed block");
1370 case BitstreamEntry::EndBlock:
1371 if (NumRecords != TypeList.size())
1372 return error("Malformed block");
1373 return std::error_code();
1374 case BitstreamEntry::Record:
1375 // The interesting case.
1381 Type *ResultTy = nullptr;
1382 switch (Stream.readRecord(Entry.ID, Record)) {
1384 return error("Invalid value");
1385 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1386 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1387 // type list. This allows us to reserve space.
1388 if (Record.size() < 1)
1389 return error("Invalid record");
1390 TypeList.resize(Record[0]);
1392 case bitc::TYPE_CODE_VOID: // VOID
1393 ResultTy = Type::getVoidTy(Context);
1395 case bitc::TYPE_CODE_HALF: // HALF
1396 ResultTy = Type::getHalfTy(Context);
1398 case bitc::TYPE_CODE_FLOAT: // FLOAT
1399 ResultTy = Type::getFloatTy(Context);
1401 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1402 ResultTy = Type::getDoubleTy(Context);
1404 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1405 ResultTy = Type::getX86_FP80Ty(Context);
1407 case bitc::TYPE_CODE_FP128: // FP128
1408 ResultTy = Type::getFP128Ty(Context);
1410 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1411 ResultTy = Type::getPPC_FP128Ty(Context);
1413 case bitc::TYPE_CODE_LABEL: // LABEL
1414 ResultTy = Type::getLabelTy(Context);
1416 case bitc::TYPE_CODE_METADATA: // METADATA
1417 ResultTy = Type::getMetadataTy(Context);
1419 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1420 ResultTy = Type::getX86_MMXTy(Context);
1422 case bitc::TYPE_CODE_TOKEN: // TOKEN
1423 ResultTy = Type::getTokenTy(Context);
1425 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1426 if (Record.size() < 1)
1427 return error("Invalid record");
1429 uint64_t NumBits = Record[0];
1430 if (NumBits < IntegerType::MIN_INT_BITS ||
1431 NumBits > IntegerType::MAX_INT_BITS)
1432 return error("Bitwidth for integer type out of range");
1433 ResultTy = IntegerType::get(Context, NumBits);
1436 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1437 // [pointee type, address space]
1438 if (Record.size() < 1)
1439 return error("Invalid record");
1440 unsigned AddressSpace = 0;
1441 if (Record.size() == 2)
1442 AddressSpace = Record[1];
1443 ResultTy = getTypeByID(Record[0]);
1445 !PointerType::isValidElementType(ResultTy))
1446 return error("Invalid type");
1447 ResultTy = PointerType::get(ResultTy, AddressSpace);
1450 case bitc::TYPE_CODE_FUNCTION_OLD: {
1451 // FIXME: attrid is dead, remove it in LLVM 4.0
1452 // FUNCTION: [vararg, attrid, retty, paramty x N]
1453 if (Record.size() < 3)
1454 return error("Invalid record");
1455 SmallVector<Type*, 8> ArgTys;
1456 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1457 if (Type *T = getTypeByID(Record[i]))
1458 ArgTys.push_back(T);
1463 ResultTy = getTypeByID(Record[2]);
1464 if (!ResultTy || ArgTys.size() < Record.size()-3)
1465 return error("Invalid type");
1467 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1470 case bitc::TYPE_CODE_FUNCTION: {
1471 // FUNCTION: [vararg, retty, paramty x N]
1472 if (Record.size() < 2)
1473 return error("Invalid record");
1474 SmallVector<Type*, 8> ArgTys;
1475 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1476 if (Type *T = getTypeByID(Record[i])) {
1477 if (!FunctionType::isValidArgumentType(T))
1478 return error("Invalid function argument type");
1479 ArgTys.push_back(T);
1485 ResultTy = getTypeByID(Record[1]);
1486 if (!ResultTy || ArgTys.size() < Record.size()-2)
1487 return error("Invalid type");
1489 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1492 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1493 if (Record.size() < 1)
1494 return error("Invalid record");
1495 SmallVector<Type*, 8> EltTys;
1496 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1497 if (Type *T = getTypeByID(Record[i]))
1498 EltTys.push_back(T);
1502 if (EltTys.size() != Record.size()-1)
1503 return error("Invalid type");
1504 ResultTy = StructType::get(Context, EltTys, Record[0]);
1507 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1508 if (convertToString(Record, 0, TypeName))
1509 return error("Invalid record");
1512 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1513 if (Record.size() < 1)
1514 return error("Invalid record");
1516 if (NumRecords >= TypeList.size())
1517 return error("Invalid TYPE table");
1519 // Check to see if this was forward referenced, if so fill in the temp.
1520 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1522 Res->setName(TypeName);
1523 TypeList[NumRecords] = nullptr;
1524 } else // Otherwise, create a new struct.
1525 Res = createIdentifiedStructType(Context, TypeName);
1528 SmallVector<Type*, 8> EltTys;
1529 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1530 if (Type *T = getTypeByID(Record[i]))
1531 EltTys.push_back(T);
1535 if (EltTys.size() != Record.size()-1)
1536 return error("Invalid record");
1537 Res->setBody(EltTys, Record[0]);
1541 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1542 if (Record.size() != 1)
1543 return error("Invalid record");
1545 if (NumRecords >= TypeList.size())
1546 return error("Invalid TYPE table");
1548 // Check to see if this was forward referenced, if so fill in the temp.
1549 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1551 Res->setName(TypeName);
1552 TypeList[NumRecords] = nullptr;
1553 } else // Otherwise, create a new struct with no body.
1554 Res = createIdentifiedStructType(Context, TypeName);
1559 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1560 if (Record.size() < 2)
1561 return error("Invalid record");
1562 ResultTy = getTypeByID(Record[1]);
1563 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1564 return error("Invalid type");
1565 ResultTy = ArrayType::get(ResultTy, Record[0]);
1567 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1568 if (Record.size() < 2)
1569 return error("Invalid record");
1571 return error("Invalid vector length");
1572 ResultTy = getTypeByID(Record[1]);
1573 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1574 return error("Invalid type");
1575 ResultTy = VectorType::get(ResultTy, Record[0]);
1579 if (NumRecords >= TypeList.size())
1580 return error("Invalid TYPE table");
1581 if (TypeList[NumRecords])
1583 "Invalid TYPE table: Only named structs can be forward referenced");
1584 assert(ResultTy && "Didn't read a type?");
1585 TypeList[NumRecords++] = ResultTy;
1589 /// Associate a value with its name from the given index in the provided record.
1590 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1591 unsigned NameIndex, Triple &TT) {
1592 SmallString<128> ValueName;
1593 if (convertToString(Record, NameIndex, ValueName))
1594 return error("Invalid record");
1595 unsigned ValueID = Record[0];
1596 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1597 return error("Invalid record");
1598 Value *V = ValueList[ValueID];
1600 V->setName(StringRef(ValueName.data(), ValueName.size()));
1601 auto *GO = dyn_cast<GlobalObject>(V);
1603 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1604 if (TT.isOSBinFormatMachO())
1605 GO->setComdat(nullptr);
1607 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1613 /// Parse the value symbol table at either the current parsing location or
1614 /// at the given bit offset if provided.
1615 std::error_code BitcodeReader::parseValueSymbolTable(unsigned Offset) {
1616 uint64_t CurrentBit;
1617 // Pass in the Offset to distinguish between calling for the module-level
1618 // VST (where we want to jump to the VST offset) and the function-level
1619 // VST (where we don't).
1621 // Save the current parsing location so we can jump back at the end
1623 CurrentBit = Stream.GetCurrentBitNo();
1624 Stream.JumpToBit(Offset * 32);
1626 // Do some checking if we are in debug mode.
1627 BitstreamEntry Entry = Stream.advance();
1628 assert(Entry.Kind == BitstreamEntry::SubBlock);
1629 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1631 // In NDEBUG mode ignore the output so we don't get an unused variable
1637 // Compute the delta between the bitcode indices in the VST (the word offset
1638 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1639 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1640 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1641 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1642 // just before entering the VST subblock because: 1) the EnterSubBlock
1643 // changes the AbbrevID width; 2) the VST block is nested within the same
1644 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1645 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1646 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1647 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1648 unsigned FuncBitcodeOffsetDelta =
1649 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1651 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1652 return error("Invalid record");
1654 SmallVector<uint64_t, 64> Record;
1656 Triple TT(TheModule->getTargetTriple());
1658 // Read all the records for this value table.
1659 SmallString<128> ValueName;
1661 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1663 switch (Entry.Kind) {
1664 case BitstreamEntry::SubBlock: // Handled for us already.
1665 case BitstreamEntry::Error:
1666 return error("Malformed block");
1667 case BitstreamEntry::EndBlock:
1669 Stream.JumpToBit(CurrentBit);
1670 return std::error_code();
1671 case BitstreamEntry::Record:
1672 // The interesting case.
1678 switch (Stream.readRecord(Entry.ID, Record)) {
1679 default: // Default behavior: unknown type.
1681 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1682 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1683 if (std::error_code EC = ValOrErr.getError())
1688 case bitc::VST_CODE_FNENTRY: {
1689 // VST_FNENTRY: [valueid, offset, namechar x N]
1690 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1691 if (std::error_code EC = ValOrErr.getError())
1693 Value *V = ValOrErr.get();
1695 auto *GO = dyn_cast<GlobalObject>(V);
1697 // If this is an alias, need to get the actual Function object
1698 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1699 auto *GA = dyn_cast<GlobalAlias>(V);
1701 GO = GA->getBaseObject();
1705 uint64_t FuncWordOffset = Record[1];
1706 Function *F = dyn_cast<Function>(GO);
1708 uint64_t FuncBitOffset = FuncWordOffset * 32;
1709 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1710 // Set the NextUnreadBit to point to the last function block.
1711 // Later when parsing is resumed after function materialization,
1712 // we can simply skip that last function block.
1713 if (FuncBitOffset > NextUnreadBit)
1714 NextUnreadBit = FuncBitOffset;
1717 case bitc::VST_CODE_BBENTRY: {
1718 if (convertToString(Record, 1, ValueName))
1719 return error("Invalid record");
1720 BasicBlock *BB = getBasicBlock(Record[0]);
1722 return error("Invalid record");
1724 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1732 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1734 std::error_code BitcodeReader::parseMetadata() {
1735 IsMetadataMaterialized = true;
1736 unsigned NextMDValueNo = MDValueList.size();
1738 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1739 return error("Invalid record");
1741 SmallVector<uint64_t, 64> Record;
1744 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1745 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1747 return getMD(ID - 1);
1750 auto getMDString = [&](unsigned ID) -> MDString *{
1751 // This requires that the ID is not really a forward reference. In
1752 // particular, the MDString must already have been resolved.
1753 return cast_or_null<MDString>(getMDOrNull(ID));
1756 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1757 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1759 // Read all the records.
1761 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1763 switch (Entry.Kind) {
1764 case BitstreamEntry::SubBlock: // Handled for us already.
1765 case BitstreamEntry::Error:
1766 return error("Malformed block");
1767 case BitstreamEntry::EndBlock:
1768 MDValueList.tryToResolveCycles();
1769 return std::error_code();
1770 case BitstreamEntry::Record:
1771 // The interesting case.
1777 unsigned Code = Stream.readRecord(Entry.ID, Record);
1778 bool IsDistinct = false;
1780 default: // Default behavior: ignore.
1782 case bitc::METADATA_NAME: {
1783 // Read name of the named metadata.
1784 SmallString<8> Name(Record.begin(), Record.end());
1786 Code = Stream.ReadCode();
1788 unsigned NextBitCode = Stream.readRecord(Code, Record);
1789 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1790 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1792 // Read named metadata elements.
1793 unsigned Size = Record.size();
1794 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1795 for (unsigned i = 0; i != Size; ++i) {
1796 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1798 return error("Invalid record");
1799 NMD->addOperand(MD);
1803 case bitc::METADATA_OLD_FN_NODE: {
1804 // FIXME: Remove in 4.0.
1805 // This is a LocalAsMetadata record, the only type of function-local
1807 if (Record.size() % 2 == 1)
1808 return error("Invalid record");
1810 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1811 // to be legal, but there's no upgrade path.
1812 auto dropRecord = [&] {
1813 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1815 if (Record.size() != 2) {
1820 Type *Ty = getTypeByID(Record[0]);
1821 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1826 MDValueList.assignValue(
1827 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1831 case bitc::METADATA_OLD_NODE: {
1832 // FIXME: Remove in 4.0.
1833 if (Record.size() % 2 == 1)
1834 return error("Invalid record");
1836 unsigned Size = Record.size();
1837 SmallVector<Metadata *, 8> Elts;
1838 for (unsigned i = 0; i != Size; i += 2) {
1839 Type *Ty = getTypeByID(Record[i]);
1841 return error("Invalid record");
1842 if (Ty->isMetadataTy())
1843 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1844 else if (!Ty->isVoidTy()) {
1846 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1847 assert(isa<ConstantAsMetadata>(MD) &&
1848 "Expected non-function-local metadata");
1851 Elts.push_back(nullptr);
1853 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1856 case bitc::METADATA_VALUE: {
1857 if (Record.size() != 2)
1858 return error("Invalid record");
1860 Type *Ty = getTypeByID(Record[0]);
1861 if (Ty->isMetadataTy() || Ty->isVoidTy())
1862 return error("Invalid record");
1864 MDValueList.assignValue(
1865 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1869 case bitc::METADATA_DISTINCT_NODE:
1872 case bitc::METADATA_NODE: {
1873 SmallVector<Metadata *, 8> Elts;
1874 Elts.reserve(Record.size());
1875 for (unsigned ID : Record)
1876 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1877 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1878 : MDNode::get(Context, Elts),
1882 case bitc::METADATA_LOCATION: {
1883 if (Record.size() != 5)
1884 return error("Invalid record");
1886 unsigned Line = Record[1];
1887 unsigned Column = Record[2];
1888 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1889 Metadata *InlinedAt =
1890 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1891 MDValueList.assignValue(
1892 GET_OR_DISTINCT(DILocation, Record[0],
1893 (Context, Line, Column, Scope, InlinedAt)),
1897 case bitc::METADATA_GENERIC_DEBUG: {
1898 if (Record.size() < 4)
1899 return error("Invalid record");
1901 unsigned Tag = Record[1];
1902 unsigned Version = Record[2];
1904 if (Tag >= 1u << 16 || Version != 0)
1905 return error("Invalid record");
1907 auto *Header = getMDString(Record[3]);
1908 SmallVector<Metadata *, 8> DwarfOps;
1909 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1910 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1912 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1913 (Context, Tag, Header, DwarfOps)),
1917 case bitc::METADATA_SUBRANGE: {
1918 if (Record.size() != 3)
1919 return error("Invalid record");
1921 MDValueList.assignValue(
1922 GET_OR_DISTINCT(DISubrange, Record[0],
1923 (Context, Record[1], unrotateSign(Record[2]))),
1927 case bitc::METADATA_ENUMERATOR: {
1928 if (Record.size() != 3)
1929 return error("Invalid record");
1931 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1932 (Context, unrotateSign(Record[1]),
1933 getMDString(Record[2]))),
1937 case bitc::METADATA_BASIC_TYPE: {
1938 if (Record.size() != 6)
1939 return error("Invalid record");
1941 MDValueList.assignValue(
1942 GET_OR_DISTINCT(DIBasicType, Record[0],
1943 (Context, Record[1], getMDString(Record[2]),
1944 Record[3], Record[4], Record[5])),
1948 case bitc::METADATA_DERIVED_TYPE: {
1949 if (Record.size() != 12)
1950 return error("Invalid record");
1952 MDValueList.assignValue(
1953 GET_OR_DISTINCT(DIDerivedType, Record[0],
1954 (Context, Record[1], getMDString(Record[2]),
1955 getMDOrNull(Record[3]), Record[4],
1956 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1957 Record[7], Record[8], Record[9], Record[10],
1958 getMDOrNull(Record[11]))),
1962 case bitc::METADATA_COMPOSITE_TYPE: {
1963 if (Record.size() != 16)
1964 return error("Invalid record");
1966 MDValueList.assignValue(
1967 GET_OR_DISTINCT(DICompositeType, Record[0],
1968 (Context, Record[1], getMDString(Record[2]),
1969 getMDOrNull(Record[3]), Record[4],
1970 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1971 Record[7], Record[8], Record[9], Record[10],
1972 getMDOrNull(Record[11]), Record[12],
1973 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1974 getMDString(Record[15]))),
1978 case bitc::METADATA_SUBROUTINE_TYPE: {
1979 if (Record.size() != 3)
1980 return error("Invalid record");
1982 MDValueList.assignValue(
1983 GET_OR_DISTINCT(DISubroutineType, Record[0],
1984 (Context, Record[1], getMDOrNull(Record[2]))),
1989 case bitc::METADATA_MODULE: {
1990 if (Record.size() != 6)
1991 return error("Invalid record");
1993 MDValueList.assignValue(
1994 GET_OR_DISTINCT(DIModule, Record[0],
1995 (Context, getMDOrNull(Record[1]),
1996 getMDString(Record[2]), getMDString(Record[3]),
1997 getMDString(Record[4]), getMDString(Record[5]))),
2002 case bitc::METADATA_FILE: {
2003 if (Record.size() != 3)
2004 return error("Invalid record");
2006 MDValueList.assignValue(
2007 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2008 getMDString(Record[2]))),
2012 case bitc::METADATA_COMPILE_UNIT: {
2013 if (Record.size() < 14 || Record.size() > 15)
2014 return error("Invalid record");
2016 // Ignore Record[1], which indicates whether this compile unit is
2017 // distinct. It's always distinct.
2018 MDValueList.assignValue(
2019 DICompileUnit::getDistinct(
2020 Context, Record[1], getMDOrNull(Record[2]),
2021 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2022 Record[6], getMDString(Record[7]), Record[8],
2023 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2024 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2025 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2029 case bitc::METADATA_SUBPROGRAM: {
2030 if (Record.size() != 19)
2031 return error("Invalid record");
2033 MDValueList.assignValue(
2036 Record[0] || Record[8], // All definitions should be distinct.
2037 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2038 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2039 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2040 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2041 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
2042 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
2046 case bitc::METADATA_LEXICAL_BLOCK: {
2047 if (Record.size() != 5)
2048 return error("Invalid record");
2050 MDValueList.assignValue(
2051 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2052 (Context, getMDOrNull(Record[1]),
2053 getMDOrNull(Record[2]), Record[3], Record[4])),
2057 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2058 if (Record.size() != 4)
2059 return error("Invalid record");
2061 MDValueList.assignValue(
2062 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2063 (Context, getMDOrNull(Record[1]),
2064 getMDOrNull(Record[2]), Record[3])),
2068 case bitc::METADATA_NAMESPACE: {
2069 if (Record.size() != 5)
2070 return error("Invalid record");
2072 MDValueList.assignValue(
2073 GET_OR_DISTINCT(DINamespace, Record[0],
2074 (Context, getMDOrNull(Record[1]),
2075 getMDOrNull(Record[2]), getMDString(Record[3]),
2080 case bitc::METADATA_TEMPLATE_TYPE: {
2081 if (Record.size() != 3)
2082 return error("Invalid record");
2084 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2086 (Context, getMDString(Record[1]),
2087 getMDOrNull(Record[2]))),
2091 case bitc::METADATA_TEMPLATE_VALUE: {
2092 if (Record.size() != 5)
2093 return error("Invalid record");
2095 MDValueList.assignValue(
2096 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2097 (Context, Record[1], getMDString(Record[2]),
2098 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2102 case bitc::METADATA_GLOBAL_VAR: {
2103 if (Record.size() != 11)
2104 return error("Invalid record");
2106 MDValueList.assignValue(
2107 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2108 (Context, getMDOrNull(Record[1]),
2109 getMDString(Record[2]), getMDString(Record[3]),
2110 getMDOrNull(Record[4]), Record[5],
2111 getMDOrNull(Record[6]), Record[7], Record[8],
2112 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2116 case bitc::METADATA_LOCAL_VAR: {
2117 // 10th field is for the obseleted 'inlinedAt:' field.
2118 if (Record.size() < 8 || Record.size() > 10)
2119 return error("Invalid record");
2121 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2122 // DW_TAG_arg_variable.
2123 bool HasTag = Record.size() > 8;
2124 MDValueList.assignValue(
2125 GET_OR_DISTINCT(DILocalVariable, Record[0],
2126 (Context, getMDOrNull(Record[1 + HasTag]),
2127 getMDString(Record[2 + HasTag]),
2128 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2129 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2130 Record[7 + HasTag])),
2134 case bitc::METADATA_EXPRESSION: {
2135 if (Record.size() < 1)
2136 return error("Invalid record");
2138 MDValueList.assignValue(
2139 GET_OR_DISTINCT(DIExpression, Record[0],
2140 (Context, makeArrayRef(Record).slice(1))),
2144 case bitc::METADATA_OBJC_PROPERTY: {
2145 if (Record.size() != 8)
2146 return error("Invalid record");
2148 MDValueList.assignValue(
2149 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2150 (Context, getMDString(Record[1]),
2151 getMDOrNull(Record[2]), Record[3],
2152 getMDString(Record[4]), getMDString(Record[5]),
2153 Record[6], getMDOrNull(Record[7]))),
2157 case bitc::METADATA_IMPORTED_ENTITY: {
2158 if (Record.size() != 6)
2159 return error("Invalid record");
2161 MDValueList.assignValue(
2162 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2163 (Context, Record[1], getMDOrNull(Record[2]),
2164 getMDOrNull(Record[3]), Record[4],
2165 getMDString(Record[5]))),
2169 case bitc::METADATA_STRING: {
2170 std::string String(Record.begin(), Record.end());
2171 llvm::UpgradeMDStringConstant(String);
2172 Metadata *MD = MDString::get(Context, String);
2173 MDValueList.assignValue(MD, NextMDValueNo++);
2176 case bitc::METADATA_KIND: {
2177 if (Record.size() < 2)
2178 return error("Invalid record");
2180 unsigned Kind = Record[0];
2181 SmallString<8> Name(Record.begin()+1, Record.end());
2183 unsigned NewKind = TheModule->getMDKindID(Name.str());
2184 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2185 return error("Conflicting METADATA_KIND records");
2190 #undef GET_OR_DISTINCT
2193 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2195 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2200 // There is no such thing as -0 with integers. "-0" really means MININT.
2204 /// Resolve all of the initializers for global values and aliases that we can.
2205 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2206 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2207 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2208 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2209 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2210 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2212 GlobalInitWorklist.swap(GlobalInits);
2213 AliasInitWorklist.swap(AliasInits);
2214 FunctionPrefixWorklist.swap(FunctionPrefixes);
2215 FunctionPrologueWorklist.swap(FunctionPrologues);
2216 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2218 while (!GlobalInitWorklist.empty()) {
2219 unsigned ValID = GlobalInitWorklist.back().second;
2220 if (ValID >= ValueList.size()) {
2221 // Not ready to resolve this yet, it requires something later in the file.
2222 GlobalInits.push_back(GlobalInitWorklist.back());
2224 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2225 GlobalInitWorklist.back().first->setInitializer(C);
2227 return error("Expected a constant");
2229 GlobalInitWorklist.pop_back();
2232 while (!AliasInitWorklist.empty()) {
2233 unsigned ValID = AliasInitWorklist.back().second;
2234 if (ValID >= ValueList.size()) {
2235 AliasInits.push_back(AliasInitWorklist.back());
2237 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2239 return error("Expected a constant");
2240 GlobalAlias *Alias = AliasInitWorklist.back().first;
2241 if (C->getType() != Alias->getType())
2242 return error("Alias and aliasee types don't match");
2243 Alias->setAliasee(C);
2245 AliasInitWorklist.pop_back();
2248 while (!FunctionPrefixWorklist.empty()) {
2249 unsigned ValID = FunctionPrefixWorklist.back().second;
2250 if (ValID >= ValueList.size()) {
2251 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2253 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2254 FunctionPrefixWorklist.back().first->setPrefixData(C);
2256 return error("Expected a constant");
2258 FunctionPrefixWorklist.pop_back();
2261 while (!FunctionPrologueWorklist.empty()) {
2262 unsigned ValID = FunctionPrologueWorklist.back().second;
2263 if (ValID >= ValueList.size()) {
2264 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2266 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2267 FunctionPrologueWorklist.back().first->setPrologueData(C);
2269 return error("Expected a constant");
2271 FunctionPrologueWorklist.pop_back();
2274 while (!FunctionPersonalityFnWorklist.empty()) {
2275 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2276 if (ValID >= ValueList.size()) {
2277 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2279 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2280 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2282 return error("Expected a constant");
2284 FunctionPersonalityFnWorklist.pop_back();
2287 return std::error_code();
2290 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2291 SmallVector<uint64_t, 8> Words(Vals.size());
2292 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2293 BitcodeReader::decodeSignRotatedValue);
2295 return APInt(TypeBits, Words);
2298 std::error_code BitcodeReader::parseConstants() {
2299 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2300 return error("Invalid record");
2302 SmallVector<uint64_t, 64> Record;
2304 // Read all the records for this value table.
2305 Type *CurTy = Type::getInt32Ty(Context);
2306 unsigned NextCstNo = ValueList.size();
2308 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2310 switch (Entry.Kind) {
2311 case BitstreamEntry::SubBlock: // Handled for us already.
2312 case BitstreamEntry::Error:
2313 return error("Malformed block");
2314 case BitstreamEntry::EndBlock:
2315 if (NextCstNo != ValueList.size())
2316 return error("Invalid ronstant reference");
2318 // Once all the constants have been read, go through and resolve forward
2320 ValueList.resolveConstantForwardRefs();
2321 return std::error_code();
2322 case BitstreamEntry::Record:
2323 // The interesting case.
2330 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2332 default: // Default behavior: unknown constant
2333 case bitc::CST_CODE_UNDEF: // UNDEF
2334 V = UndefValue::get(CurTy);
2336 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2338 return error("Invalid record");
2339 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2340 return error("Invalid record");
2341 CurTy = TypeList[Record[0]];
2342 continue; // Skip the ValueList manipulation.
2343 case bitc::CST_CODE_NULL: // NULL
2344 V = Constant::getNullValue(CurTy);
2346 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2347 if (!CurTy->isIntegerTy() || Record.empty())
2348 return error("Invalid record");
2349 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2351 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2352 if (!CurTy->isIntegerTy() || Record.empty())
2353 return error("Invalid record");
2356 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2357 V = ConstantInt::get(Context, VInt);
2361 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2363 return error("Invalid record");
2364 if (CurTy->isHalfTy())
2365 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2366 APInt(16, (uint16_t)Record[0])));
2367 else if (CurTy->isFloatTy())
2368 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2369 APInt(32, (uint32_t)Record[0])));
2370 else if (CurTy->isDoubleTy())
2371 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2372 APInt(64, Record[0])));
2373 else if (CurTy->isX86_FP80Ty()) {
2374 // Bits are not stored the same way as a normal i80 APInt, compensate.
2375 uint64_t Rearrange[2];
2376 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2377 Rearrange[1] = Record[0] >> 48;
2378 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2379 APInt(80, Rearrange)));
2380 } else if (CurTy->isFP128Ty())
2381 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2382 APInt(128, Record)));
2383 else if (CurTy->isPPC_FP128Ty())
2384 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2385 APInt(128, Record)));
2387 V = UndefValue::get(CurTy);
2391 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2393 return error("Invalid record");
2395 unsigned Size = Record.size();
2396 SmallVector<Constant*, 16> Elts;
2398 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2399 for (unsigned i = 0; i != Size; ++i)
2400 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2401 STy->getElementType(i)));
2402 V = ConstantStruct::get(STy, Elts);
2403 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2404 Type *EltTy = ATy->getElementType();
2405 for (unsigned i = 0; i != Size; ++i)
2406 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2407 V = ConstantArray::get(ATy, Elts);
2408 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2409 Type *EltTy = VTy->getElementType();
2410 for (unsigned i = 0; i != Size; ++i)
2411 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2412 V = ConstantVector::get(Elts);
2414 V = UndefValue::get(CurTy);
2418 case bitc::CST_CODE_STRING: // STRING: [values]
2419 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2421 return error("Invalid record");
2423 SmallString<16> Elts(Record.begin(), Record.end());
2424 V = ConstantDataArray::getString(Context, Elts,
2425 BitCode == bitc::CST_CODE_CSTRING);
2428 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2430 return error("Invalid record");
2432 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2433 unsigned Size = Record.size();
2435 if (EltTy->isIntegerTy(8)) {
2436 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2437 if (isa<VectorType>(CurTy))
2438 V = ConstantDataVector::get(Context, Elts);
2440 V = ConstantDataArray::get(Context, Elts);
2441 } else if (EltTy->isIntegerTy(16)) {
2442 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2443 if (isa<VectorType>(CurTy))
2444 V = ConstantDataVector::get(Context, Elts);
2446 V = ConstantDataArray::get(Context, Elts);
2447 } else if (EltTy->isIntegerTy(32)) {
2448 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2449 if (isa<VectorType>(CurTy))
2450 V = ConstantDataVector::get(Context, Elts);
2452 V = ConstantDataArray::get(Context, Elts);
2453 } else if (EltTy->isIntegerTy(64)) {
2454 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2455 if (isa<VectorType>(CurTy))
2456 V = ConstantDataVector::get(Context, Elts);
2458 V = ConstantDataArray::get(Context, Elts);
2459 } else if (EltTy->isFloatTy()) {
2460 SmallVector<float, 16> Elts(Size);
2461 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2462 if (isa<VectorType>(CurTy))
2463 V = ConstantDataVector::get(Context, Elts);
2465 V = ConstantDataArray::get(Context, Elts);
2466 } else if (EltTy->isDoubleTy()) {
2467 SmallVector<double, 16> Elts(Size);
2468 std::transform(Record.begin(), Record.end(), Elts.begin(),
2470 if (isa<VectorType>(CurTy))
2471 V = ConstantDataVector::get(Context, Elts);
2473 V = ConstantDataArray::get(Context, Elts);
2475 return error("Invalid type for value");
2480 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2481 if (Record.size() < 3)
2482 return error("Invalid record");
2483 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2485 V = UndefValue::get(CurTy); // Unknown binop.
2487 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2488 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2490 if (Record.size() >= 4) {
2491 if (Opc == Instruction::Add ||
2492 Opc == Instruction::Sub ||
2493 Opc == Instruction::Mul ||
2494 Opc == Instruction::Shl) {
2495 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2496 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2497 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2498 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2499 } else if (Opc == Instruction::SDiv ||
2500 Opc == Instruction::UDiv ||
2501 Opc == Instruction::LShr ||
2502 Opc == Instruction::AShr) {
2503 if (Record[3] & (1 << bitc::PEO_EXACT))
2504 Flags |= SDivOperator::IsExact;
2507 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2511 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2512 if (Record.size() < 3)
2513 return error("Invalid record");
2514 int Opc = getDecodedCastOpcode(Record[0]);
2516 V = UndefValue::get(CurTy); // Unknown cast.
2518 Type *OpTy = getTypeByID(Record[1]);
2520 return error("Invalid record");
2521 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2522 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2523 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2527 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2528 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2530 Type *PointeeType = nullptr;
2531 if (Record.size() % 2)
2532 PointeeType = getTypeByID(Record[OpNum++]);
2533 SmallVector<Constant*, 16> Elts;
2534 while (OpNum != Record.size()) {
2535 Type *ElTy = getTypeByID(Record[OpNum++]);
2537 return error("Invalid record");
2538 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2543 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2545 return error("Explicit gep operator type does not match pointee type "
2546 "of pointer operand");
2548 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2549 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2551 bitc::CST_CODE_CE_INBOUNDS_GEP);
2554 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2555 if (Record.size() < 3)
2556 return error("Invalid record");
2558 Type *SelectorTy = Type::getInt1Ty(Context);
2560 // The selector might be an i1 or an <n x i1>
2561 // Get the type from the ValueList before getting a forward ref.
2562 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2563 if (Value *V = ValueList[Record[0]])
2564 if (SelectorTy != V->getType())
2565 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2567 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2569 ValueList.getConstantFwdRef(Record[1],CurTy),
2570 ValueList.getConstantFwdRef(Record[2],CurTy));
2573 case bitc::CST_CODE_CE_EXTRACTELT
2574 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2575 if (Record.size() < 3)
2576 return error("Invalid record");
2578 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2580 return error("Invalid record");
2581 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2582 Constant *Op1 = nullptr;
2583 if (Record.size() == 4) {
2584 Type *IdxTy = getTypeByID(Record[2]);
2586 return error("Invalid record");
2587 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2588 } else // TODO: Remove with llvm 4.0
2589 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2591 return error("Invalid record");
2592 V = ConstantExpr::getExtractElement(Op0, Op1);
2595 case bitc::CST_CODE_CE_INSERTELT
2596 : { // CE_INSERTELT: [opval, opval, opty, opval]
2597 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2598 if (Record.size() < 3 || !OpTy)
2599 return error("Invalid record");
2600 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2601 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2602 OpTy->getElementType());
2603 Constant *Op2 = nullptr;
2604 if (Record.size() == 4) {
2605 Type *IdxTy = getTypeByID(Record[2]);
2607 return error("Invalid record");
2608 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2609 } else // TODO: Remove with llvm 4.0
2610 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2612 return error("Invalid record");
2613 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2616 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2617 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2618 if (Record.size() < 3 || !OpTy)
2619 return error("Invalid record");
2620 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2621 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2622 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2623 OpTy->getNumElements());
2624 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2625 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2628 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2629 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2631 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2632 if (Record.size() < 4 || !RTy || !OpTy)
2633 return error("Invalid record");
2634 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2635 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2636 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2637 RTy->getNumElements());
2638 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2639 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2642 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2643 if (Record.size() < 4)
2644 return error("Invalid record");
2645 Type *OpTy = getTypeByID(Record[0]);
2647 return error("Invalid record");
2648 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2649 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2651 if (OpTy->isFPOrFPVectorTy())
2652 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2654 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2657 // This maintains backward compatibility, pre-asm dialect keywords.
2658 // FIXME: Remove with the 4.0 release.
2659 case bitc::CST_CODE_INLINEASM_OLD: {
2660 if (Record.size() < 2)
2661 return error("Invalid record");
2662 std::string AsmStr, ConstrStr;
2663 bool HasSideEffects = Record[0] & 1;
2664 bool IsAlignStack = Record[0] >> 1;
2665 unsigned AsmStrSize = Record[1];
2666 if (2+AsmStrSize >= Record.size())
2667 return error("Invalid record");
2668 unsigned ConstStrSize = Record[2+AsmStrSize];
2669 if (3+AsmStrSize+ConstStrSize > Record.size())
2670 return error("Invalid record");
2672 for (unsigned i = 0; i != AsmStrSize; ++i)
2673 AsmStr += (char)Record[2+i];
2674 for (unsigned i = 0; i != ConstStrSize; ++i)
2675 ConstrStr += (char)Record[3+AsmStrSize+i];
2676 PointerType *PTy = cast<PointerType>(CurTy);
2677 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2678 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2681 // This version adds support for the asm dialect keywords (e.g.,
2683 case bitc::CST_CODE_INLINEASM: {
2684 if (Record.size() < 2)
2685 return error("Invalid record");
2686 std::string AsmStr, ConstrStr;
2687 bool HasSideEffects = Record[0] & 1;
2688 bool IsAlignStack = (Record[0] >> 1) & 1;
2689 unsigned AsmDialect = Record[0] >> 2;
2690 unsigned AsmStrSize = Record[1];
2691 if (2+AsmStrSize >= Record.size())
2692 return error("Invalid record");
2693 unsigned ConstStrSize = Record[2+AsmStrSize];
2694 if (3+AsmStrSize+ConstStrSize > Record.size())
2695 return error("Invalid record");
2697 for (unsigned i = 0; i != AsmStrSize; ++i)
2698 AsmStr += (char)Record[2+i];
2699 for (unsigned i = 0; i != ConstStrSize; ++i)
2700 ConstrStr += (char)Record[3+AsmStrSize+i];
2701 PointerType *PTy = cast<PointerType>(CurTy);
2702 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2703 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2704 InlineAsm::AsmDialect(AsmDialect));
2707 case bitc::CST_CODE_BLOCKADDRESS:{
2708 if (Record.size() < 3)
2709 return error("Invalid record");
2710 Type *FnTy = getTypeByID(Record[0]);
2712 return error("Invalid record");
2714 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2716 return error("Invalid record");
2718 // Don't let Fn get dematerialized.
2719 BlockAddressesTaken.insert(Fn);
2721 // If the function is already parsed we can insert the block address right
2724 unsigned BBID = Record[2];
2726 // Invalid reference to entry block.
2727 return error("Invalid ID");
2729 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2730 for (size_t I = 0, E = BBID; I != E; ++I) {
2732 return error("Invalid ID");
2737 // Otherwise insert a placeholder and remember it so it can be inserted
2738 // when the function is parsed.
2739 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2741 BasicBlockFwdRefQueue.push_back(Fn);
2742 if (FwdBBs.size() < BBID + 1)
2743 FwdBBs.resize(BBID + 1);
2745 FwdBBs[BBID] = BasicBlock::Create(Context);
2748 V = BlockAddress::get(Fn, BB);
2753 if (ValueList.assignValue(V, NextCstNo))
2754 return error("Invalid forward reference");
2759 std::error_code BitcodeReader::parseUseLists() {
2760 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2761 return error("Invalid record");
2763 // Read all the records.
2764 SmallVector<uint64_t, 64> Record;
2766 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2768 switch (Entry.Kind) {
2769 case BitstreamEntry::SubBlock: // Handled for us already.
2770 case BitstreamEntry::Error:
2771 return error("Malformed block");
2772 case BitstreamEntry::EndBlock:
2773 return std::error_code();
2774 case BitstreamEntry::Record:
2775 // The interesting case.
2779 // Read a use list record.
2782 switch (Stream.readRecord(Entry.ID, Record)) {
2783 default: // Default behavior: unknown type.
2785 case bitc::USELIST_CODE_BB:
2788 case bitc::USELIST_CODE_DEFAULT: {
2789 unsigned RecordLength = Record.size();
2790 if (RecordLength < 3)
2791 // Records should have at least an ID and two indexes.
2792 return error("Invalid record");
2793 unsigned ID = Record.back();
2798 assert(ID < FunctionBBs.size() && "Basic block not found");
2799 V = FunctionBBs[ID];
2802 unsigned NumUses = 0;
2803 SmallDenseMap<const Use *, unsigned, 16> Order;
2804 for (const Use &U : V->uses()) {
2805 if (++NumUses > Record.size())
2807 Order[&U] = Record[NumUses - 1];
2809 if (Order.size() != Record.size() || NumUses > Record.size())
2810 // Mismatches can happen if the functions are being materialized lazily
2811 // (out-of-order), or a value has been upgraded.
2814 V->sortUseList([&](const Use &L, const Use &R) {
2815 return Order.lookup(&L) < Order.lookup(&R);
2823 /// When we see the block for metadata, remember where it is and then skip it.
2824 /// This lets us lazily deserialize the metadata.
2825 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2826 // Save the current stream state.
2827 uint64_t CurBit = Stream.GetCurrentBitNo();
2828 DeferredMetadataInfo.push_back(CurBit);
2830 // Skip over the block for now.
2831 if (Stream.SkipBlock())
2832 return error("Invalid record");
2833 return std::error_code();
2836 std::error_code BitcodeReader::materializeMetadata() {
2837 for (uint64_t BitPos : DeferredMetadataInfo) {
2838 // Move the bit stream to the saved position.
2839 Stream.JumpToBit(BitPos);
2840 if (std::error_code EC = parseMetadata())
2843 DeferredMetadataInfo.clear();
2844 return std::error_code();
2847 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2849 /// When we see the block for a function body, remember where it is and then
2850 /// skip it. This lets us lazily deserialize the functions.
2851 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2852 // Get the function we are talking about.
2853 if (FunctionsWithBodies.empty())
2854 return error("Insufficient function protos");
2856 Function *Fn = FunctionsWithBodies.back();
2857 FunctionsWithBodies.pop_back();
2859 // Save the current stream state.
2860 uint64_t CurBit = Stream.GetCurrentBitNo();
2861 DeferredFunctionInfo[Fn] = CurBit;
2863 // Skip over the function block for now.
2864 if (Stream.SkipBlock())
2865 return error("Invalid record");
2866 return std::error_code();
2869 std::error_code BitcodeReader::globalCleanup() {
2870 // Patch the initializers for globals and aliases up.
2871 resolveGlobalAndAliasInits();
2872 if (!GlobalInits.empty() || !AliasInits.empty())
2873 return error("Malformed global initializer set");
2875 // Look for intrinsic functions which need to be upgraded at some point
2876 for (Function &F : *TheModule) {
2878 if (UpgradeIntrinsicFunction(&F, NewFn))
2879 UpgradedIntrinsics[&F] = NewFn;
2882 // Look for global variables which need to be renamed.
2883 for (GlobalVariable &GV : TheModule->globals())
2884 UpgradeGlobalVariable(&GV);
2886 // Force deallocation of memory for these vectors to favor the client that
2887 // want lazy deserialization.
2888 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2889 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2890 return std::error_code();
2893 std::error_code BitcodeReader::parseModule(bool Resume,
2894 bool ShouldLazyLoadMetadata) {
2896 Stream.JumpToBit(NextUnreadBit);
2897 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2898 return error("Invalid record");
2900 SmallVector<uint64_t, 64> Record;
2901 std::vector<std::string> SectionTable;
2902 std::vector<std::string> GCTable;
2904 // Read all the records for this module.
2906 BitstreamEntry Entry = Stream.advance();
2908 switch (Entry.Kind) {
2909 case BitstreamEntry::Error:
2910 return error("Malformed block");
2911 case BitstreamEntry::EndBlock:
2912 return globalCleanup();
2914 case BitstreamEntry::SubBlock:
2916 default: // Skip unknown content.
2917 if (Stream.SkipBlock())
2918 return error("Invalid record");
2920 case bitc::BLOCKINFO_BLOCK_ID:
2921 if (Stream.ReadBlockInfoBlock())
2922 return error("Malformed block");
2924 case bitc::PARAMATTR_BLOCK_ID:
2925 if (std::error_code EC = parseAttributeBlock())
2928 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2929 if (std::error_code EC = parseAttributeGroupBlock())
2932 case bitc::TYPE_BLOCK_ID_NEW:
2933 if (std::error_code EC = parseTypeTable())
2936 case bitc::VALUE_SYMTAB_BLOCK_ID:
2937 if (!SeenValueSymbolTable) {
2938 // Either this is an old form VST without function index and an
2939 // associated VST forward declaration record (which would have caused
2940 // the VST to be jumped to and parsed before it was encountered
2941 // normally in the stream), or there were no function blocks to
2942 // trigger an earlier parsing of the VST.
2943 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
2944 if (std::error_code EC = parseValueSymbolTable())
2946 SeenValueSymbolTable = true;
2948 // We must have had a VST forward declaration record, which caused
2949 // the parser to jump to and parse the VST earlier.
2950 assert(VSTOffset > 0);
2951 if (Stream.SkipBlock())
2952 return error("Invalid record");
2955 case bitc::CONSTANTS_BLOCK_ID:
2956 if (std::error_code EC = parseConstants())
2958 if (std::error_code EC = resolveGlobalAndAliasInits())
2961 case bitc::METADATA_BLOCK_ID:
2962 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2963 if (std::error_code EC = rememberAndSkipMetadata())
2967 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2968 if (std::error_code EC = parseMetadata())
2971 case bitc::FUNCTION_BLOCK_ID:
2972 // If this is the first function body we've seen, reverse the
2973 // FunctionsWithBodies list.
2974 if (!SeenFirstFunctionBody) {
2975 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2976 if (std::error_code EC = globalCleanup())
2978 SeenFirstFunctionBody = true;
2981 if (VSTOffset > 0) {
2982 // If we have a VST forward declaration record, make sure we
2983 // parse the VST now if we haven't already. It is needed to
2984 // set up the DeferredFunctionInfo vector for lazy reading.
2985 if (!SeenValueSymbolTable) {
2986 if (std::error_code EC =
2987 BitcodeReader::parseValueSymbolTable(VSTOffset))
2989 SeenValueSymbolTable = true;
2990 return std::error_code();
2992 // If we have a VST forward declaration record, but have already
2993 // parsed the VST (just above, when the first function body was
2994 // encountered here), then we are resuming the parse after
2995 // materializing functions. The NextUnreadBit points to the start
2996 // of the last function block recorded in the VST (set when
2997 // parsing the VST function entries). Skip it.
2998 if (Stream.SkipBlock())
2999 return error("Invalid record");
3004 // Support older bitcode files that did not have the function
3005 // index in the VST, nor a VST forward declaration record.
3006 // Build the DeferredFunctionInfo vector on the fly.
3007 if (std::error_code EC = rememberAndSkipFunctionBody())
3009 // Suspend parsing when we reach the function bodies. Subsequent
3010 // materialization calls will resume it when necessary. If the bitcode
3011 // file is old, the symbol table will be at the end instead and will not
3012 // have been seen yet. In this case, just finish the parse now.
3013 if (SeenValueSymbolTable) {
3014 NextUnreadBit = Stream.GetCurrentBitNo();
3015 return std::error_code();
3018 case bitc::USELIST_BLOCK_ID:
3019 if (std::error_code EC = parseUseLists())
3025 case BitstreamEntry::Record:
3026 // The interesting case.
3032 auto BitCode = Stream.readRecord(Entry.ID, Record);
3034 default: break; // Default behavior, ignore unknown content.
3035 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3036 if (Record.size() < 1)
3037 return error("Invalid record");
3038 // Only version #0 and #1 are supported so far.
3039 unsigned module_version = Record[0];
3040 switch (module_version) {
3042 return error("Invalid value");
3044 UseRelativeIDs = false;
3047 UseRelativeIDs = true;
3052 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3054 if (convertToString(Record, 0, S))
3055 return error("Invalid record");
3056 TheModule->setTargetTriple(S);
3059 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3061 if (convertToString(Record, 0, S))
3062 return error("Invalid record");
3063 TheModule->setDataLayout(S);
3066 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3068 if (convertToString(Record, 0, S))
3069 return error("Invalid record");
3070 TheModule->setModuleInlineAsm(S);
3073 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3074 // FIXME: Remove in 4.0.
3076 if (convertToString(Record, 0, S))
3077 return error("Invalid record");
3081 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3083 if (convertToString(Record, 0, S))
3084 return error("Invalid record");
3085 SectionTable.push_back(S);
3088 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3090 if (convertToString(Record, 0, S))
3091 return error("Invalid record");
3092 GCTable.push_back(S);
3095 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3096 if (Record.size() < 2)
3097 return error("Invalid record");
3098 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3099 unsigned ComdatNameSize = Record[1];
3100 std::string ComdatName;
3101 ComdatName.reserve(ComdatNameSize);
3102 for (unsigned i = 0; i != ComdatNameSize; ++i)
3103 ComdatName += (char)Record[2 + i];
3104 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3105 C->setSelectionKind(SK);
3106 ComdatList.push_back(C);
3109 // GLOBALVAR: [pointer type, isconst, initid,
3110 // linkage, alignment, section, visibility, threadlocal,
3111 // unnamed_addr, externally_initialized, dllstorageclass,
3113 case bitc::MODULE_CODE_GLOBALVAR: {
3114 if (Record.size() < 6)
3115 return error("Invalid record");
3116 Type *Ty = getTypeByID(Record[0]);
3118 return error("Invalid record");
3119 bool isConstant = Record[1] & 1;
3120 bool explicitType = Record[1] & 2;
3121 unsigned AddressSpace;
3123 AddressSpace = Record[1] >> 2;
3125 if (!Ty->isPointerTy())
3126 return error("Invalid type for value");
3127 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3128 Ty = cast<PointerType>(Ty)->getElementType();
3131 uint64_t RawLinkage = Record[3];
3132 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3134 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3136 std::string Section;
3138 if (Record[5]-1 >= SectionTable.size())
3139 return error("Invalid ID");
3140 Section = SectionTable[Record[5]-1];
3142 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3143 // Local linkage must have default visibility.
3144 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3145 // FIXME: Change to an error if non-default in 4.0.
3146 Visibility = getDecodedVisibility(Record[6]);
3148 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3149 if (Record.size() > 7)
3150 TLM = getDecodedThreadLocalMode(Record[7]);
3152 bool UnnamedAddr = false;
3153 if (Record.size() > 8)
3154 UnnamedAddr = Record[8];
3156 bool ExternallyInitialized = false;
3157 if (Record.size() > 9)
3158 ExternallyInitialized = Record[9];
3160 GlobalVariable *NewGV =
3161 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3162 TLM, AddressSpace, ExternallyInitialized);
3163 NewGV->setAlignment(Alignment);
3164 if (!Section.empty())
3165 NewGV->setSection(Section);
3166 NewGV->setVisibility(Visibility);
3167 NewGV->setUnnamedAddr(UnnamedAddr);
3169 if (Record.size() > 10)
3170 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3172 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3174 ValueList.push_back(NewGV);
3176 // Remember which value to use for the global initializer.
3177 if (unsigned InitID = Record[2])
3178 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3180 if (Record.size() > 11) {
3181 if (unsigned ComdatID = Record[11]) {
3182 if (ComdatID > ComdatList.size())
3183 return error("Invalid global variable comdat ID");
3184 NewGV->setComdat(ComdatList[ComdatID - 1]);
3186 } else if (hasImplicitComdat(RawLinkage)) {
3187 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3191 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3192 // alignment, section, visibility, gc, unnamed_addr,
3193 // prologuedata, dllstorageclass, comdat, prefixdata]
3194 case bitc::MODULE_CODE_FUNCTION: {
3195 if (Record.size() < 8)
3196 return error("Invalid record");
3197 Type *Ty = getTypeByID(Record[0]);
3199 return error("Invalid record");
3200 if (auto *PTy = dyn_cast<PointerType>(Ty))
3201 Ty = PTy->getElementType();
3202 auto *FTy = dyn_cast<FunctionType>(Ty);
3204 return error("Invalid type for value");
3206 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3209 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
3210 bool isProto = Record[2];
3211 uint64_t RawLinkage = Record[3];
3212 Func->setLinkage(getDecodedLinkage(RawLinkage));
3213 Func->setAttributes(getAttributes(Record[4]));
3216 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3218 Func->setAlignment(Alignment);
3220 if (Record[6]-1 >= SectionTable.size())
3221 return error("Invalid ID");
3222 Func->setSection(SectionTable[Record[6]-1]);
3224 // Local linkage must have default visibility.
3225 if (!Func->hasLocalLinkage())
3226 // FIXME: Change to an error if non-default in 4.0.
3227 Func->setVisibility(getDecodedVisibility(Record[7]));
3228 if (Record.size() > 8 && Record[8]) {
3229 if (Record[8]-1 >= GCTable.size())
3230 return error("Invalid ID");
3231 Func->setGC(GCTable[Record[8]-1].c_str());
3233 bool UnnamedAddr = false;
3234 if (Record.size() > 9)
3235 UnnamedAddr = Record[9];
3236 Func->setUnnamedAddr(UnnamedAddr);
3237 if (Record.size() > 10 && Record[10] != 0)
3238 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3240 if (Record.size() > 11)
3241 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3243 upgradeDLLImportExportLinkage(Func, RawLinkage);
3245 if (Record.size() > 12) {
3246 if (unsigned ComdatID = Record[12]) {
3247 if (ComdatID > ComdatList.size())
3248 return error("Invalid function comdat ID");
3249 Func->setComdat(ComdatList[ComdatID - 1]);
3251 } else if (hasImplicitComdat(RawLinkage)) {
3252 Func->setComdat(reinterpret_cast<Comdat *>(1));
3255 if (Record.size() > 13 && Record[13] != 0)
3256 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3258 if (Record.size() > 14 && Record[14] != 0)
3259 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3261 ValueList.push_back(Func);
3263 // If this is a function with a body, remember the prototype we are
3264 // creating now, so that we can match up the body with them later.
3266 Func->setIsMaterializable(true);
3267 FunctionsWithBodies.push_back(Func);
3268 DeferredFunctionInfo[Func] = 0;
3272 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3273 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3274 case bitc::MODULE_CODE_ALIAS:
3275 case bitc::MODULE_CODE_ALIAS_OLD: {
3276 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3277 if (Record.size() < (3 + NewRecord))
3278 return error("Invalid record");
3280 Type *Ty = getTypeByID(Record[OpNum++]);
3282 return error("Invalid record");
3286 auto *PTy = dyn_cast<PointerType>(Ty);
3288 return error("Invalid type for value");
3289 Ty = PTy->getElementType();
3290 AddrSpace = PTy->getAddressSpace();
3292 AddrSpace = Record[OpNum++];
3295 auto Val = Record[OpNum++];
3296 auto Linkage = Record[OpNum++];
3297 auto *NewGA = GlobalAlias::create(
3298 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3299 // Old bitcode files didn't have visibility field.
3300 // Local linkage must have default visibility.
3301 if (OpNum != Record.size()) {
3302 auto VisInd = OpNum++;
3303 if (!NewGA->hasLocalLinkage())
3304 // FIXME: Change to an error if non-default in 4.0.
3305 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3307 if (OpNum != Record.size())
3308 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3310 upgradeDLLImportExportLinkage(NewGA, Linkage);
3311 if (OpNum != Record.size())
3312 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3313 if (OpNum != Record.size())
3314 NewGA->setUnnamedAddr(Record[OpNum++]);
3315 ValueList.push_back(NewGA);
3316 AliasInits.push_back(std::make_pair(NewGA, Val));
3319 /// MODULE_CODE_PURGEVALS: [numvals]
3320 case bitc::MODULE_CODE_PURGEVALS:
3321 // Trim down the value list to the specified size.
3322 if (Record.size() < 1 || Record[0] > ValueList.size())
3323 return error("Invalid record");
3324 ValueList.shrinkTo(Record[0]);
3326 /// MODULE_CODE_VSTOFFSET: [offset]
3327 case bitc::MODULE_CODE_VSTOFFSET:
3328 if (Record.size() < 1)
3329 return error("Invalid record");
3330 VSTOffset = Record[0];
3338 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3339 Module *M, bool ShouldLazyLoadMetadata) {
3342 if (std::error_code EC = initStream(std::move(Streamer)))
3345 // Sniff for the signature.
3346 if (Stream.Read(8) != 'B' ||
3347 Stream.Read(8) != 'C' ||
3348 Stream.Read(4) != 0x0 ||
3349 Stream.Read(4) != 0xC ||
3350 Stream.Read(4) != 0xE ||
3351 Stream.Read(4) != 0xD)
3352 return error("Invalid bitcode signature");
3354 // We expect a number of well-defined blocks, though we don't necessarily
3355 // need to understand them all.
3357 if (Stream.AtEndOfStream()) {
3358 // We didn't really read a proper Module.
3359 return error("Malformed IR file");
3362 BitstreamEntry Entry =
3363 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3365 if (Entry.Kind != BitstreamEntry::SubBlock)
3366 return error("Malformed block");
3368 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3369 return parseModule(false, ShouldLazyLoadMetadata);
3371 if (Stream.SkipBlock())
3372 return error("Invalid record");
3376 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3377 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3378 return error("Invalid record");
3380 SmallVector<uint64_t, 64> Record;
3383 // Read all the records for this module.
3385 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3387 switch (Entry.Kind) {
3388 case BitstreamEntry::SubBlock: // Handled for us already.
3389 case BitstreamEntry::Error:
3390 return error("Malformed block");
3391 case BitstreamEntry::EndBlock:
3393 case BitstreamEntry::Record:
3394 // The interesting case.
3399 switch (Stream.readRecord(Entry.ID, Record)) {
3400 default: break; // Default behavior, ignore unknown content.
3401 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3403 if (convertToString(Record, 0, S))
3404 return error("Invalid record");
3411 llvm_unreachable("Exit infinite loop");
3414 ErrorOr<std::string> BitcodeReader::parseTriple() {
3415 if (std::error_code EC = initStream(nullptr))
3418 // Sniff for the signature.
3419 if (Stream.Read(8) != 'B' ||
3420 Stream.Read(8) != 'C' ||
3421 Stream.Read(4) != 0x0 ||
3422 Stream.Read(4) != 0xC ||
3423 Stream.Read(4) != 0xE ||
3424 Stream.Read(4) != 0xD)
3425 return error("Invalid bitcode signature");
3427 // We expect a number of well-defined blocks, though we don't necessarily
3428 // need to understand them all.
3430 BitstreamEntry Entry = Stream.advance();
3432 switch (Entry.Kind) {
3433 case BitstreamEntry::Error:
3434 return error("Malformed block");
3435 case BitstreamEntry::EndBlock:
3436 return std::error_code();
3438 case BitstreamEntry::SubBlock:
3439 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3440 return parseModuleTriple();
3442 // Ignore other sub-blocks.
3443 if (Stream.SkipBlock())
3444 return error("Malformed block");
3447 case BitstreamEntry::Record:
3448 Stream.skipRecord(Entry.ID);
3454 /// Parse metadata attachments.
3455 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3456 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3457 return error("Invalid record");
3459 SmallVector<uint64_t, 64> Record;
3461 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3463 switch (Entry.Kind) {
3464 case BitstreamEntry::SubBlock: // Handled for us already.
3465 case BitstreamEntry::Error:
3466 return error("Malformed block");
3467 case BitstreamEntry::EndBlock:
3468 return std::error_code();
3469 case BitstreamEntry::Record:
3470 // The interesting case.
3474 // Read a metadata attachment record.
3476 switch (Stream.readRecord(Entry.ID, Record)) {
3477 default: // Default behavior: ignore.
3479 case bitc::METADATA_ATTACHMENT: {
3480 unsigned RecordLength = Record.size();
3482 return error("Invalid record");
3483 if (RecordLength % 2 == 0) {
3484 // A function attachment.
3485 for (unsigned I = 0; I != RecordLength; I += 2) {
3486 auto K = MDKindMap.find(Record[I]);
3487 if (K == MDKindMap.end())
3488 return error("Invalid ID");
3489 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3490 F.setMetadata(K->second, cast<MDNode>(MD));
3495 // An instruction attachment.
3496 Instruction *Inst = InstructionList[Record[0]];
3497 for (unsigned i = 1; i != RecordLength; i = i+2) {
3498 unsigned Kind = Record[i];
3499 DenseMap<unsigned, unsigned>::iterator I =
3500 MDKindMap.find(Kind);
3501 if (I == MDKindMap.end())
3502 return error("Invalid ID");
3503 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3504 if (isa<LocalAsMetadata>(Node))
3505 // Drop the attachment. This used to be legal, but there's no
3508 Inst->setMetadata(I->second, cast<MDNode>(Node));
3509 if (I->second == LLVMContext::MD_tbaa)
3510 InstsWithTBAATag.push_back(Inst);
3518 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3519 Type *ValType, Type *PtrType) {
3520 if (!isa<PointerType>(PtrType))
3521 return error(DH, "Load/Store operand is not a pointer type");
3522 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3524 if (ValType && ValType != ElemType)
3525 return error(DH, "Explicit load/store type does not match pointee type of "
3527 if (!PointerType::isLoadableOrStorableType(ElemType))
3528 return error(DH, "Cannot load/store from pointer");
3529 return std::error_code();
3532 /// Lazily parse the specified function body block.
3533 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3534 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3535 return error("Invalid record");
3537 InstructionList.clear();
3538 unsigned ModuleValueListSize = ValueList.size();
3539 unsigned ModuleMDValueListSize = MDValueList.size();
3541 // Add all the function arguments to the value table.
3542 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3543 ValueList.push_back(I);
3545 unsigned NextValueNo = ValueList.size();
3546 BasicBlock *CurBB = nullptr;
3547 unsigned CurBBNo = 0;
3550 auto getLastInstruction = [&]() -> Instruction * {
3551 if (CurBB && !CurBB->empty())
3552 return &CurBB->back();
3553 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3554 !FunctionBBs[CurBBNo - 1]->empty())
3555 return &FunctionBBs[CurBBNo - 1]->back();
3559 // Read all the records.
3560 SmallVector<uint64_t, 64> Record;
3562 BitstreamEntry Entry = Stream.advance();
3564 switch (Entry.Kind) {
3565 case BitstreamEntry::Error:
3566 return error("Malformed block");
3567 case BitstreamEntry::EndBlock:
3568 goto OutOfRecordLoop;
3570 case BitstreamEntry::SubBlock:
3572 default: // Skip unknown content.
3573 if (Stream.SkipBlock())
3574 return error("Invalid record");
3576 case bitc::CONSTANTS_BLOCK_ID:
3577 if (std::error_code EC = parseConstants())
3579 NextValueNo = ValueList.size();
3581 case bitc::VALUE_SYMTAB_BLOCK_ID:
3582 if (std::error_code EC = parseValueSymbolTable())
3585 case bitc::METADATA_ATTACHMENT_ID:
3586 if (std::error_code EC = parseMetadataAttachment(*F))
3589 case bitc::METADATA_BLOCK_ID:
3590 if (std::error_code EC = parseMetadata())
3593 case bitc::USELIST_BLOCK_ID:
3594 if (std::error_code EC = parseUseLists())
3600 case BitstreamEntry::Record:
3601 // The interesting case.
3607 Instruction *I = nullptr;
3608 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3610 default: // Default behavior: reject
3611 return error("Invalid value");
3612 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3613 if (Record.size() < 1 || Record[0] == 0)
3614 return error("Invalid record");
3615 // Create all the basic blocks for the function.
3616 FunctionBBs.resize(Record[0]);
3618 // See if anything took the address of blocks in this function.
3619 auto BBFRI = BasicBlockFwdRefs.find(F);
3620 if (BBFRI == BasicBlockFwdRefs.end()) {
3621 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3622 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3624 auto &BBRefs = BBFRI->second;
3625 // Check for invalid basic block references.
3626 if (BBRefs.size() > FunctionBBs.size())
3627 return error("Invalid ID");
3628 assert(!BBRefs.empty() && "Unexpected empty array");
3629 assert(!BBRefs.front() && "Invalid reference to entry block");
3630 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3632 if (I < RE && BBRefs[I]) {
3633 BBRefs[I]->insertInto(F);
3634 FunctionBBs[I] = BBRefs[I];
3636 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3639 // Erase from the table.
3640 BasicBlockFwdRefs.erase(BBFRI);
3643 CurBB = FunctionBBs[0];
3647 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3648 // This record indicates that the last instruction is at the same
3649 // location as the previous instruction with a location.
3650 I = getLastInstruction();
3653 return error("Invalid record");
3654 I->setDebugLoc(LastLoc);
3658 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3659 I = getLastInstruction();
3660 if (!I || Record.size() < 4)
3661 return error("Invalid record");
3663 unsigned Line = Record[0], Col = Record[1];
3664 unsigned ScopeID = Record[2], IAID = Record[3];
3666 MDNode *Scope = nullptr, *IA = nullptr;
3667 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3668 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3669 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3670 I->setDebugLoc(LastLoc);
3675 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3678 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3679 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3680 OpNum+1 > Record.size())
3681 return error("Invalid record");
3683 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3685 return error("Invalid record");
3686 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3687 InstructionList.push_back(I);
3688 if (OpNum < Record.size()) {
3689 if (Opc == Instruction::Add ||
3690 Opc == Instruction::Sub ||
3691 Opc == Instruction::Mul ||
3692 Opc == Instruction::Shl) {
3693 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3694 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3695 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3696 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3697 } else if (Opc == Instruction::SDiv ||
3698 Opc == Instruction::UDiv ||
3699 Opc == Instruction::LShr ||
3700 Opc == Instruction::AShr) {
3701 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3702 cast<BinaryOperator>(I)->setIsExact(true);
3703 } else if (isa<FPMathOperator>(I)) {
3704 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3706 I->setFastMathFlags(FMF);
3712 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3715 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3716 OpNum+2 != Record.size())
3717 return error("Invalid record");
3719 Type *ResTy = getTypeByID(Record[OpNum]);
3720 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3721 if (Opc == -1 || !ResTy)
3722 return error("Invalid record");
3723 Instruction *Temp = nullptr;
3724 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3726 InstructionList.push_back(Temp);
3727 CurBB->getInstList().push_back(Temp);
3730 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3732 InstructionList.push_back(I);
3735 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3736 case bitc::FUNC_CODE_INST_GEP_OLD:
3737 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3743 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3744 InBounds = Record[OpNum++];
3745 Ty = getTypeByID(Record[OpNum++]);
3747 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3752 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3753 return error("Invalid record");
3756 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3759 cast<SequentialType>(BasePtr->getType()->getScalarType())
3762 "Explicit gep type does not match pointee type of pointer operand");
3764 SmallVector<Value*, 16> GEPIdx;
3765 while (OpNum != Record.size()) {
3767 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3768 return error("Invalid record");
3769 GEPIdx.push_back(Op);
3772 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3774 InstructionList.push_back(I);
3776 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3780 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3781 // EXTRACTVAL: [opty, opval, n x indices]
3784 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3785 return error("Invalid record");
3787 unsigned RecSize = Record.size();
3788 if (OpNum == RecSize)
3789 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3791 SmallVector<unsigned, 4> EXTRACTVALIdx;
3792 Type *CurTy = Agg->getType();
3793 for (; OpNum != RecSize; ++OpNum) {
3794 bool IsArray = CurTy->isArrayTy();
3795 bool IsStruct = CurTy->isStructTy();
3796 uint64_t Index = Record[OpNum];
3798 if (!IsStruct && !IsArray)
3799 return error("EXTRACTVAL: Invalid type");
3800 if ((unsigned)Index != Index)
3801 return error("Invalid value");
3802 if (IsStruct && Index >= CurTy->subtypes().size())
3803 return error("EXTRACTVAL: Invalid struct index");
3804 if (IsArray && Index >= CurTy->getArrayNumElements())
3805 return error("EXTRACTVAL: Invalid array index");
3806 EXTRACTVALIdx.push_back((unsigned)Index);
3809 CurTy = CurTy->subtypes()[Index];
3811 CurTy = CurTy->subtypes()[0];
3814 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3815 InstructionList.push_back(I);
3819 case bitc::FUNC_CODE_INST_INSERTVAL: {
3820 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3823 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3824 return error("Invalid record");
3826 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3827 return error("Invalid record");
3829 unsigned RecSize = Record.size();
3830 if (OpNum == RecSize)
3831 return error("INSERTVAL: Invalid instruction with 0 indices");
3833 SmallVector<unsigned, 4> INSERTVALIdx;
3834 Type *CurTy = Agg->getType();
3835 for (; OpNum != RecSize; ++OpNum) {
3836 bool IsArray = CurTy->isArrayTy();
3837 bool IsStruct = CurTy->isStructTy();
3838 uint64_t Index = Record[OpNum];
3840 if (!IsStruct && !IsArray)
3841 return error("INSERTVAL: Invalid type");
3842 if ((unsigned)Index != Index)
3843 return error("Invalid value");
3844 if (IsStruct && Index >= CurTy->subtypes().size())
3845 return error("INSERTVAL: Invalid struct index");
3846 if (IsArray && Index >= CurTy->getArrayNumElements())
3847 return error("INSERTVAL: Invalid array index");
3849 INSERTVALIdx.push_back((unsigned)Index);
3851 CurTy = CurTy->subtypes()[Index];
3853 CurTy = CurTy->subtypes()[0];
3856 if (CurTy != Val->getType())
3857 return error("Inserted value type doesn't match aggregate type");
3859 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3860 InstructionList.push_back(I);
3864 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3865 // obsolete form of select
3866 // handles select i1 ... in old bitcode
3868 Value *TrueVal, *FalseVal, *Cond;
3869 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3870 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3871 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3872 return error("Invalid record");
3874 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3875 InstructionList.push_back(I);
3879 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3880 // new form of select
3881 // handles select i1 or select [N x i1]
3883 Value *TrueVal, *FalseVal, *Cond;
3884 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3885 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3886 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3887 return error("Invalid record");
3889 // select condition can be either i1 or [N x i1]
3890 if (VectorType* vector_type =
3891 dyn_cast<VectorType>(Cond->getType())) {
3893 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3894 return error("Invalid type for value");
3897 if (Cond->getType() != Type::getInt1Ty(Context))
3898 return error("Invalid type for value");
3901 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3902 InstructionList.push_back(I);
3906 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3909 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3910 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3911 return error("Invalid record");
3912 if (!Vec->getType()->isVectorTy())
3913 return error("Invalid type for value");
3914 I = ExtractElementInst::Create(Vec, Idx);
3915 InstructionList.push_back(I);
3919 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3921 Value *Vec, *Elt, *Idx;
3922 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3923 return error("Invalid record");
3924 if (!Vec->getType()->isVectorTy())
3925 return error("Invalid type for value");
3926 if (popValue(Record, OpNum, NextValueNo,
3927 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3928 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3929 return error("Invalid record");
3930 I = InsertElementInst::Create(Vec, Elt, Idx);
3931 InstructionList.push_back(I);
3935 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3937 Value *Vec1, *Vec2, *Mask;
3938 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3939 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3940 return error("Invalid record");
3942 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3943 return error("Invalid record");
3944 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3945 return error("Invalid type for value");
3946 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3947 InstructionList.push_back(I);
3951 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3952 // Old form of ICmp/FCmp returning bool
3953 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3954 // both legal on vectors but had different behaviour.
3955 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3956 // FCmp/ICmp returning bool or vector of bool
3960 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3961 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3962 return error("Invalid record");
3964 unsigned PredVal = Record[OpNum];
3965 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3967 if (IsFP && Record.size() > OpNum+1)
3968 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3970 if (OpNum+1 != Record.size())
3971 return error("Invalid record");
3973 if (LHS->getType()->isFPOrFPVectorTy())
3974 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3976 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3979 I->setFastMathFlags(FMF);
3980 InstructionList.push_back(I);
3984 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3986 unsigned Size = Record.size();
3988 I = ReturnInst::Create(Context);
3989 InstructionList.push_back(I);
3994 Value *Op = nullptr;
3995 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3996 return error("Invalid record");
3997 if (OpNum != Record.size())
3998 return error("Invalid record");
4000 I = ReturnInst::Create(Context, Op);
4001 InstructionList.push_back(I);
4004 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4005 if (Record.size() != 1 && Record.size() != 3)
4006 return error("Invalid record");
4007 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4009 return error("Invalid record");
4011 if (Record.size() == 1) {
4012 I = BranchInst::Create(TrueDest);
4013 InstructionList.push_back(I);
4016 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4017 Value *Cond = getValue(Record, 2, NextValueNo,
4018 Type::getInt1Ty(Context));
4019 if (!FalseDest || !Cond)
4020 return error("Invalid record");
4021 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4022 InstructionList.push_back(I);
4026 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4027 if (Record.size() != 1 && Record.size() != 2)
4028 return error("Invalid record");
4030 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4031 Type::getTokenTy(Context), OC_CleanupPad);
4033 return error("Invalid record");
4034 BasicBlock *UnwindDest = nullptr;
4035 if (Record.size() == 2) {
4036 UnwindDest = getBasicBlock(Record[Idx++]);
4038 return error("Invalid record");
4041 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4043 InstructionList.push_back(I);
4046 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4047 if (Record.size() != 2)
4048 return error("Invalid record");
4050 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4051 Type::getTokenTy(Context), OC_CatchPad);
4053 return error("Invalid record");
4054 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4056 return error("Invalid record");
4058 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4059 InstructionList.push_back(I);
4062 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4063 if (Record.size() < 3)
4064 return error("Invalid record");
4066 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4068 return error("Invalid record");
4069 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4071 return error("Invalid record");
4072 unsigned NumArgOperands = Record[Idx++];
4073 SmallVector<Value *, 2> Args;
4074 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4076 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4077 return error("Invalid record");
4078 Args.push_back(Val);
4080 if (Record.size() != Idx)
4081 return error("Invalid record");
4083 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4084 InstructionList.push_back(I);
4087 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4088 if (Record.size() < 1)
4089 return error("Invalid record");
4091 bool HasUnwindDest = !!Record[Idx++];
4092 BasicBlock *UnwindDest = nullptr;
4093 if (HasUnwindDest) {
4094 if (Idx == Record.size())
4095 return error("Invalid record");
4096 UnwindDest = getBasicBlock(Record[Idx++]);
4098 return error("Invalid record");
4100 unsigned NumArgOperands = Record[Idx++];
4101 SmallVector<Value *, 2> Args;
4102 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4104 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4105 return error("Invalid record");
4106 Args.push_back(Val);
4108 if (Record.size() != Idx)
4109 return error("Invalid record");
4111 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4112 InstructionList.push_back(I);
4115 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4116 if (Record.size() < 1)
4117 return error("Invalid record");
4119 unsigned NumArgOperands = Record[Idx++];
4120 SmallVector<Value *, 2> Args;
4121 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4123 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4124 return error("Invalid record");
4125 Args.push_back(Val);
4127 if (Record.size() != Idx)
4128 return error("Invalid record");
4130 I = CleanupPadInst::Create(Context, Args);
4131 InstructionList.push_back(I);
4134 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4135 if (Record.size() > 1)
4136 return error("Invalid record");
4137 BasicBlock *BB = nullptr;
4138 if (Record.size() == 1) {
4139 BB = getBasicBlock(Record[0]);
4141 return error("Invalid record");
4143 I = CatchEndPadInst::Create(Context, BB);
4144 InstructionList.push_back(I);
4147 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4148 if (Record.size() != 1 && Record.size() != 2)
4149 return error("Invalid record");
4151 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4152 Type::getTokenTy(Context), OC_CleanupPad);
4154 return error("Invalid record");
4156 BasicBlock *BB = nullptr;
4157 if (Record.size() == 2) {
4158 BB = getBasicBlock(Record[Idx++]);
4160 return error("Invalid record");
4162 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4163 InstructionList.push_back(I);
4166 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4168 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4169 // "New" SwitchInst format with case ranges. The changes to write this
4170 // format were reverted but we still recognize bitcode that uses it.
4171 // Hopefully someday we will have support for case ranges and can use
4172 // this format again.
4174 Type *OpTy = getTypeByID(Record[1]);
4175 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4177 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4178 BasicBlock *Default = getBasicBlock(Record[3]);
4179 if (!OpTy || !Cond || !Default)
4180 return error("Invalid record");
4182 unsigned NumCases = Record[4];
4184 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4185 InstructionList.push_back(SI);
4187 unsigned CurIdx = 5;
4188 for (unsigned i = 0; i != NumCases; ++i) {
4189 SmallVector<ConstantInt*, 1> CaseVals;
4190 unsigned NumItems = Record[CurIdx++];
4191 for (unsigned ci = 0; ci != NumItems; ++ci) {
4192 bool isSingleNumber = Record[CurIdx++];
4195 unsigned ActiveWords = 1;
4196 if (ValueBitWidth > 64)
4197 ActiveWords = Record[CurIdx++];
4198 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4200 CurIdx += ActiveWords;
4202 if (!isSingleNumber) {
4204 if (ValueBitWidth > 64)
4205 ActiveWords = Record[CurIdx++];
4206 APInt High = readWideAPInt(
4207 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4208 CurIdx += ActiveWords;
4210 // FIXME: It is not clear whether values in the range should be
4211 // compared as signed or unsigned values. The partially
4212 // implemented changes that used this format in the past used
4213 // unsigned comparisons.
4214 for ( ; Low.ule(High); ++Low)
4215 CaseVals.push_back(ConstantInt::get(Context, Low));
4217 CaseVals.push_back(ConstantInt::get(Context, Low));
4219 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4220 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4221 cve = CaseVals.end(); cvi != cve; ++cvi)
4222 SI->addCase(*cvi, DestBB);
4228 // Old SwitchInst format without case ranges.
4230 if (Record.size() < 3 || (Record.size() & 1) == 0)
4231 return error("Invalid record");
4232 Type *OpTy = getTypeByID(Record[0]);
4233 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4234 BasicBlock *Default = getBasicBlock(Record[2]);
4235 if (!OpTy || !Cond || !Default)
4236 return error("Invalid record");
4237 unsigned NumCases = (Record.size()-3)/2;
4238 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4239 InstructionList.push_back(SI);
4240 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4241 ConstantInt *CaseVal =
4242 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4243 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4244 if (!CaseVal || !DestBB) {
4246 return error("Invalid record");
4248 SI->addCase(CaseVal, DestBB);
4253 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4254 if (Record.size() < 2)
4255 return error("Invalid record");
4256 Type *OpTy = getTypeByID(Record[0]);
4257 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4258 if (!OpTy || !Address)
4259 return error("Invalid record");
4260 unsigned NumDests = Record.size()-2;
4261 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4262 InstructionList.push_back(IBI);
4263 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4264 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4265 IBI->addDestination(DestBB);
4268 return error("Invalid record");
4275 case bitc::FUNC_CODE_INST_INVOKE: {
4276 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4277 if (Record.size() < 4)
4278 return error("Invalid record");
4280 AttributeSet PAL = getAttributes(Record[OpNum++]);
4281 unsigned CCInfo = Record[OpNum++];
4282 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4283 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4285 FunctionType *FTy = nullptr;
4286 if (CCInfo >> 13 & 1 &&
4287 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4288 return error("Explicit invoke type is not a function type");
4291 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4292 return error("Invalid record");
4294 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4296 return error("Callee is not a pointer");
4298 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4300 return error("Callee is not of pointer to function type");
4301 } else if (CalleeTy->getElementType() != FTy)
4302 return error("Explicit invoke type does not match pointee type of "
4304 if (Record.size() < FTy->getNumParams() + OpNum)
4305 return error("Insufficient operands to call");
4307 SmallVector<Value*, 16> Ops;
4308 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4309 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4310 FTy->getParamType(i)));
4312 return error("Invalid record");
4315 if (!FTy->isVarArg()) {
4316 if (Record.size() != OpNum)
4317 return error("Invalid record");
4319 // Read type/value pairs for varargs params.
4320 while (OpNum != Record.size()) {
4322 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4323 return error("Invalid record");
4328 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
4329 InstructionList.push_back(I);
4331 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
4332 cast<InvokeInst>(I)->setAttributes(PAL);
4335 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4337 Value *Val = nullptr;
4338 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4339 return error("Invalid record");
4340 I = ResumeInst::Create(Val);
4341 InstructionList.push_back(I);
4344 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4345 I = new UnreachableInst(Context);
4346 InstructionList.push_back(I);
4348 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4349 if (Record.size() < 1 || ((Record.size()-1)&1))
4350 return error("Invalid record");
4351 Type *Ty = getTypeByID(Record[0]);
4353 return error("Invalid record");
4355 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4356 InstructionList.push_back(PN);
4358 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4360 // With the new function encoding, it is possible that operands have
4361 // negative IDs (for forward references). Use a signed VBR
4362 // representation to keep the encoding small.
4364 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4366 V = getValue(Record, 1+i, NextValueNo, Ty);
4367 BasicBlock *BB = getBasicBlock(Record[2+i]);
4369 return error("Invalid record");
4370 PN->addIncoming(V, BB);
4376 case bitc::FUNC_CODE_INST_LANDINGPAD:
4377 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4378 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4380 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4381 if (Record.size() < 3)
4382 return error("Invalid record");
4384 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4385 if (Record.size() < 4)
4386 return error("Invalid record");
4388 Type *Ty = getTypeByID(Record[Idx++]);
4390 return error("Invalid record");
4391 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4392 Value *PersFn = nullptr;
4393 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4394 return error("Invalid record");
4396 if (!F->hasPersonalityFn())
4397 F->setPersonalityFn(cast<Constant>(PersFn));
4398 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4399 return error("Personality function mismatch");
4402 bool IsCleanup = !!Record[Idx++];
4403 unsigned NumClauses = Record[Idx++];
4404 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4405 LP->setCleanup(IsCleanup);
4406 for (unsigned J = 0; J != NumClauses; ++J) {
4407 LandingPadInst::ClauseType CT =
4408 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4411 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4413 return error("Invalid record");
4416 assert((CT != LandingPadInst::Catch ||
4417 !isa<ArrayType>(Val->getType())) &&
4418 "Catch clause has a invalid type!");
4419 assert((CT != LandingPadInst::Filter ||
4420 isa<ArrayType>(Val->getType())) &&
4421 "Filter clause has invalid type!");
4422 LP->addClause(cast<Constant>(Val));
4426 InstructionList.push_back(I);
4430 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4431 if (Record.size() != 4)
4432 return error("Invalid record");
4433 uint64_t AlignRecord = Record[3];
4434 const uint64_t InAllocaMask = uint64_t(1) << 5;
4435 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4436 // Reserve bit 7 for SwiftError flag.
4437 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4438 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4439 bool InAlloca = AlignRecord & InAllocaMask;
4440 Type *Ty = getTypeByID(Record[0]);
4441 if ((AlignRecord & ExplicitTypeMask) == 0) {
4442 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4444 return error("Old-style alloca with a non-pointer type");
4445 Ty = PTy->getElementType();
4447 Type *OpTy = getTypeByID(Record[1]);
4448 Value *Size = getFnValueByID(Record[2], OpTy);
4450 if (std::error_code EC =
4451 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4455 return error("Invalid record");
4456 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4457 AI->setUsedWithInAlloca(InAlloca);
4459 InstructionList.push_back(I);
4462 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4465 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4466 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4467 return error("Invalid record");
4470 if (OpNum + 3 == Record.size())
4471 Ty = getTypeByID(Record[OpNum++]);
4472 if (std::error_code EC =
4473 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4476 Ty = cast<PointerType>(Op->getType())->getElementType();
4479 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4481 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4483 InstructionList.push_back(I);
4486 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4487 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4490 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4491 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4492 return error("Invalid record");
4495 if (OpNum + 5 == Record.size())
4496 Ty = getTypeByID(Record[OpNum++]);
4497 if (std::error_code EC =
4498 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4501 Ty = cast<PointerType>(Op->getType())->getElementType();
4503 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4504 if (Ordering == NotAtomic || Ordering == Release ||
4505 Ordering == AcquireRelease)
4506 return error("Invalid record");
4507 if (Ordering != NotAtomic && Record[OpNum] == 0)
4508 return error("Invalid record");
4509 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4512 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4514 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4516 InstructionList.push_back(I);
4519 case bitc::FUNC_CODE_INST_STORE:
4520 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4523 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4524 (BitCode == bitc::FUNC_CODE_INST_STORE
4525 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4526 : popValue(Record, OpNum, NextValueNo,
4527 cast<PointerType>(Ptr->getType())->getElementType(),
4529 OpNum + 2 != Record.size())
4530 return error("Invalid record");
4532 if (std::error_code EC = typeCheckLoadStoreInst(
4533 DiagnosticHandler, Val->getType(), Ptr->getType()))
4536 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4538 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4539 InstructionList.push_back(I);
4542 case bitc::FUNC_CODE_INST_STOREATOMIC:
4543 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4544 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4547 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4548 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4549 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4550 : popValue(Record, OpNum, NextValueNo,
4551 cast<PointerType>(Ptr->getType())->getElementType(),
4553 OpNum + 4 != Record.size())
4554 return error("Invalid record");
4556 if (std::error_code EC = typeCheckLoadStoreInst(
4557 DiagnosticHandler, Val->getType(), Ptr->getType()))
4559 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4560 if (Ordering == NotAtomic || Ordering == Acquire ||
4561 Ordering == AcquireRelease)
4562 return error("Invalid record");
4563 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4564 if (Ordering != NotAtomic && Record[OpNum] == 0)
4565 return error("Invalid record");
4568 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4570 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4571 InstructionList.push_back(I);
4574 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4575 case bitc::FUNC_CODE_INST_CMPXCHG: {
4576 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4577 // failureordering?, isweak?]
4579 Value *Ptr, *Cmp, *New;
4580 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4581 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4582 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4583 : popValue(Record, OpNum, NextValueNo,
4584 cast<PointerType>(Ptr->getType())->getElementType(),
4586 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4587 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4588 return error("Invalid record");
4589 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4590 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4591 return error("Invalid record");
4592 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4594 if (std::error_code EC = typeCheckLoadStoreInst(
4595 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4597 AtomicOrdering FailureOrdering;
4598 if (Record.size() < 7)
4600 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4602 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4604 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4606 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4608 if (Record.size() < 8) {
4609 // Before weak cmpxchgs existed, the instruction simply returned the
4610 // value loaded from memory, so bitcode files from that era will be
4611 // expecting the first component of a modern cmpxchg.
4612 CurBB->getInstList().push_back(I);
4613 I = ExtractValueInst::Create(I, 0);
4615 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4618 InstructionList.push_back(I);
4621 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4622 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4625 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4626 popValue(Record, OpNum, NextValueNo,
4627 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4628 OpNum+4 != Record.size())
4629 return error("Invalid record");
4630 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4631 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4632 Operation > AtomicRMWInst::LAST_BINOP)
4633 return error("Invalid record");
4634 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4635 if (Ordering == NotAtomic || Ordering == Unordered)
4636 return error("Invalid record");
4637 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4638 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4639 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4640 InstructionList.push_back(I);
4643 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4644 if (2 != Record.size())
4645 return error("Invalid record");
4646 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4647 if (Ordering == NotAtomic || Ordering == Unordered ||
4648 Ordering == Monotonic)
4649 return error("Invalid record");
4650 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4651 I = new FenceInst(Context, Ordering, SynchScope);
4652 InstructionList.push_back(I);
4655 case bitc::FUNC_CODE_INST_CALL: {
4656 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4657 if (Record.size() < 3)
4658 return error("Invalid record");
4661 AttributeSet PAL = getAttributes(Record[OpNum++]);
4662 unsigned CCInfo = Record[OpNum++];
4664 FunctionType *FTy = nullptr;
4665 if (CCInfo >> 15 & 1 &&
4666 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4667 return error("Explicit call type is not a function type");
4670 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4671 return error("Invalid record");
4673 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4675 return error("Callee is not a pointer type");
4677 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4679 return error("Callee is not of pointer to function type");
4680 } else if (OpTy->getElementType() != FTy)
4681 return error("Explicit call type does not match pointee type of "
4683 if (Record.size() < FTy->getNumParams() + OpNum)
4684 return error("Insufficient operands to call");
4686 SmallVector<Value*, 16> Args;
4687 // Read the fixed params.
4688 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4689 if (FTy->getParamType(i)->isLabelTy())
4690 Args.push_back(getBasicBlock(Record[OpNum]));
4692 Args.push_back(getValue(Record, OpNum, NextValueNo,
4693 FTy->getParamType(i)));
4695 return error("Invalid record");
4698 // Read type/value pairs for varargs params.
4699 if (!FTy->isVarArg()) {
4700 if (OpNum != Record.size())
4701 return error("Invalid record");
4703 while (OpNum != Record.size()) {
4705 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4706 return error("Invalid record");
4711 I = CallInst::Create(FTy, Callee, Args);
4712 InstructionList.push_back(I);
4713 cast<CallInst>(I)->setCallingConv(
4714 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4715 CallInst::TailCallKind TCK = CallInst::TCK_None;
4717 TCK = CallInst::TCK_Tail;
4718 if (CCInfo & (1 << 14))
4719 TCK = CallInst::TCK_MustTail;
4720 cast<CallInst>(I)->setTailCallKind(TCK);
4721 cast<CallInst>(I)->setAttributes(PAL);
4724 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4725 if (Record.size() < 3)
4726 return error("Invalid record");
4727 Type *OpTy = getTypeByID(Record[0]);
4728 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4729 Type *ResTy = getTypeByID(Record[2]);
4730 if (!OpTy || !Op || !ResTy)
4731 return error("Invalid record");
4732 I = new VAArgInst(Op, ResTy);
4733 InstructionList.push_back(I);
4738 // Add instruction to end of current BB. If there is no current BB, reject
4742 return error("Invalid instruction with no BB");
4744 CurBB->getInstList().push_back(I);
4746 // If this was a terminator instruction, move to the next block.
4747 if (isa<TerminatorInst>(I)) {
4749 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4752 // Non-void values get registered in the value table for future use.
4753 if (I && !I->getType()->isVoidTy())
4754 if (ValueList.assignValue(I, NextValueNo++))
4755 return error("Invalid forward reference");
4760 // Check the function list for unresolved values.
4761 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4762 if (!A->getParent()) {
4763 // We found at least one unresolved value. Nuke them all to avoid leaks.
4764 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4765 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4766 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4770 return error("Never resolved value found in function");
4774 // FIXME: Check for unresolved forward-declared metadata references
4775 // and clean up leaks.
4777 // Trim the value list down to the size it was before we parsed this function.
4778 ValueList.shrinkTo(ModuleValueListSize);
4779 MDValueList.shrinkTo(ModuleMDValueListSize);
4780 std::vector<BasicBlock*>().swap(FunctionBBs);
4781 return std::error_code();
4784 /// Find the function body in the bitcode stream
4785 std::error_code BitcodeReader::findFunctionInStream(
4787 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4788 while (DeferredFunctionInfoIterator->second == 0) {
4789 // This is the fallback handling for the old format bitcode that
4790 // didn't contain the function index in the VST. Assert if we end up
4791 // here for the new format (which is the only time the VSTOffset would
4793 assert(VSTOffset == 0);
4794 if (Stream.AtEndOfStream())
4795 return error("Could not find function in stream");
4796 // ParseModule will parse the next body in the stream and set its
4797 // position in the DeferredFunctionInfo map.
4798 if (std::error_code EC = parseModule(true))
4801 return std::error_code();
4804 //===----------------------------------------------------------------------===//
4805 // GVMaterializer implementation
4806 //===----------------------------------------------------------------------===//
4808 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4810 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4811 if (std::error_code EC = materializeMetadata())
4814 Function *F = dyn_cast<Function>(GV);
4815 // If it's not a function or is already material, ignore the request.
4816 if (!F || !F->isMaterializable())
4817 return std::error_code();
4819 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4820 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4821 // If its position is recorded as 0, its body is somewhere in the stream
4822 // but we haven't seen it yet.
4823 if (DFII->second == 0)
4824 if (std::error_code EC = findFunctionInStream(F, DFII))
4827 // Move the bit stream to the saved position of the deferred function body.
4828 Stream.JumpToBit(DFII->second);
4830 if (std::error_code EC = parseFunctionBody(F))
4832 F->setIsMaterializable(false);
4837 // Upgrade any old intrinsic calls in the function.
4838 for (auto &I : UpgradedIntrinsics) {
4839 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
4842 if (CallInst *CI = dyn_cast<CallInst>(U))
4843 UpgradeIntrinsicCall(CI, I.second);
4847 // Bring in any functions that this function forward-referenced via
4849 return materializeForwardReferencedFunctions();
4852 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4853 const Function *F = dyn_cast<Function>(GV);
4854 if (!F || F->isDeclaration())
4857 // Dematerializing F would leave dangling references that wouldn't be
4858 // reconnected on re-materialization.
4859 if (BlockAddressesTaken.count(F))
4862 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4865 void BitcodeReader::dematerialize(GlobalValue *GV) {
4866 Function *F = dyn_cast<Function>(GV);
4867 // If this function isn't dematerializable, this is a noop.
4868 if (!F || !isDematerializable(F))
4871 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4873 // Just forget the function body, we can remat it later.
4874 F->dropAllReferences();
4875 F->setIsMaterializable(true);
4878 std::error_code BitcodeReader::materializeModule(Module *M) {
4879 assert(M == TheModule &&
4880 "Can only Materialize the Module this BitcodeReader is attached to.");
4882 if (std::error_code EC = materializeMetadata())
4885 // Promise to materialize all forward references.
4886 WillMaterializeAllForwardRefs = true;
4888 // Iterate over the module, deserializing any functions that are still on
4890 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4892 if (std::error_code EC = materialize(F))
4895 // At this point, if there are any function bodies, the current bit is
4896 // pointing to the END_BLOCK record after them. Now make sure the rest
4897 // of the bits in the module have been read.
4901 // Check that all block address forward references got resolved (as we
4903 if (!BasicBlockFwdRefs.empty())
4904 return error("Never resolved function from blockaddress");
4906 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4907 // delete the old functions to clean up. We can't do this unless the entire
4908 // module is materialized because there could always be another function body
4909 // with calls to the old function.
4910 for (auto &I : UpgradedIntrinsics) {
4911 for (auto *U : I.first->users()) {
4912 if (CallInst *CI = dyn_cast<CallInst>(U))
4913 UpgradeIntrinsicCall(CI, I.second);
4915 if (!I.first->use_empty())
4916 I.first->replaceAllUsesWith(I.second);
4917 I.first->eraseFromParent();
4919 UpgradedIntrinsics.clear();
4921 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4922 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4924 UpgradeDebugInfo(*M);
4925 return std::error_code();
4928 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4929 return IdentifiedStructTypes;
4933 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
4935 return initLazyStream(std::move(Streamer));
4936 return initStreamFromBuffer();
4939 std::error_code BitcodeReader::initStreamFromBuffer() {
4940 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4941 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4943 if (Buffer->getBufferSize() & 3)
4944 return error("Invalid bitcode signature");
4946 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4947 // The magic number is 0x0B17C0DE stored in little endian.
4948 if (isBitcodeWrapper(BufPtr, BufEnd))
4949 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4950 return error("Invalid bitcode wrapper header");
4952 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4953 Stream.init(&*StreamFile);
4955 return std::error_code();
4959 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
4960 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4963 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
4964 StreamingMemoryObject &Bytes = *OwnedBytes;
4965 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4966 Stream.init(&*StreamFile);
4968 unsigned char buf[16];
4969 if (Bytes.readBytes(buf, 16, 0) != 16)
4970 return error("Invalid bitcode signature");
4972 if (!isBitcode(buf, buf + 16))
4973 return error("Invalid bitcode signature");
4975 if (isBitcodeWrapper(buf, buf + 4)) {
4976 const unsigned char *bitcodeStart = buf;
4977 const unsigned char *bitcodeEnd = buf + 16;
4978 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4979 Bytes.dropLeadingBytes(bitcodeStart - buf);
4980 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4982 return std::error_code();
4986 class BitcodeErrorCategoryType : public std::error_category {
4987 const char *name() const LLVM_NOEXCEPT override {
4988 return "llvm.bitcode";
4990 std::string message(int IE) const override {
4991 BitcodeError E = static_cast<BitcodeError>(IE);
4993 case BitcodeError::InvalidBitcodeSignature:
4994 return "Invalid bitcode signature";
4995 case BitcodeError::CorruptedBitcode:
4996 return "Corrupted bitcode";
4998 llvm_unreachable("Unknown error type!");
5003 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5005 const std::error_category &llvm::BitcodeErrorCategory() {
5006 return *ErrorCategory;
5009 //===----------------------------------------------------------------------===//
5010 // External interface
5011 //===----------------------------------------------------------------------===//
5013 static ErrorOr<std::unique_ptr<Module>>
5014 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5015 BitcodeReader *R, LLVMContext &Context,
5016 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5017 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5018 M->setMaterializer(R);
5020 auto cleanupOnError = [&](std::error_code EC) {
5021 R->releaseBuffer(); // Never take ownership on error.
5025 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5026 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5027 ShouldLazyLoadMetadata))
5028 return cleanupOnError(EC);
5030 if (MaterializeAll) {
5031 // Read in the entire module, and destroy the BitcodeReader.
5032 if (std::error_code EC = M->materializeAllPermanently())
5033 return cleanupOnError(EC);
5035 // Resolve forward references from blockaddresses.
5036 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5037 return cleanupOnError(EC);
5039 return std::move(M);
5042 /// \brief Get a lazy one-at-time loading module from bitcode.
5044 /// This isn't always used in a lazy context. In particular, it's also used by
5045 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5046 /// in forward-referenced functions from block address references.
5048 /// \param[in] MaterializeAll Set to \c true if we should materialize
5050 static ErrorOr<std::unique_ptr<Module>>
5051 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5052 LLVMContext &Context, bool MaterializeAll,
5053 DiagnosticHandlerFunction DiagnosticHandler,
5054 bool ShouldLazyLoadMetadata = false) {
5056 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5058 ErrorOr<std::unique_ptr<Module>> Ret =
5059 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5060 MaterializeAll, ShouldLazyLoadMetadata);
5064 Buffer.release(); // The BitcodeReader owns it now.
5068 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5069 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5070 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5071 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5072 DiagnosticHandler, ShouldLazyLoadMetadata);
5075 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5076 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5077 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5078 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5079 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5081 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5085 ErrorOr<std::unique_ptr<Module>>
5086 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5087 DiagnosticHandlerFunction DiagnosticHandler) {
5088 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5089 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5091 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5092 // written. We must defer until the Module has been fully materialized.
5096 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5097 DiagnosticHandlerFunction DiagnosticHandler) {
5098 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5099 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5101 ErrorOr<std::string> Triple = R->parseTriple();
5102 if (Triple.getError())
5104 return Triple.get();