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;
229 std::vector<std::string> BundleTags;
232 std::error_code error(BitcodeError E, const Twine &Message);
233 std::error_code error(BitcodeError E);
234 std::error_code error(const Twine &Message);
236 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
237 DiagnosticHandlerFunction DiagnosticHandler);
238 BitcodeReader(LLVMContext &Context,
239 DiagnosticHandlerFunction DiagnosticHandler);
240 ~BitcodeReader() override { freeState(); }
242 std::error_code materializeForwardReferencedFunctions();
246 void releaseBuffer();
248 bool isDematerializable(const GlobalValue *GV) const override;
249 std::error_code materialize(GlobalValue *GV) override;
250 std::error_code materializeModule(Module *M) override;
251 std::vector<StructType *> getIdentifiedStructTypes() const override;
252 void dematerialize(GlobalValue *GV) override;
254 /// \brief Main interface to parsing a bitcode buffer.
255 /// \returns true if an error occurred.
256 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
258 bool ShouldLazyLoadMetadata = false);
260 /// \brief Cheap mechanism to just extract module triple
261 /// \returns true if an error occurred.
262 ErrorOr<std::string> parseTriple();
264 static uint64_t decodeSignRotatedValue(uint64_t V);
266 /// Materialize any deferred Metadata block.
267 std::error_code materializeMetadata() override;
269 void setStripDebugInfo() override;
272 std::vector<StructType *> IdentifiedStructTypes;
273 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
274 StructType *createIdentifiedStructType(LLVMContext &Context);
276 Type *getTypeByID(unsigned ID);
277 Value *getFnValueByID(unsigned ID, Type *Ty,
278 OperatorConstraint OC = OC_None) {
279 if (Ty && Ty->isMetadataTy())
280 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
281 return ValueList.getValueFwdRef(ID, Ty, OC);
283 Metadata *getFnMetadataByID(unsigned ID) {
284 return MDValueList.getValueFwdRef(ID);
286 BasicBlock *getBasicBlock(unsigned ID) const {
287 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
288 return FunctionBBs[ID];
290 AttributeSet getAttributes(unsigned i) const {
291 if (i-1 < MAttributes.size())
292 return MAttributes[i-1];
293 return AttributeSet();
296 /// Read a value/type pair out of the specified record from slot 'Slot'.
297 /// Increment Slot past the number of slots used in the record. Return true on
299 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
300 unsigned InstNum, Value *&ResVal) {
301 if (Slot == Record.size()) return true;
302 unsigned ValNo = (unsigned)Record[Slot++];
303 // Adjust the ValNo, if it was encoded relative to the InstNum.
305 ValNo = InstNum - ValNo;
306 if (ValNo < InstNum) {
307 // If this is not a forward reference, just return the value we already
309 ResVal = getFnValueByID(ValNo, nullptr);
310 return ResVal == nullptr;
312 if (Slot == Record.size())
315 unsigned TypeNo = (unsigned)Record[Slot++];
316 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
317 return ResVal == nullptr;
320 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
321 /// past the number of slots used by the value in the record. Return true if
322 /// there is an error.
323 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
324 unsigned InstNum, Type *Ty, Value *&ResVal,
325 OperatorConstraint OC = OC_None) {
326 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
328 // All values currently take a single record slot.
333 /// Like popValue, but does not increment the Slot number.
334 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
335 unsigned InstNum, Type *Ty, Value *&ResVal,
336 OperatorConstraint OC = OC_None) {
337 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
338 return ResVal == nullptr;
341 /// Version of getValue that returns ResVal directly, or 0 if there is an
343 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
344 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
345 if (Slot == Record.size()) return nullptr;
346 unsigned ValNo = (unsigned)Record[Slot];
347 // Adjust the ValNo, if it was encoded relative to the InstNum.
349 ValNo = InstNum - ValNo;
350 return getFnValueByID(ValNo, Ty, OC);
353 /// Like getValue, but decodes signed VBRs.
354 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
355 unsigned InstNum, Type *Ty,
356 OperatorConstraint OC = OC_None) {
357 if (Slot == Record.size()) return nullptr;
358 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
359 // Adjust the ValNo, if it was encoded relative to the InstNum.
361 ValNo = InstNum - ValNo;
362 return getFnValueByID(ValNo, Ty, OC);
365 /// Converts alignment exponent (i.e. power of two (or zero)) to the
366 /// corresponding alignment to use. If alignment is too large, returns
367 /// a corresponding error code.
368 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
369 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
370 std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
371 std::error_code parseAttributeBlock();
372 std::error_code parseAttributeGroupBlock();
373 std::error_code parseTypeTable();
374 std::error_code parseTypeTableBody();
375 std::error_code parseOperandBundleTags();
377 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
378 unsigned NameIndex, Triple &TT);
379 std::error_code parseValueSymbolTable(unsigned Offset = 0);
380 std::error_code parseConstants();
381 std::error_code rememberAndSkipFunctionBody();
382 /// Save the positions of the Metadata blocks and skip parsing the blocks.
383 std::error_code rememberAndSkipMetadata();
384 std::error_code parseFunctionBody(Function *F);
385 std::error_code globalCleanup();
386 std::error_code resolveGlobalAndAliasInits();
387 std::error_code parseMetadata();
388 std::error_code parseMetadataAttachment(Function &F);
389 ErrorOr<std::string> parseModuleTriple();
390 std::error_code parseUseLists();
391 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
392 std::error_code initStreamFromBuffer();
393 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
394 std::error_code findFunctionInStream(
396 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
400 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
401 DiagnosticSeverity Severity,
403 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
405 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
407 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
408 std::error_code EC, const Twine &Message) {
409 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
410 DiagnosticHandler(DI);
414 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
415 std::error_code EC) {
416 return error(DiagnosticHandler, EC, EC.message());
419 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
420 const Twine &Message) {
421 return error(DiagnosticHandler,
422 make_error_code(BitcodeError::CorruptedBitcode), Message);
425 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
426 return ::error(DiagnosticHandler, make_error_code(E), Message);
429 std::error_code BitcodeReader::error(const Twine &Message) {
430 return ::error(DiagnosticHandler,
431 make_error_code(BitcodeError::CorruptedBitcode), Message);
434 std::error_code BitcodeReader::error(BitcodeError E) {
435 return ::error(DiagnosticHandler, make_error_code(E));
438 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
442 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
445 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
446 DiagnosticHandlerFunction DiagnosticHandler)
448 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
449 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
451 BitcodeReader::BitcodeReader(LLVMContext &Context,
452 DiagnosticHandlerFunction DiagnosticHandler)
454 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
455 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
457 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
458 if (WillMaterializeAllForwardRefs)
459 return std::error_code();
461 // Prevent recursion.
462 WillMaterializeAllForwardRefs = true;
464 while (!BasicBlockFwdRefQueue.empty()) {
465 Function *F = BasicBlockFwdRefQueue.front();
466 BasicBlockFwdRefQueue.pop_front();
467 assert(F && "Expected valid function");
468 if (!BasicBlockFwdRefs.count(F))
469 // Already materialized.
472 // Check for a function that isn't materializable to prevent an infinite
473 // loop. When parsing a blockaddress stored in a global variable, there
474 // isn't a trivial way to check if a function will have a body without a
475 // linear search through FunctionsWithBodies, so just check it here.
476 if (!F->isMaterializable())
477 return error("Never resolved function from blockaddress");
479 // Try to materialize F.
480 if (std::error_code EC = materialize(F))
483 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
486 WillMaterializeAllForwardRefs = false;
487 return std::error_code();
490 void BitcodeReader::freeState() {
492 std::vector<Type*>().swap(TypeList);
495 std::vector<Comdat *>().swap(ComdatList);
497 std::vector<AttributeSet>().swap(MAttributes);
498 std::vector<BasicBlock*>().swap(FunctionBBs);
499 std::vector<Function*>().swap(FunctionsWithBodies);
500 DeferredFunctionInfo.clear();
501 DeferredMetadataInfo.clear();
504 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
505 BasicBlockFwdRefQueue.clear();
508 //===----------------------------------------------------------------------===//
509 // Helper functions to implement forward reference resolution, etc.
510 //===----------------------------------------------------------------------===//
512 /// Convert a string from a record into an std::string, return true on failure.
513 template <typename StrTy>
514 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
516 if (Idx > Record.size())
519 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
520 Result += (char)Record[i];
524 static bool hasImplicitComdat(size_t Val) {
528 case 1: // Old WeakAnyLinkage
529 case 4: // Old LinkOnceAnyLinkage
530 case 10: // Old WeakODRLinkage
531 case 11: // Old LinkOnceODRLinkage
536 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
538 default: // Map unknown/new linkages to external
540 return GlobalValue::ExternalLinkage;
542 return GlobalValue::AppendingLinkage;
544 return GlobalValue::InternalLinkage;
546 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
548 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
550 return GlobalValue::ExternalWeakLinkage;
552 return GlobalValue::CommonLinkage;
554 return GlobalValue::PrivateLinkage;
556 return GlobalValue::AvailableExternallyLinkage;
558 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
560 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
562 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
563 case 1: // Old value with implicit comdat.
565 return GlobalValue::WeakAnyLinkage;
566 case 10: // Old value with implicit comdat.
568 return GlobalValue::WeakODRLinkage;
569 case 4: // Old value with implicit comdat.
571 return GlobalValue::LinkOnceAnyLinkage;
572 case 11: // Old value with implicit comdat.
574 return GlobalValue::LinkOnceODRLinkage;
578 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
580 default: // Map unknown visibilities to default.
581 case 0: return GlobalValue::DefaultVisibility;
582 case 1: return GlobalValue::HiddenVisibility;
583 case 2: return GlobalValue::ProtectedVisibility;
587 static GlobalValue::DLLStorageClassTypes
588 getDecodedDLLStorageClass(unsigned Val) {
590 default: // Map unknown values to default.
591 case 0: return GlobalValue::DefaultStorageClass;
592 case 1: return GlobalValue::DLLImportStorageClass;
593 case 2: return GlobalValue::DLLExportStorageClass;
597 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
599 case 0: return GlobalVariable::NotThreadLocal;
600 default: // Map unknown non-zero value to general dynamic.
601 case 1: return GlobalVariable::GeneralDynamicTLSModel;
602 case 2: return GlobalVariable::LocalDynamicTLSModel;
603 case 3: return GlobalVariable::InitialExecTLSModel;
604 case 4: return GlobalVariable::LocalExecTLSModel;
608 static int getDecodedCastOpcode(unsigned Val) {
611 case bitc::CAST_TRUNC : return Instruction::Trunc;
612 case bitc::CAST_ZEXT : return Instruction::ZExt;
613 case bitc::CAST_SEXT : return Instruction::SExt;
614 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
615 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
616 case bitc::CAST_UITOFP : return Instruction::UIToFP;
617 case bitc::CAST_SITOFP : return Instruction::SIToFP;
618 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
619 case bitc::CAST_FPEXT : return Instruction::FPExt;
620 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
621 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
622 case bitc::CAST_BITCAST : return Instruction::BitCast;
623 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
627 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
628 bool IsFP = Ty->isFPOrFPVectorTy();
629 // BinOps are only valid for int/fp or vector of int/fp types
630 if (!IsFP && !Ty->isIntOrIntVectorTy())
636 case bitc::BINOP_ADD:
637 return IsFP ? Instruction::FAdd : Instruction::Add;
638 case bitc::BINOP_SUB:
639 return IsFP ? Instruction::FSub : Instruction::Sub;
640 case bitc::BINOP_MUL:
641 return IsFP ? Instruction::FMul : Instruction::Mul;
642 case bitc::BINOP_UDIV:
643 return IsFP ? -1 : Instruction::UDiv;
644 case bitc::BINOP_SDIV:
645 return IsFP ? Instruction::FDiv : Instruction::SDiv;
646 case bitc::BINOP_UREM:
647 return IsFP ? -1 : Instruction::URem;
648 case bitc::BINOP_SREM:
649 return IsFP ? Instruction::FRem : Instruction::SRem;
650 case bitc::BINOP_SHL:
651 return IsFP ? -1 : Instruction::Shl;
652 case bitc::BINOP_LSHR:
653 return IsFP ? -1 : Instruction::LShr;
654 case bitc::BINOP_ASHR:
655 return IsFP ? -1 : Instruction::AShr;
656 case bitc::BINOP_AND:
657 return IsFP ? -1 : Instruction::And;
659 return IsFP ? -1 : Instruction::Or;
660 case bitc::BINOP_XOR:
661 return IsFP ? -1 : Instruction::Xor;
665 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
667 default: return AtomicRMWInst::BAD_BINOP;
668 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
669 case bitc::RMW_ADD: return AtomicRMWInst::Add;
670 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
671 case bitc::RMW_AND: return AtomicRMWInst::And;
672 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
673 case bitc::RMW_OR: return AtomicRMWInst::Or;
674 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
675 case bitc::RMW_MAX: return AtomicRMWInst::Max;
676 case bitc::RMW_MIN: return AtomicRMWInst::Min;
677 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
678 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
682 static AtomicOrdering getDecodedOrdering(unsigned Val) {
684 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
685 case bitc::ORDERING_UNORDERED: return Unordered;
686 case bitc::ORDERING_MONOTONIC: return Monotonic;
687 case bitc::ORDERING_ACQUIRE: return Acquire;
688 case bitc::ORDERING_RELEASE: return Release;
689 case bitc::ORDERING_ACQREL: return AcquireRelease;
690 default: // Map unknown orderings to sequentially-consistent.
691 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
695 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
697 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
698 default: // Map unknown scopes to cross-thread.
699 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
703 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
705 default: // Map unknown selection kinds to any.
706 case bitc::COMDAT_SELECTION_KIND_ANY:
708 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
709 return Comdat::ExactMatch;
710 case bitc::COMDAT_SELECTION_KIND_LARGEST:
711 return Comdat::Largest;
712 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
713 return Comdat::NoDuplicates;
714 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
715 return Comdat::SameSize;
719 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
721 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
722 FMF.setUnsafeAlgebra();
723 if (0 != (Val & FastMathFlags::NoNaNs))
725 if (0 != (Val & FastMathFlags::NoInfs))
727 if (0 != (Val & FastMathFlags::NoSignedZeros))
728 FMF.setNoSignedZeros();
729 if (0 != (Val & FastMathFlags::AllowReciprocal))
730 FMF.setAllowReciprocal();
734 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
736 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
737 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
743 /// \brief A class for maintaining the slot number definition
744 /// as a placeholder for the actual definition for forward constants defs.
745 class ConstantPlaceHolder : public ConstantExpr {
746 void operator=(const ConstantPlaceHolder &) = delete;
749 // allocate space for exactly one operand
750 void *operator new(size_t s) { return User::operator new(s, 1); }
751 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
752 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
753 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
756 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
757 static bool classof(const Value *V) {
758 return isa<ConstantExpr>(V) &&
759 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
762 /// Provide fast operand accessors
763 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
767 // FIXME: can we inherit this from ConstantExpr?
769 struct OperandTraits<ConstantPlaceHolder> :
770 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
772 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
775 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
784 WeakVH &OldV = ValuePtrs[Idx];
790 // Handle constants and non-constants (e.g. instrs) differently for
792 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
793 ResolveConstants.push_back(std::make_pair(PHC, Idx));
796 // If there was a forward reference to this value, replace it.
797 Value *PrevVal = OldV;
798 // Check operator constraints. We only put cleanuppads or catchpads in
799 // the forward value map if the value is constrained to match.
800 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
801 if (!isa<CatchPadInst>(V))
803 // Delete the dummy basic block that was created with the sentinel
805 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
806 assert(DummyBlock == CatchPad->getNormalDest());
807 CatchPad->dropAllReferences();
809 } else if (isa<CleanupPadInst>(PrevVal)) {
810 if (!isa<CleanupPadInst>(V))
813 OldV->replaceAllUsesWith(V);
821 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
826 if (Value *V = ValuePtrs[Idx]) {
827 if (Ty != V->getType())
828 report_fatal_error("Type mismatch in constant table!");
829 return cast<Constant>(V);
832 // Create and return a placeholder, which will later be RAUW'd.
833 Constant *C = new ConstantPlaceHolder(Ty, Context);
838 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
839 OperatorConstraint OC) {
840 // Bail out for a clearly invalid value. This would make us call resize(0)
847 if (Value *V = ValuePtrs[Idx]) {
848 // If the types don't match, it's invalid.
849 if (Ty && Ty != V->getType())
853 // Use dyn_cast to enforce operator constraints
856 return dyn_cast<CatchPadInst>(V);
858 return dyn_cast<CleanupPadInst>(V);
860 llvm_unreachable("Unexpected operator constraint");
864 // No type specified, must be invalid reference.
865 if (!Ty) return nullptr;
867 // Create and return a placeholder, which will later be RAUW'd.
871 V = new Argument(Ty);
874 BasicBlock *BB = BasicBlock::Create(Context);
875 V = CatchPadInst::Create(BB, BB, {});
879 assert(OC == OC_CleanupPad && "unexpected operator constraint");
880 V = CleanupPadInst::Create(Context, {});
888 /// Once all constants are read, this method bulk resolves any forward
889 /// references. The idea behind this is that we sometimes get constants (such
890 /// as large arrays) which reference *many* forward ref constants. Replacing
891 /// each of these causes a lot of thrashing when building/reuniquing the
892 /// constant. Instead of doing this, we look at all the uses and rewrite all
893 /// the place holders at once for any constant that uses a placeholder.
894 void BitcodeReaderValueList::resolveConstantForwardRefs() {
895 // Sort the values by-pointer so that they are efficient to look up with a
897 std::sort(ResolveConstants.begin(), ResolveConstants.end());
899 SmallVector<Constant*, 64> NewOps;
901 while (!ResolveConstants.empty()) {
902 Value *RealVal = operator[](ResolveConstants.back().second);
903 Constant *Placeholder = ResolveConstants.back().first;
904 ResolveConstants.pop_back();
906 // Loop over all users of the placeholder, updating them to reference the
907 // new value. If they reference more than one placeholder, update them all
909 while (!Placeholder->use_empty()) {
910 auto UI = Placeholder->user_begin();
913 // If the using object isn't uniqued, just update the operands. This
914 // handles instructions and initializers for global variables.
915 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
916 UI.getUse().set(RealVal);
920 // Otherwise, we have a constant that uses the placeholder. Replace that
921 // constant with a new constant that has *all* placeholder uses updated.
922 Constant *UserC = cast<Constant>(U);
923 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
926 if (!isa<ConstantPlaceHolder>(*I)) {
927 // Not a placeholder reference.
929 } else if (*I == Placeholder) {
930 // Common case is that it just references this one placeholder.
933 // Otherwise, look up the placeholder in ResolveConstants.
934 ResolveConstantsTy::iterator It =
935 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
936 std::pair<Constant*, unsigned>(cast<Constant>(*I),
938 assert(It != ResolveConstants.end() && It->first == *I);
939 NewOp = operator[](It->second);
942 NewOps.push_back(cast<Constant>(NewOp));
945 // Make the new constant.
947 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
948 NewC = ConstantArray::get(UserCA->getType(), NewOps);
949 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
950 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
951 } else if (isa<ConstantVector>(UserC)) {
952 NewC = ConstantVector::get(NewOps);
954 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
955 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
958 UserC->replaceAllUsesWith(NewC);
959 UserC->destroyConstant();
963 // Update all ValueHandles, they should be the only users at this point.
964 Placeholder->replaceAllUsesWith(RealVal);
969 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
978 TrackingMDRef &OldMD = MDValuePtrs[Idx];
984 // If there was a forward reference to this value, replace it.
985 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
986 PrevMD->replaceAllUsesWith(MD);
990 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
994 if (Metadata *MD = MDValuePtrs[Idx])
997 // Track forward refs to be resolved later.
999 MinFwdRef = std::min(MinFwdRef, Idx);
1000 MaxFwdRef = std::max(MaxFwdRef, Idx);
1003 MinFwdRef = MaxFwdRef = Idx;
1007 // Create and return a placeholder, which will later be RAUW'd.
1008 Metadata *MD = MDNode::getTemporary(Context, None).release();
1009 MDValuePtrs[Idx].reset(MD);
1013 void BitcodeReaderMDValueList::tryToResolveCycles() {
1019 // Still forward references... can't resolve cycles.
1022 // Resolve any cycles.
1023 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1024 auto &MD = MDValuePtrs[I];
1025 auto *N = dyn_cast_or_null<MDNode>(MD);
1029 assert(!N->isTemporary() && "Unexpected forward reference");
1033 // Make sure we return early again until there's another forward ref.
1037 Type *BitcodeReader::getTypeByID(unsigned ID) {
1038 // The type table size is always specified correctly.
1039 if (ID >= TypeList.size())
1042 if (Type *Ty = TypeList[ID])
1045 // If we have a forward reference, the only possible case is when it is to a
1046 // named struct. Just create a placeholder for now.
1047 return TypeList[ID] = createIdentifiedStructType(Context);
1050 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1052 auto *Ret = StructType::create(Context, Name);
1053 IdentifiedStructTypes.push_back(Ret);
1057 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1058 auto *Ret = StructType::create(Context);
1059 IdentifiedStructTypes.push_back(Ret);
1064 //===----------------------------------------------------------------------===//
1065 // Functions for parsing blocks from the bitcode file
1066 //===----------------------------------------------------------------------===//
1069 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1070 /// been decoded from the given integer. This function must stay in sync with
1071 /// 'encodeLLVMAttributesForBitcode'.
1072 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1073 uint64_t EncodedAttrs) {
1074 // FIXME: Remove in 4.0.
1076 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1077 // the bits above 31 down by 11 bits.
1078 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1079 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1080 "Alignment must be a power of two.");
1083 B.addAlignmentAttr(Alignment);
1084 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1085 (EncodedAttrs & 0xffff));
1088 std::error_code BitcodeReader::parseAttributeBlock() {
1089 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1090 return error("Invalid record");
1092 if (!MAttributes.empty())
1093 return error("Invalid multiple blocks");
1095 SmallVector<uint64_t, 64> Record;
1097 SmallVector<AttributeSet, 8> Attrs;
1099 // Read all the records.
1101 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1103 switch (Entry.Kind) {
1104 case BitstreamEntry::SubBlock: // Handled for us already.
1105 case BitstreamEntry::Error:
1106 return error("Malformed block");
1107 case BitstreamEntry::EndBlock:
1108 return std::error_code();
1109 case BitstreamEntry::Record:
1110 // The interesting case.
1116 switch (Stream.readRecord(Entry.ID, Record)) {
1117 default: // Default behavior: ignore.
1119 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1120 // FIXME: Remove in 4.0.
1121 if (Record.size() & 1)
1122 return error("Invalid record");
1124 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1126 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1127 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1130 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1134 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1135 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1136 Attrs.push_back(MAttributeGroups[Record[i]]);
1138 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1146 // Returns Attribute::None on unrecognized codes.
1147 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1150 return Attribute::None;
1151 case bitc::ATTR_KIND_ALIGNMENT:
1152 return Attribute::Alignment;
1153 case bitc::ATTR_KIND_ALWAYS_INLINE:
1154 return Attribute::AlwaysInline;
1155 case bitc::ATTR_KIND_ARGMEMONLY:
1156 return Attribute::ArgMemOnly;
1157 case bitc::ATTR_KIND_BUILTIN:
1158 return Attribute::Builtin;
1159 case bitc::ATTR_KIND_BY_VAL:
1160 return Attribute::ByVal;
1161 case bitc::ATTR_KIND_IN_ALLOCA:
1162 return Attribute::InAlloca;
1163 case bitc::ATTR_KIND_COLD:
1164 return Attribute::Cold;
1165 case bitc::ATTR_KIND_CONVERGENT:
1166 return Attribute::Convergent;
1167 case bitc::ATTR_KIND_INLINE_HINT:
1168 return Attribute::InlineHint;
1169 case bitc::ATTR_KIND_IN_REG:
1170 return Attribute::InReg;
1171 case bitc::ATTR_KIND_JUMP_TABLE:
1172 return Attribute::JumpTable;
1173 case bitc::ATTR_KIND_MIN_SIZE:
1174 return Attribute::MinSize;
1175 case bitc::ATTR_KIND_NAKED:
1176 return Attribute::Naked;
1177 case bitc::ATTR_KIND_NEST:
1178 return Attribute::Nest;
1179 case bitc::ATTR_KIND_NO_ALIAS:
1180 return Attribute::NoAlias;
1181 case bitc::ATTR_KIND_NO_BUILTIN:
1182 return Attribute::NoBuiltin;
1183 case bitc::ATTR_KIND_NO_CAPTURE:
1184 return Attribute::NoCapture;
1185 case bitc::ATTR_KIND_NO_DUPLICATE:
1186 return Attribute::NoDuplicate;
1187 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1188 return Attribute::NoImplicitFloat;
1189 case bitc::ATTR_KIND_NO_INLINE:
1190 return Attribute::NoInline;
1191 case bitc::ATTR_KIND_NON_LAZY_BIND:
1192 return Attribute::NonLazyBind;
1193 case bitc::ATTR_KIND_NON_NULL:
1194 return Attribute::NonNull;
1195 case bitc::ATTR_KIND_DEREFERENCEABLE:
1196 return Attribute::Dereferenceable;
1197 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1198 return Attribute::DereferenceableOrNull;
1199 case bitc::ATTR_KIND_NO_RED_ZONE:
1200 return Attribute::NoRedZone;
1201 case bitc::ATTR_KIND_NO_RETURN:
1202 return Attribute::NoReturn;
1203 case bitc::ATTR_KIND_NO_UNWIND:
1204 return Attribute::NoUnwind;
1205 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1206 return Attribute::OptimizeForSize;
1207 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1208 return Attribute::OptimizeNone;
1209 case bitc::ATTR_KIND_READ_NONE:
1210 return Attribute::ReadNone;
1211 case bitc::ATTR_KIND_READ_ONLY:
1212 return Attribute::ReadOnly;
1213 case bitc::ATTR_KIND_RETURNED:
1214 return Attribute::Returned;
1215 case bitc::ATTR_KIND_RETURNS_TWICE:
1216 return Attribute::ReturnsTwice;
1217 case bitc::ATTR_KIND_S_EXT:
1218 return Attribute::SExt;
1219 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1220 return Attribute::StackAlignment;
1221 case bitc::ATTR_KIND_STACK_PROTECT:
1222 return Attribute::StackProtect;
1223 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1224 return Attribute::StackProtectReq;
1225 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1226 return Attribute::StackProtectStrong;
1227 case bitc::ATTR_KIND_SAFESTACK:
1228 return Attribute::SafeStack;
1229 case bitc::ATTR_KIND_STRUCT_RET:
1230 return Attribute::StructRet;
1231 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1232 return Attribute::SanitizeAddress;
1233 case bitc::ATTR_KIND_SANITIZE_THREAD:
1234 return Attribute::SanitizeThread;
1235 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1236 return Attribute::SanitizeMemory;
1237 case bitc::ATTR_KIND_UW_TABLE:
1238 return Attribute::UWTable;
1239 case bitc::ATTR_KIND_Z_EXT:
1240 return Attribute::ZExt;
1244 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1245 unsigned &Alignment) {
1246 // Note: Alignment in bitcode files is incremented by 1, so that zero
1247 // can be used for default alignment.
1248 if (Exponent > Value::MaxAlignmentExponent + 1)
1249 return error("Invalid alignment value");
1250 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1251 return std::error_code();
1254 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1255 Attribute::AttrKind *Kind) {
1256 *Kind = getAttrFromCode(Code);
1257 if (*Kind == Attribute::None)
1258 return error(BitcodeError::CorruptedBitcode,
1259 "Unknown attribute kind (" + Twine(Code) + ")");
1260 return std::error_code();
1263 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1264 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1265 return error("Invalid record");
1267 if (!MAttributeGroups.empty())
1268 return error("Invalid multiple blocks");
1270 SmallVector<uint64_t, 64> Record;
1272 // Read all the records.
1274 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1276 switch (Entry.Kind) {
1277 case BitstreamEntry::SubBlock: // Handled for us already.
1278 case BitstreamEntry::Error:
1279 return error("Malformed block");
1280 case BitstreamEntry::EndBlock:
1281 return std::error_code();
1282 case BitstreamEntry::Record:
1283 // The interesting case.
1289 switch (Stream.readRecord(Entry.ID, Record)) {
1290 default: // Default behavior: ignore.
1292 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1293 if (Record.size() < 3)
1294 return error("Invalid record");
1296 uint64_t GrpID = Record[0];
1297 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1300 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1301 if (Record[i] == 0) { // Enum attribute
1302 Attribute::AttrKind Kind;
1303 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1306 B.addAttribute(Kind);
1307 } else if (Record[i] == 1) { // Integer attribute
1308 Attribute::AttrKind Kind;
1309 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1311 if (Kind == Attribute::Alignment)
1312 B.addAlignmentAttr(Record[++i]);
1313 else if (Kind == Attribute::StackAlignment)
1314 B.addStackAlignmentAttr(Record[++i]);
1315 else if (Kind == Attribute::Dereferenceable)
1316 B.addDereferenceableAttr(Record[++i]);
1317 else if (Kind == Attribute::DereferenceableOrNull)
1318 B.addDereferenceableOrNullAttr(Record[++i]);
1319 } else { // String attribute
1320 assert((Record[i] == 3 || Record[i] == 4) &&
1321 "Invalid attribute group entry");
1322 bool HasValue = (Record[i++] == 4);
1323 SmallString<64> KindStr;
1324 SmallString<64> ValStr;
1326 while (Record[i] != 0 && i != e)
1327 KindStr += Record[i++];
1328 assert(Record[i] == 0 && "Kind string not null terminated");
1331 // Has a value associated with it.
1332 ++i; // Skip the '0' that terminates the "kind" string.
1333 while (Record[i] != 0 && i != e)
1334 ValStr += Record[i++];
1335 assert(Record[i] == 0 && "Value string not null terminated");
1338 B.addAttribute(KindStr.str(), ValStr.str());
1342 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1349 std::error_code BitcodeReader::parseTypeTable() {
1350 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1351 return error("Invalid record");
1353 return parseTypeTableBody();
1356 std::error_code BitcodeReader::parseTypeTableBody() {
1357 if (!TypeList.empty())
1358 return error("Invalid multiple blocks");
1360 SmallVector<uint64_t, 64> Record;
1361 unsigned NumRecords = 0;
1363 SmallString<64> TypeName;
1365 // Read all the records for this type table.
1367 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1369 switch (Entry.Kind) {
1370 case BitstreamEntry::SubBlock: // Handled for us already.
1371 case BitstreamEntry::Error:
1372 return error("Malformed block");
1373 case BitstreamEntry::EndBlock:
1374 if (NumRecords != TypeList.size())
1375 return error("Malformed block");
1376 return std::error_code();
1377 case BitstreamEntry::Record:
1378 // The interesting case.
1384 Type *ResultTy = nullptr;
1385 switch (Stream.readRecord(Entry.ID, Record)) {
1387 return error("Invalid value");
1388 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1389 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1390 // type list. This allows us to reserve space.
1391 if (Record.size() < 1)
1392 return error("Invalid record");
1393 TypeList.resize(Record[0]);
1395 case bitc::TYPE_CODE_VOID: // VOID
1396 ResultTy = Type::getVoidTy(Context);
1398 case bitc::TYPE_CODE_HALF: // HALF
1399 ResultTy = Type::getHalfTy(Context);
1401 case bitc::TYPE_CODE_FLOAT: // FLOAT
1402 ResultTy = Type::getFloatTy(Context);
1404 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1405 ResultTy = Type::getDoubleTy(Context);
1407 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1408 ResultTy = Type::getX86_FP80Ty(Context);
1410 case bitc::TYPE_CODE_FP128: // FP128
1411 ResultTy = Type::getFP128Ty(Context);
1413 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1414 ResultTy = Type::getPPC_FP128Ty(Context);
1416 case bitc::TYPE_CODE_LABEL: // LABEL
1417 ResultTy = Type::getLabelTy(Context);
1419 case bitc::TYPE_CODE_METADATA: // METADATA
1420 ResultTy = Type::getMetadataTy(Context);
1422 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1423 ResultTy = Type::getX86_MMXTy(Context);
1425 case bitc::TYPE_CODE_TOKEN: // TOKEN
1426 ResultTy = Type::getTokenTy(Context);
1428 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1429 if (Record.size() < 1)
1430 return error("Invalid record");
1432 uint64_t NumBits = Record[0];
1433 if (NumBits < IntegerType::MIN_INT_BITS ||
1434 NumBits > IntegerType::MAX_INT_BITS)
1435 return error("Bitwidth for integer type out of range");
1436 ResultTy = IntegerType::get(Context, NumBits);
1439 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1440 // [pointee type, address space]
1441 if (Record.size() < 1)
1442 return error("Invalid record");
1443 unsigned AddressSpace = 0;
1444 if (Record.size() == 2)
1445 AddressSpace = Record[1];
1446 ResultTy = getTypeByID(Record[0]);
1448 !PointerType::isValidElementType(ResultTy))
1449 return error("Invalid type");
1450 ResultTy = PointerType::get(ResultTy, AddressSpace);
1453 case bitc::TYPE_CODE_FUNCTION_OLD: {
1454 // FIXME: attrid is dead, remove it in LLVM 4.0
1455 // FUNCTION: [vararg, attrid, retty, paramty x N]
1456 if (Record.size() < 3)
1457 return error("Invalid record");
1458 SmallVector<Type*, 8> ArgTys;
1459 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1460 if (Type *T = getTypeByID(Record[i]))
1461 ArgTys.push_back(T);
1466 ResultTy = getTypeByID(Record[2]);
1467 if (!ResultTy || ArgTys.size() < Record.size()-3)
1468 return error("Invalid type");
1470 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1473 case bitc::TYPE_CODE_FUNCTION: {
1474 // FUNCTION: [vararg, retty, paramty x N]
1475 if (Record.size() < 2)
1476 return error("Invalid record");
1477 SmallVector<Type*, 8> ArgTys;
1478 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1479 if (Type *T = getTypeByID(Record[i])) {
1480 if (!FunctionType::isValidArgumentType(T))
1481 return error("Invalid function argument type");
1482 ArgTys.push_back(T);
1488 ResultTy = getTypeByID(Record[1]);
1489 if (!ResultTy || ArgTys.size() < Record.size()-2)
1490 return error("Invalid type");
1492 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1495 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1496 if (Record.size() < 1)
1497 return error("Invalid record");
1498 SmallVector<Type*, 8> EltTys;
1499 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1500 if (Type *T = getTypeByID(Record[i]))
1501 EltTys.push_back(T);
1505 if (EltTys.size() != Record.size()-1)
1506 return error("Invalid type");
1507 ResultTy = StructType::get(Context, EltTys, Record[0]);
1510 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1511 if (convertToString(Record, 0, TypeName))
1512 return error("Invalid record");
1515 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1516 if (Record.size() < 1)
1517 return error("Invalid record");
1519 if (NumRecords >= TypeList.size())
1520 return error("Invalid TYPE table");
1522 // Check to see if this was forward referenced, if so fill in the temp.
1523 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1525 Res->setName(TypeName);
1526 TypeList[NumRecords] = nullptr;
1527 } else // Otherwise, create a new struct.
1528 Res = createIdentifiedStructType(Context, TypeName);
1531 SmallVector<Type*, 8> EltTys;
1532 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1533 if (Type *T = getTypeByID(Record[i]))
1534 EltTys.push_back(T);
1538 if (EltTys.size() != Record.size()-1)
1539 return error("Invalid record");
1540 Res->setBody(EltTys, Record[0]);
1544 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1545 if (Record.size() != 1)
1546 return error("Invalid record");
1548 if (NumRecords >= TypeList.size())
1549 return error("Invalid TYPE table");
1551 // Check to see if this was forward referenced, if so fill in the temp.
1552 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1554 Res->setName(TypeName);
1555 TypeList[NumRecords] = nullptr;
1556 } else // Otherwise, create a new struct with no body.
1557 Res = createIdentifiedStructType(Context, TypeName);
1562 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1563 if (Record.size() < 2)
1564 return error("Invalid record");
1565 ResultTy = getTypeByID(Record[1]);
1566 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1567 return error("Invalid type");
1568 ResultTy = ArrayType::get(ResultTy, Record[0]);
1570 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1571 if (Record.size() < 2)
1572 return error("Invalid record");
1574 return error("Invalid vector length");
1575 ResultTy = getTypeByID(Record[1]);
1576 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1577 return error("Invalid type");
1578 ResultTy = VectorType::get(ResultTy, Record[0]);
1582 if (NumRecords >= TypeList.size())
1583 return error("Invalid TYPE table");
1584 if (TypeList[NumRecords])
1586 "Invalid TYPE table: Only named structs can be forward referenced");
1587 assert(ResultTy && "Didn't read a type?");
1588 TypeList[NumRecords++] = ResultTy;
1592 std::error_code BitcodeReader::parseOperandBundleTags() {
1593 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1594 return error("Invalid record");
1596 if (!BundleTags.empty())
1597 return error("Invalid multiple blocks");
1599 SmallVector<uint64_t, 64> Record;
1602 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1604 switch (Entry.Kind) {
1605 case BitstreamEntry::SubBlock: // Handled for us already.
1606 case BitstreamEntry::Error:
1607 return error("Malformed block");
1608 case BitstreamEntry::EndBlock:
1609 return std::error_code();
1610 case BitstreamEntry::Record:
1611 // The interesting case.
1615 // Tags are implicitly mapped to integers by their order.
1617 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1618 return error("Invalid record");
1620 // OPERAND_BUNDLE_TAG: [strchr x N]
1621 BundleTags.emplace_back();
1622 if (convertToString(Record, 0, BundleTags.back()))
1623 return error("Invalid record");
1628 /// Associate a value with its name from the given index in the provided record.
1629 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1630 unsigned NameIndex, Triple &TT) {
1631 SmallString<128> ValueName;
1632 if (convertToString(Record, NameIndex, ValueName))
1633 return error("Invalid record");
1634 unsigned ValueID = Record[0];
1635 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1636 return error("Invalid record");
1637 Value *V = ValueList[ValueID];
1639 V->setName(StringRef(ValueName.data(), ValueName.size()));
1640 auto *GO = dyn_cast<GlobalObject>(V);
1642 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1643 if (TT.isOSBinFormatMachO())
1644 GO->setComdat(nullptr);
1646 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1652 /// Parse the value symbol table at either the current parsing location or
1653 /// at the given bit offset if provided.
1654 std::error_code BitcodeReader::parseValueSymbolTable(unsigned Offset) {
1655 uint64_t CurrentBit;
1656 // Pass in the Offset to distinguish between calling for the module-level
1657 // VST (where we want to jump to the VST offset) and the function-level
1658 // VST (where we don't).
1660 // Save the current parsing location so we can jump back at the end
1662 CurrentBit = Stream.GetCurrentBitNo();
1663 Stream.JumpToBit(Offset * 32);
1665 // Do some checking if we are in debug mode.
1666 BitstreamEntry Entry = Stream.advance();
1667 assert(Entry.Kind == BitstreamEntry::SubBlock);
1668 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1670 // In NDEBUG mode ignore the output so we don't get an unused variable
1676 // Compute the delta between the bitcode indices in the VST (the word offset
1677 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1678 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1679 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1680 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1681 // just before entering the VST subblock because: 1) the EnterSubBlock
1682 // changes the AbbrevID width; 2) the VST block is nested within the same
1683 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1684 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1685 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1686 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1687 unsigned FuncBitcodeOffsetDelta =
1688 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1690 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1691 return error("Invalid record");
1693 SmallVector<uint64_t, 64> Record;
1695 Triple TT(TheModule->getTargetTriple());
1697 // Read all the records for this value table.
1698 SmallString<128> ValueName;
1700 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1702 switch (Entry.Kind) {
1703 case BitstreamEntry::SubBlock: // Handled for us already.
1704 case BitstreamEntry::Error:
1705 return error("Malformed block");
1706 case BitstreamEntry::EndBlock:
1708 Stream.JumpToBit(CurrentBit);
1709 return std::error_code();
1710 case BitstreamEntry::Record:
1711 // The interesting case.
1717 switch (Stream.readRecord(Entry.ID, Record)) {
1718 default: // Default behavior: unknown type.
1720 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1721 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1722 if (std::error_code EC = ValOrErr.getError())
1727 case bitc::VST_CODE_FNENTRY: {
1728 // VST_FNENTRY: [valueid, offset, namechar x N]
1729 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1730 if (std::error_code EC = ValOrErr.getError())
1732 Value *V = ValOrErr.get();
1734 auto *GO = dyn_cast<GlobalObject>(V);
1736 // If this is an alias, need to get the actual Function object
1737 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1738 auto *GA = dyn_cast<GlobalAlias>(V);
1740 GO = GA->getBaseObject();
1744 uint64_t FuncWordOffset = Record[1];
1745 Function *F = dyn_cast<Function>(GO);
1747 uint64_t FuncBitOffset = FuncWordOffset * 32;
1748 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1749 // Set the NextUnreadBit to point to the last function block.
1750 // Later when parsing is resumed after function materialization,
1751 // we can simply skip that last function block.
1752 if (FuncBitOffset > NextUnreadBit)
1753 NextUnreadBit = FuncBitOffset;
1756 case bitc::VST_CODE_BBENTRY: {
1757 if (convertToString(Record, 1, ValueName))
1758 return error("Invalid record");
1759 BasicBlock *BB = getBasicBlock(Record[0]);
1761 return error("Invalid record");
1763 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1771 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1773 std::error_code BitcodeReader::parseMetadata() {
1774 IsMetadataMaterialized = true;
1775 unsigned NextMDValueNo = MDValueList.size();
1777 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1778 return error("Invalid record");
1780 SmallVector<uint64_t, 64> Record;
1783 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1784 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1786 return getMD(ID - 1);
1789 auto getMDString = [&](unsigned ID) -> MDString *{
1790 // This requires that the ID is not really a forward reference. In
1791 // particular, the MDString must already have been resolved.
1792 return cast_or_null<MDString>(getMDOrNull(ID));
1795 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1796 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1798 // Read all the records.
1800 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1802 switch (Entry.Kind) {
1803 case BitstreamEntry::SubBlock: // Handled for us already.
1804 case BitstreamEntry::Error:
1805 return error("Malformed block");
1806 case BitstreamEntry::EndBlock:
1807 MDValueList.tryToResolveCycles();
1808 return std::error_code();
1809 case BitstreamEntry::Record:
1810 // The interesting case.
1816 unsigned Code = Stream.readRecord(Entry.ID, Record);
1817 bool IsDistinct = false;
1819 default: // Default behavior: ignore.
1821 case bitc::METADATA_NAME: {
1822 // Read name of the named metadata.
1823 SmallString<8> Name(Record.begin(), Record.end());
1825 Code = Stream.ReadCode();
1827 unsigned NextBitCode = Stream.readRecord(Code, Record);
1828 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1829 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1831 // Read named metadata elements.
1832 unsigned Size = Record.size();
1833 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1834 for (unsigned i = 0; i != Size; ++i) {
1835 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1837 return error("Invalid record");
1838 NMD->addOperand(MD);
1842 case bitc::METADATA_OLD_FN_NODE: {
1843 // FIXME: Remove in 4.0.
1844 // This is a LocalAsMetadata record, the only type of function-local
1846 if (Record.size() % 2 == 1)
1847 return error("Invalid record");
1849 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1850 // to be legal, but there's no upgrade path.
1851 auto dropRecord = [&] {
1852 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1854 if (Record.size() != 2) {
1859 Type *Ty = getTypeByID(Record[0]);
1860 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1865 MDValueList.assignValue(
1866 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1870 case bitc::METADATA_OLD_NODE: {
1871 // FIXME: Remove in 4.0.
1872 if (Record.size() % 2 == 1)
1873 return error("Invalid record");
1875 unsigned Size = Record.size();
1876 SmallVector<Metadata *, 8> Elts;
1877 for (unsigned i = 0; i != Size; i += 2) {
1878 Type *Ty = getTypeByID(Record[i]);
1880 return error("Invalid record");
1881 if (Ty->isMetadataTy())
1882 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1883 else if (!Ty->isVoidTy()) {
1885 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1886 assert(isa<ConstantAsMetadata>(MD) &&
1887 "Expected non-function-local metadata");
1890 Elts.push_back(nullptr);
1892 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1895 case bitc::METADATA_VALUE: {
1896 if (Record.size() != 2)
1897 return error("Invalid record");
1899 Type *Ty = getTypeByID(Record[0]);
1900 if (Ty->isMetadataTy() || Ty->isVoidTy())
1901 return error("Invalid record");
1903 MDValueList.assignValue(
1904 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1908 case bitc::METADATA_DISTINCT_NODE:
1911 case bitc::METADATA_NODE: {
1912 SmallVector<Metadata *, 8> Elts;
1913 Elts.reserve(Record.size());
1914 for (unsigned ID : Record)
1915 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1916 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1917 : MDNode::get(Context, Elts),
1921 case bitc::METADATA_LOCATION: {
1922 if (Record.size() != 5)
1923 return error("Invalid record");
1925 unsigned Line = Record[1];
1926 unsigned Column = Record[2];
1927 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1928 Metadata *InlinedAt =
1929 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1930 MDValueList.assignValue(
1931 GET_OR_DISTINCT(DILocation, Record[0],
1932 (Context, Line, Column, Scope, InlinedAt)),
1936 case bitc::METADATA_GENERIC_DEBUG: {
1937 if (Record.size() < 4)
1938 return error("Invalid record");
1940 unsigned Tag = Record[1];
1941 unsigned Version = Record[2];
1943 if (Tag >= 1u << 16 || Version != 0)
1944 return error("Invalid record");
1946 auto *Header = getMDString(Record[3]);
1947 SmallVector<Metadata *, 8> DwarfOps;
1948 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1949 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1951 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1952 (Context, Tag, Header, DwarfOps)),
1956 case bitc::METADATA_SUBRANGE: {
1957 if (Record.size() != 3)
1958 return error("Invalid record");
1960 MDValueList.assignValue(
1961 GET_OR_DISTINCT(DISubrange, Record[0],
1962 (Context, Record[1], unrotateSign(Record[2]))),
1966 case bitc::METADATA_ENUMERATOR: {
1967 if (Record.size() != 3)
1968 return error("Invalid record");
1970 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1971 (Context, unrotateSign(Record[1]),
1972 getMDString(Record[2]))),
1976 case bitc::METADATA_BASIC_TYPE: {
1977 if (Record.size() != 6)
1978 return error("Invalid record");
1980 MDValueList.assignValue(
1981 GET_OR_DISTINCT(DIBasicType, Record[0],
1982 (Context, Record[1], getMDString(Record[2]),
1983 Record[3], Record[4], Record[5])),
1987 case bitc::METADATA_DERIVED_TYPE: {
1988 if (Record.size() != 12)
1989 return error("Invalid record");
1991 MDValueList.assignValue(
1992 GET_OR_DISTINCT(DIDerivedType, Record[0],
1993 (Context, Record[1], getMDString(Record[2]),
1994 getMDOrNull(Record[3]), Record[4],
1995 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1996 Record[7], Record[8], Record[9], Record[10],
1997 getMDOrNull(Record[11]))),
2001 case bitc::METADATA_COMPOSITE_TYPE: {
2002 if (Record.size() != 16)
2003 return error("Invalid record");
2005 MDValueList.assignValue(
2006 GET_OR_DISTINCT(DICompositeType, Record[0],
2007 (Context, Record[1], getMDString(Record[2]),
2008 getMDOrNull(Record[3]), Record[4],
2009 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2010 Record[7], Record[8], Record[9], Record[10],
2011 getMDOrNull(Record[11]), Record[12],
2012 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2013 getMDString(Record[15]))),
2017 case bitc::METADATA_SUBROUTINE_TYPE: {
2018 if (Record.size() != 3)
2019 return error("Invalid record");
2021 MDValueList.assignValue(
2022 GET_OR_DISTINCT(DISubroutineType, Record[0],
2023 (Context, Record[1], getMDOrNull(Record[2]))),
2028 case bitc::METADATA_MODULE: {
2029 if (Record.size() != 6)
2030 return error("Invalid record");
2032 MDValueList.assignValue(
2033 GET_OR_DISTINCT(DIModule, Record[0],
2034 (Context, getMDOrNull(Record[1]),
2035 getMDString(Record[2]), getMDString(Record[3]),
2036 getMDString(Record[4]), getMDString(Record[5]))),
2041 case bitc::METADATA_FILE: {
2042 if (Record.size() != 3)
2043 return error("Invalid record");
2045 MDValueList.assignValue(
2046 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2047 getMDString(Record[2]))),
2051 case bitc::METADATA_COMPILE_UNIT: {
2052 if (Record.size() < 14 || Record.size() > 15)
2053 return error("Invalid record");
2055 // Ignore Record[1], which indicates whether this compile unit is
2056 // distinct. It's always distinct.
2057 MDValueList.assignValue(
2058 DICompileUnit::getDistinct(
2059 Context, Record[1], getMDOrNull(Record[2]),
2060 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2061 Record[6], getMDString(Record[7]), Record[8],
2062 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2063 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2064 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2068 case bitc::METADATA_SUBPROGRAM: {
2069 if (Record.size() != 19)
2070 return error("Invalid record");
2072 MDValueList.assignValue(
2075 Record[0] || Record[8], // All definitions should be distinct.
2076 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2077 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2078 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2079 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2080 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
2081 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
2085 case bitc::METADATA_LEXICAL_BLOCK: {
2086 if (Record.size() != 5)
2087 return error("Invalid record");
2089 MDValueList.assignValue(
2090 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2091 (Context, getMDOrNull(Record[1]),
2092 getMDOrNull(Record[2]), Record[3], Record[4])),
2096 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2097 if (Record.size() != 4)
2098 return error("Invalid record");
2100 MDValueList.assignValue(
2101 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2102 (Context, getMDOrNull(Record[1]),
2103 getMDOrNull(Record[2]), Record[3])),
2107 case bitc::METADATA_NAMESPACE: {
2108 if (Record.size() != 5)
2109 return error("Invalid record");
2111 MDValueList.assignValue(
2112 GET_OR_DISTINCT(DINamespace, Record[0],
2113 (Context, getMDOrNull(Record[1]),
2114 getMDOrNull(Record[2]), getMDString(Record[3]),
2119 case bitc::METADATA_TEMPLATE_TYPE: {
2120 if (Record.size() != 3)
2121 return error("Invalid record");
2123 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2125 (Context, getMDString(Record[1]),
2126 getMDOrNull(Record[2]))),
2130 case bitc::METADATA_TEMPLATE_VALUE: {
2131 if (Record.size() != 5)
2132 return error("Invalid record");
2134 MDValueList.assignValue(
2135 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2136 (Context, Record[1], getMDString(Record[2]),
2137 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2141 case bitc::METADATA_GLOBAL_VAR: {
2142 if (Record.size() != 11)
2143 return error("Invalid record");
2145 MDValueList.assignValue(
2146 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2147 (Context, getMDOrNull(Record[1]),
2148 getMDString(Record[2]), getMDString(Record[3]),
2149 getMDOrNull(Record[4]), Record[5],
2150 getMDOrNull(Record[6]), Record[7], Record[8],
2151 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2155 case bitc::METADATA_LOCAL_VAR: {
2156 // 10th field is for the obseleted 'inlinedAt:' field.
2157 if (Record.size() < 8 || Record.size() > 10)
2158 return error("Invalid record");
2160 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2161 // DW_TAG_arg_variable.
2162 bool HasTag = Record.size() > 8;
2163 MDValueList.assignValue(
2164 GET_OR_DISTINCT(DILocalVariable, Record[0],
2165 (Context, getMDOrNull(Record[1 + HasTag]),
2166 getMDString(Record[2 + HasTag]),
2167 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2168 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2169 Record[7 + HasTag])),
2173 case bitc::METADATA_EXPRESSION: {
2174 if (Record.size() < 1)
2175 return error("Invalid record");
2177 MDValueList.assignValue(
2178 GET_OR_DISTINCT(DIExpression, Record[0],
2179 (Context, makeArrayRef(Record).slice(1))),
2183 case bitc::METADATA_OBJC_PROPERTY: {
2184 if (Record.size() != 8)
2185 return error("Invalid record");
2187 MDValueList.assignValue(
2188 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2189 (Context, getMDString(Record[1]),
2190 getMDOrNull(Record[2]), Record[3],
2191 getMDString(Record[4]), getMDString(Record[5]),
2192 Record[6], getMDOrNull(Record[7]))),
2196 case bitc::METADATA_IMPORTED_ENTITY: {
2197 if (Record.size() != 6)
2198 return error("Invalid record");
2200 MDValueList.assignValue(
2201 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2202 (Context, Record[1], getMDOrNull(Record[2]),
2203 getMDOrNull(Record[3]), Record[4],
2204 getMDString(Record[5]))),
2208 case bitc::METADATA_STRING: {
2209 std::string String(Record.begin(), Record.end());
2210 llvm::UpgradeMDStringConstant(String);
2211 Metadata *MD = MDString::get(Context, String);
2212 MDValueList.assignValue(MD, NextMDValueNo++);
2215 case bitc::METADATA_KIND: {
2216 if (Record.size() < 2)
2217 return error("Invalid record");
2219 unsigned Kind = Record[0];
2220 SmallString<8> Name(Record.begin()+1, Record.end());
2222 unsigned NewKind = TheModule->getMDKindID(Name.str());
2223 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2224 return error("Conflicting METADATA_KIND records");
2229 #undef GET_OR_DISTINCT
2232 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2234 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2239 // There is no such thing as -0 with integers. "-0" really means MININT.
2243 /// Resolve all of the initializers for global values and aliases that we can.
2244 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2245 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2246 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2247 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2248 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2249 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2251 GlobalInitWorklist.swap(GlobalInits);
2252 AliasInitWorklist.swap(AliasInits);
2253 FunctionPrefixWorklist.swap(FunctionPrefixes);
2254 FunctionPrologueWorklist.swap(FunctionPrologues);
2255 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2257 while (!GlobalInitWorklist.empty()) {
2258 unsigned ValID = GlobalInitWorklist.back().second;
2259 if (ValID >= ValueList.size()) {
2260 // Not ready to resolve this yet, it requires something later in the file.
2261 GlobalInits.push_back(GlobalInitWorklist.back());
2263 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2264 GlobalInitWorklist.back().first->setInitializer(C);
2266 return error("Expected a constant");
2268 GlobalInitWorklist.pop_back();
2271 while (!AliasInitWorklist.empty()) {
2272 unsigned ValID = AliasInitWorklist.back().second;
2273 if (ValID >= ValueList.size()) {
2274 AliasInits.push_back(AliasInitWorklist.back());
2276 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2278 return error("Expected a constant");
2279 GlobalAlias *Alias = AliasInitWorklist.back().first;
2280 if (C->getType() != Alias->getType())
2281 return error("Alias and aliasee types don't match");
2282 Alias->setAliasee(C);
2284 AliasInitWorklist.pop_back();
2287 while (!FunctionPrefixWorklist.empty()) {
2288 unsigned ValID = FunctionPrefixWorklist.back().second;
2289 if (ValID >= ValueList.size()) {
2290 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2292 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2293 FunctionPrefixWorklist.back().first->setPrefixData(C);
2295 return error("Expected a constant");
2297 FunctionPrefixWorklist.pop_back();
2300 while (!FunctionPrologueWorklist.empty()) {
2301 unsigned ValID = FunctionPrologueWorklist.back().second;
2302 if (ValID >= ValueList.size()) {
2303 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2305 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2306 FunctionPrologueWorklist.back().first->setPrologueData(C);
2308 return error("Expected a constant");
2310 FunctionPrologueWorklist.pop_back();
2313 while (!FunctionPersonalityFnWorklist.empty()) {
2314 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2315 if (ValID >= ValueList.size()) {
2316 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2318 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2319 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2321 return error("Expected a constant");
2323 FunctionPersonalityFnWorklist.pop_back();
2326 return std::error_code();
2329 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2330 SmallVector<uint64_t, 8> Words(Vals.size());
2331 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2332 BitcodeReader::decodeSignRotatedValue);
2334 return APInt(TypeBits, Words);
2337 std::error_code BitcodeReader::parseConstants() {
2338 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2339 return error("Invalid record");
2341 SmallVector<uint64_t, 64> Record;
2343 // Read all the records for this value table.
2344 Type *CurTy = Type::getInt32Ty(Context);
2345 unsigned NextCstNo = ValueList.size();
2347 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2349 switch (Entry.Kind) {
2350 case BitstreamEntry::SubBlock: // Handled for us already.
2351 case BitstreamEntry::Error:
2352 return error("Malformed block");
2353 case BitstreamEntry::EndBlock:
2354 if (NextCstNo != ValueList.size())
2355 return error("Invalid ronstant reference");
2357 // Once all the constants have been read, go through and resolve forward
2359 ValueList.resolveConstantForwardRefs();
2360 return std::error_code();
2361 case BitstreamEntry::Record:
2362 // The interesting case.
2369 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2371 default: // Default behavior: unknown constant
2372 case bitc::CST_CODE_UNDEF: // UNDEF
2373 V = UndefValue::get(CurTy);
2375 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2377 return error("Invalid record");
2378 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2379 return error("Invalid record");
2380 CurTy = TypeList[Record[0]];
2381 continue; // Skip the ValueList manipulation.
2382 case bitc::CST_CODE_NULL: // NULL
2383 V = Constant::getNullValue(CurTy);
2385 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2386 if (!CurTy->isIntegerTy() || Record.empty())
2387 return error("Invalid record");
2388 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2390 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2391 if (!CurTy->isIntegerTy() || Record.empty())
2392 return error("Invalid record");
2395 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2396 V = ConstantInt::get(Context, VInt);
2400 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2402 return error("Invalid record");
2403 if (CurTy->isHalfTy())
2404 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2405 APInt(16, (uint16_t)Record[0])));
2406 else if (CurTy->isFloatTy())
2407 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2408 APInt(32, (uint32_t)Record[0])));
2409 else if (CurTy->isDoubleTy())
2410 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2411 APInt(64, Record[0])));
2412 else if (CurTy->isX86_FP80Ty()) {
2413 // Bits are not stored the same way as a normal i80 APInt, compensate.
2414 uint64_t Rearrange[2];
2415 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2416 Rearrange[1] = Record[0] >> 48;
2417 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2418 APInt(80, Rearrange)));
2419 } else if (CurTy->isFP128Ty())
2420 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2421 APInt(128, Record)));
2422 else if (CurTy->isPPC_FP128Ty())
2423 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2424 APInt(128, Record)));
2426 V = UndefValue::get(CurTy);
2430 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2432 return error("Invalid record");
2434 unsigned Size = Record.size();
2435 SmallVector<Constant*, 16> Elts;
2437 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2438 for (unsigned i = 0; i != Size; ++i)
2439 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2440 STy->getElementType(i)));
2441 V = ConstantStruct::get(STy, Elts);
2442 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2443 Type *EltTy = ATy->getElementType();
2444 for (unsigned i = 0; i != Size; ++i)
2445 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2446 V = ConstantArray::get(ATy, Elts);
2447 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2448 Type *EltTy = VTy->getElementType();
2449 for (unsigned i = 0; i != Size; ++i)
2450 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2451 V = ConstantVector::get(Elts);
2453 V = UndefValue::get(CurTy);
2457 case bitc::CST_CODE_STRING: // STRING: [values]
2458 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2460 return error("Invalid record");
2462 SmallString<16> Elts(Record.begin(), Record.end());
2463 V = ConstantDataArray::getString(Context, Elts,
2464 BitCode == bitc::CST_CODE_CSTRING);
2467 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2469 return error("Invalid record");
2471 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2472 unsigned Size = Record.size();
2474 if (EltTy->isIntegerTy(8)) {
2475 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2476 if (isa<VectorType>(CurTy))
2477 V = ConstantDataVector::get(Context, Elts);
2479 V = ConstantDataArray::get(Context, Elts);
2480 } else if (EltTy->isIntegerTy(16)) {
2481 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2482 if (isa<VectorType>(CurTy))
2483 V = ConstantDataVector::get(Context, Elts);
2485 V = ConstantDataArray::get(Context, Elts);
2486 } else if (EltTy->isIntegerTy(32)) {
2487 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2488 if (isa<VectorType>(CurTy))
2489 V = ConstantDataVector::get(Context, Elts);
2491 V = ConstantDataArray::get(Context, Elts);
2492 } else if (EltTy->isIntegerTy(64)) {
2493 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2494 if (isa<VectorType>(CurTy))
2495 V = ConstantDataVector::get(Context, Elts);
2497 V = ConstantDataArray::get(Context, Elts);
2498 } else if (EltTy->isFloatTy()) {
2499 SmallVector<float, 16> Elts(Size);
2500 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2501 if (isa<VectorType>(CurTy))
2502 V = ConstantDataVector::get(Context, Elts);
2504 V = ConstantDataArray::get(Context, Elts);
2505 } else if (EltTy->isDoubleTy()) {
2506 SmallVector<double, 16> Elts(Size);
2507 std::transform(Record.begin(), Record.end(), Elts.begin(),
2509 if (isa<VectorType>(CurTy))
2510 V = ConstantDataVector::get(Context, Elts);
2512 V = ConstantDataArray::get(Context, Elts);
2514 return error("Invalid type for value");
2519 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2520 if (Record.size() < 3)
2521 return error("Invalid record");
2522 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2524 V = UndefValue::get(CurTy); // Unknown binop.
2526 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2527 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2529 if (Record.size() >= 4) {
2530 if (Opc == Instruction::Add ||
2531 Opc == Instruction::Sub ||
2532 Opc == Instruction::Mul ||
2533 Opc == Instruction::Shl) {
2534 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2535 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2536 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2537 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2538 } else if (Opc == Instruction::SDiv ||
2539 Opc == Instruction::UDiv ||
2540 Opc == Instruction::LShr ||
2541 Opc == Instruction::AShr) {
2542 if (Record[3] & (1 << bitc::PEO_EXACT))
2543 Flags |= SDivOperator::IsExact;
2546 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2550 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2551 if (Record.size() < 3)
2552 return error("Invalid record");
2553 int Opc = getDecodedCastOpcode(Record[0]);
2555 V = UndefValue::get(CurTy); // Unknown cast.
2557 Type *OpTy = getTypeByID(Record[1]);
2559 return error("Invalid record");
2560 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2561 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2562 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2566 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2567 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2569 Type *PointeeType = nullptr;
2570 if (Record.size() % 2)
2571 PointeeType = getTypeByID(Record[OpNum++]);
2572 SmallVector<Constant*, 16> Elts;
2573 while (OpNum != Record.size()) {
2574 Type *ElTy = getTypeByID(Record[OpNum++]);
2576 return error("Invalid record");
2577 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2582 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2584 return error("Explicit gep operator type does not match pointee type "
2585 "of pointer operand");
2587 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2588 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2590 bitc::CST_CODE_CE_INBOUNDS_GEP);
2593 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2594 if (Record.size() < 3)
2595 return error("Invalid record");
2597 Type *SelectorTy = Type::getInt1Ty(Context);
2599 // The selector might be an i1 or an <n x i1>
2600 // Get the type from the ValueList before getting a forward ref.
2601 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2602 if (Value *V = ValueList[Record[0]])
2603 if (SelectorTy != V->getType())
2604 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2606 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2608 ValueList.getConstantFwdRef(Record[1],CurTy),
2609 ValueList.getConstantFwdRef(Record[2],CurTy));
2612 case bitc::CST_CODE_CE_EXTRACTELT
2613 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2614 if (Record.size() < 3)
2615 return error("Invalid record");
2617 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2619 return error("Invalid record");
2620 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2621 Constant *Op1 = nullptr;
2622 if (Record.size() == 4) {
2623 Type *IdxTy = getTypeByID(Record[2]);
2625 return error("Invalid record");
2626 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2627 } else // TODO: Remove with llvm 4.0
2628 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2630 return error("Invalid record");
2631 V = ConstantExpr::getExtractElement(Op0, Op1);
2634 case bitc::CST_CODE_CE_INSERTELT
2635 : { // CE_INSERTELT: [opval, opval, opty, opval]
2636 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2637 if (Record.size() < 3 || !OpTy)
2638 return error("Invalid record");
2639 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2640 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2641 OpTy->getElementType());
2642 Constant *Op2 = nullptr;
2643 if (Record.size() == 4) {
2644 Type *IdxTy = getTypeByID(Record[2]);
2646 return error("Invalid record");
2647 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2648 } else // TODO: Remove with llvm 4.0
2649 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2651 return error("Invalid record");
2652 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2655 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2656 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2657 if (Record.size() < 3 || !OpTy)
2658 return error("Invalid record");
2659 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2660 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2661 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2662 OpTy->getNumElements());
2663 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2664 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2667 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2668 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2670 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2671 if (Record.size() < 4 || !RTy || !OpTy)
2672 return error("Invalid record");
2673 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2674 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2675 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2676 RTy->getNumElements());
2677 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2678 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2681 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2682 if (Record.size() < 4)
2683 return error("Invalid record");
2684 Type *OpTy = getTypeByID(Record[0]);
2686 return error("Invalid record");
2687 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2688 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2690 if (OpTy->isFPOrFPVectorTy())
2691 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2693 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2696 // This maintains backward compatibility, pre-asm dialect keywords.
2697 // FIXME: Remove with the 4.0 release.
2698 case bitc::CST_CODE_INLINEASM_OLD: {
2699 if (Record.size() < 2)
2700 return error("Invalid record");
2701 std::string AsmStr, ConstrStr;
2702 bool HasSideEffects = Record[0] & 1;
2703 bool IsAlignStack = Record[0] >> 1;
2704 unsigned AsmStrSize = Record[1];
2705 if (2+AsmStrSize >= Record.size())
2706 return error("Invalid record");
2707 unsigned ConstStrSize = Record[2+AsmStrSize];
2708 if (3+AsmStrSize+ConstStrSize > Record.size())
2709 return error("Invalid record");
2711 for (unsigned i = 0; i != AsmStrSize; ++i)
2712 AsmStr += (char)Record[2+i];
2713 for (unsigned i = 0; i != ConstStrSize; ++i)
2714 ConstrStr += (char)Record[3+AsmStrSize+i];
2715 PointerType *PTy = cast<PointerType>(CurTy);
2716 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2717 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2720 // This version adds support for the asm dialect keywords (e.g.,
2722 case bitc::CST_CODE_INLINEASM: {
2723 if (Record.size() < 2)
2724 return error("Invalid record");
2725 std::string AsmStr, ConstrStr;
2726 bool HasSideEffects = Record[0] & 1;
2727 bool IsAlignStack = (Record[0] >> 1) & 1;
2728 unsigned AsmDialect = Record[0] >> 2;
2729 unsigned AsmStrSize = Record[1];
2730 if (2+AsmStrSize >= Record.size())
2731 return error("Invalid record");
2732 unsigned ConstStrSize = Record[2+AsmStrSize];
2733 if (3+AsmStrSize+ConstStrSize > Record.size())
2734 return error("Invalid record");
2736 for (unsigned i = 0; i != AsmStrSize; ++i)
2737 AsmStr += (char)Record[2+i];
2738 for (unsigned i = 0; i != ConstStrSize; ++i)
2739 ConstrStr += (char)Record[3+AsmStrSize+i];
2740 PointerType *PTy = cast<PointerType>(CurTy);
2741 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2742 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2743 InlineAsm::AsmDialect(AsmDialect));
2746 case bitc::CST_CODE_BLOCKADDRESS:{
2747 if (Record.size() < 3)
2748 return error("Invalid record");
2749 Type *FnTy = getTypeByID(Record[0]);
2751 return error("Invalid record");
2753 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2755 return error("Invalid record");
2757 // Don't let Fn get dematerialized.
2758 BlockAddressesTaken.insert(Fn);
2760 // If the function is already parsed we can insert the block address right
2763 unsigned BBID = Record[2];
2765 // Invalid reference to entry block.
2766 return error("Invalid ID");
2768 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2769 for (size_t I = 0, E = BBID; I != E; ++I) {
2771 return error("Invalid ID");
2776 // Otherwise insert a placeholder and remember it so it can be inserted
2777 // when the function is parsed.
2778 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2780 BasicBlockFwdRefQueue.push_back(Fn);
2781 if (FwdBBs.size() < BBID + 1)
2782 FwdBBs.resize(BBID + 1);
2784 FwdBBs[BBID] = BasicBlock::Create(Context);
2787 V = BlockAddress::get(Fn, BB);
2792 if (ValueList.assignValue(V, NextCstNo))
2793 return error("Invalid forward reference");
2798 std::error_code BitcodeReader::parseUseLists() {
2799 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2800 return error("Invalid record");
2802 // Read all the records.
2803 SmallVector<uint64_t, 64> Record;
2805 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2807 switch (Entry.Kind) {
2808 case BitstreamEntry::SubBlock: // Handled for us already.
2809 case BitstreamEntry::Error:
2810 return error("Malformed block");
2811 case BitstreamEntry::EndBlock:
2812 return std::error_code();
2813 case BitstreamEntry::Record:
2814 // The interesting case.
2818 // Read a use list record.
2821 switch (Stream.readRecord(Entry.ID, Record)) {
2822 default: // Default behavior: unknown type.
2824 case bitc::USELIST_CODE_BB:
2827 case bitc::USELIST_CODE_DEFAULT: {
2828 unsigned RecordLength = Record.size();
2829 if (RecordLength < 3)
2830 // Records should have at least an ID and two indexes.
2831 return error("Invalid record");
2832 unsigned ID = Record.back();
2837 assert(ID < FunctionBBs.size() && "Basic block not found");
2838 V = FunctionBBs[ID];
2841 unsigned NumUses = 0;
2842 SmallDenseMap<const Use *, unsigned, 16> Order;
2843 for (const Use &U : V->uses()) {
2844 if (++NumUses > Record.size())
2846 Order[&U] = Record[NumUses - 1];
2848 if (Order.size() != Record.size() || NumUses > Record.size())
2849 // Mismatches can happen if the functions are being materialized lazily
2850 // (out-of-order), or a value has been upgraded.
2853 V->sortUseList([&](const Use &L, const Use &R) {
2854 return Order.lookup(&L) < Order.lookup(&R);
2862 /// When we see the block for metadata, remember where it is and then skip it.
2863 /// This lets us lazily deserialize the metadata.
2864 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2865 // Save the current stream state.
2866 uint64_t CurBit = Stream.GetCurrentBitNo();
2867 DeferredMetadataInfo.push_back(CurBit);
2869 // Skip over the block for now.
2870 if (Stream.SkipBlock())
2871 return error("Invalid record");
2872 return std::error_code();
2875 std::error_code BitcodeReader::materializeMetadata() {
2876 for (uint64_t BitPos : DeferredMetadataInfo) {
2877 // Move the bit stream to the saved position.
2878 Stream.JumpToBit(BitPos);
2879 if (std::error_code EC = parseMetadata())
2882 DeferredMetadataInfo.clear();
2883 return std::error_code();
2886 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2888 /// When we see the block for a function body, remember where it is and then
2889 /// skip it. This lets us lazily deserialize the functions.
2890 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2891 // Get the function we are talking about.
2892 if (FunctionsWithBodies.empty())
2893 return error("Insufficient function protos");
2895 Function *Fn = FunctionsWithBodies.back();
2896 FunctionsWithBodies.pop_back();
2898 // Save the current stream state.
2899 uint64_t CurBit = Stream.GetCurrentBitNo();
2900 DeferredFunctionInfo[Fn] = CurBit;
2902 // Skip over the function block for now.
2903 if (Stream.SkipBlock())
2904 return error("Invalid record");
2905 return std::error_code();
2908 std::error_code BitcodeReader::globalCleanup() {
2909 // Patch the initializers for globals and aliases up.
2910 resolveGlobalAndAliasInits();
2911 if (!GlobalInits.empty() || !AliasInits.empty())
2912 return error("Malformed global initializer set");
2914 // Look for intrinsic functions which need to be upgraded at some point
2915 for (Function &F : *TheModule) {
2917 if (UpgradeIntrinsicFunction(&F, NewFn))
2918 UpgradedIntrinsics[&F] = NewFn;
2921 // Look for global variables which need to be renamed.
2922 for (GlobalVariable &GV : TheModule->globals())
2923 UpgradeGlobalVariable(&GV);
2925 // Force deallocation of memory for these vectors to favor the client that
2926 // want lazy deserialization.
2927 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2928 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2929 return std::error_code();
2932 std::error_code BitcodeReader::parseModule(bool Resume,
2933 bool ShouldLazyLoadMetadata) {
2935 Stream.JumpToBit(NextUnreadBit);
2936 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2937 return error("Invalid record");
2939 SmallVector<uint64_t, 64> Record;
2940 std::vector<std::string> SectionTable;
2941 std::vector<std::string> GCTable;
2943 // Read all the records for this module.
2945 BitstreamEntry Entry = Stream.advance();
2947 switch (Entry.Kind) {
2948 case BitstreamEntry::Error:
2949 return error("Malformed block");
2950 case BitstreamEntry::EndBlock:
2951 return globalCleanup();
2953 case BitstreamEntry::SubBlock:
2955 default: // Skip unknown content.
2956 if (Stream.SkipBlock())
2957 return error("Invalid record");
2959 case bitc::BLOCKINFO_BLOCK_ID:
2960 if (Stream.ReadBlockInfoBlock())
2961 return error("Malformed block");
2963 case bitc::PARAMATTR_BLOCK_ID:
2964 if (std::error_code EC = parseAttributeBlock())
2967 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2968 if (std::error_code EC = parseAttributeGroupBlock())
2971 case bitc::TYPE_BLOCK_ID_NEW:
2972 if (std::error_code EC = parseTypeTable())
2975 case bitc::VALUE_SYMTAB_BLOCK_ID:
2976 if (!SeenValueSymbolTable) {
2977 // Either this is an old form VST without function index and an
2978 // associated VST forward declaration record (which would have caused
2979 // the VST to be jumped to and parsed before it was encountered
2980 // normally in the stream), or there were no function blocks to
2981 // trigger an earlier parsing of the VST.
2982 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
2983 if (std::error_code EC = parseValueSymbolTable())
2985 SeenValueSymbolTable = true;
2987 // We must have had a VST forward declaration record, which caused
2988 // the parser to jump to and parse the VST earlier.
2989 assert(VSTOffset > 0);
2990 if (Stream.SkipBlock())
2991 return error("Invalid record");
2994 case bitc::CONSTANTS_BLOCK_ID:
2995 if (std::error_code EC = parseConstants())
2997 if (std::error_code EC = resolveGlobalAndAliasInits())
3000 case bitc::METADATA_BLOCK_ID:
3001 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3002 if (std::error_code EC = rememberAndSkipMetadata())
3006 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3007 if (std::error_code EC = parseMetadata())
3010 case bitc::FUNCTION_BLOCK_ID:
3011 // If this is the first function body we've seen, reverse the
3012 // FunctionsWithBodies list.
3013 if (!SeenFirstFunctionBody) {
3014 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3015 if (std::error_code EC = globalCleanup())
3017 SeenFirstFunctionBody = true;
3020 if (VSTOffset > 0) {
3021 // If we have a VST forward declaration record, make sure we
3022 // parse the VST now if we haven't already. It is needed to
3023 // set up the DeferredFunctionInfo vector for lazy reading.
3024 if (!SeenValueSymbolTable) {
3025 if (std::error_code EC =
3026 BitcodeReader::parseValueSymbolTable(VSTOffset))
3028 SeenValueSymbolTable = true;
3029 return std::error_code();
3031 // If we have a VST forward declaration record, but have already
3032 // parsed the VST (just above, when the first function body was
3033 // encountered here), then we are resuming the parse after
3034 // materializing functions. The NextUnreadBit points to the start
3035 // of the last function block recorded in the VST (set when
3036 // parsing the VST function entries). Skip it.
3037 if (Stream.SkipBlock())
3038 return error("Invalid record");
3043 // Support older bitcode files that did not have the function
3044 // index in the VST, nor a VST forward declaration record.
3045 // Build the DeferredFunctionInfo vector on the fly.
3046 if (std::error_code EC = rememberAndSkipFunctionBody())
3048 // Suspend parsing when we reach the function bodies. Subsequent
3049 // materialization calls will resume it when necessary. If the bitcode
3050 // file is old, the symbol table will be at the end instead and will not
3051 // have been seen yet. In this case, just finish the parse now.
3052 if (SeenValueSymbolTable) {
3053 NextUnreadBit = Stream.GetCurrentBitNo();
3054 return std::error_code();
3057 case bitc::USELIST_BLOCK_ID:
3058 if (std::error_code EC = parseUseLists())
3061 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3062 if (std::error_code EC = parseOperandBundleTags())
3068 case BitstreamEntry::Record:
3069 // The interesting case.
3075 auto BitCode = Stream.readRecord(Entry.ID, Record);
3077 default: break; // Default behavior, ignore unknown content.
3078 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3079 if (Record.size() < 1)
3080 return error("Invalid record");
3081 // Only version #0 and #1 are supported so far.
3082 unsigned module_version = Record[0];
3083 switch (module_version) {
3085 return error("Invalid value");
3087 UseRelativeIDs = false;
3090 UseRelativeIDs = true;
3095 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3097 if (convertToString(Record, 0, S))
3098 return error("Invalid record");
3099 TheModule->setTargetTriple(S);
3102 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3104 if (convertToString(Record, 0, S))
3105 return error("Invalid record");
3106 TheModule->setDataLayout(S);
3109 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3111 if (convertToString(Record, 0, S))
3112 return error("Invalid record");
3113 TheModule->setModuleInlineAsm(S);
3116 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3117 // FIXME: Remove in 4.0.
3119 if (convertToString(Record, 0, S))
3120 return error("Invalid record");
3124 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3126 if (convertToString(Record, 0, S))
3127 return error("Invalid record");
3128 SectionTable.push_back(S);
3131 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3133 if (convertToString(Record, 0, S))
3134 return error("Invalid record");
3135 GCTable.push_back(S);
3138 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3139 if (Record.size() < 2)
3140 return error("Invalid record");
3141 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3142 unsigned ComdatNameSize = Record[1];
3143 std::string ComdatName;
3144 ComdatName.reserve(ComdatNameSize);
3145 for (unsigned i = 0; i != ComdatNameSize; ++i)
3146 ComdatName += (char)Record[2 + i];
3147 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3148 C->setSelectionKind(SK);
3149 ComdatList.push_back(C);
3152 // GLOBALVAR: [pointer type, isconst, initid,
3153 // linkage, alignment, section, visibility, threadlocal,
3154 // unnamed_addr, externally_initialized, dllstorageclass,
3156 case bitc::MODULE_CODE_GLOBALVAR: {
3157 if (Record.size() < 6)
3158 return error("Invalid record");
3159 Type *Ty = getTypeByID(Record[0]);
3161 return error("Invalid record");
3162 bool isConstant = Record[1] & 1;
3163 bool explicitType = Record[1] & 2;
3164 unsigned AddressSpace;
3166 AddressSpace = Record[1] >> 2;
3168 if (!Ty->isPointerTy())
3169 return error("Invalid type for value");
3170 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3171 Ty = cast<PointerType>(Ty)->getElementType();
3174 uint64_t RawLinkage = Record[3];
3175 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3177 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3179 std::string Section;
3181 if (Record[5]-1 >= SectionTable.size())
3182 return error("Invalid ID");
3183 Section = SectionTable[Record[5]-1];
3185 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3186 // Local linkage must have default visibility.
3187 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3188 // FIXME: Change to an error if non-default in 4.0.
3189 Visibility = getDecodedVisibility(Record[6]);
3191 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3192 if (Record.size() > 7)
3193 TLM = getDecodedThreadLocalMode(Record[7]);
3195 bool UnnamedAddr = false;
3196 if (Record.size() > 8)
3197 UnnamedAddr = Record[8];
3199 bool ExternallyInitialized = false;
3200 if (Record.size() > 9)
3201 ExternallyInitialized = Record[9];
3203 GlobalVariable *NewGV =
3204 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3205 TLM, AddressSpace, ExternallyInitialized);
3206 NewGV->setAlignment(Alignment);
3207 if (!Section.empty())
3208 NewGV->setSection(Section);
3209 NewGV->setVisibility(Visibility);
3210 NewGV->setUnnamedAddr(UnnamedAddr);
3212 if (Record.size() > 10)
3213 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3215 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3217 ValueList.push_back(NewGV);
3219 // Remember which value to use for the global initializer.
3220 if (unsigned InitID = Record[2])
3221 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3223 if (Record.size() > 11) {
3224 if (unsigned ComdatID = Record[11]) {
3225 if (ComdatID > ComdatList.size())
3226 return error("Invalid global variable comdat ID");
3227 NewGV->setComdat(ComdatList[ComdatID - 1]);
3229 } else if (hasImplicitComdat(RawLinkage)) {
3230 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3234 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3235 // alignment, section, visibility, gc, unnamed_addr,
3236 // prologuedata, dllstorageclass, comdat, prefixdata]
3237 case bitc::MODULE_CODE_FUNCTION: {
3238 if (Record.size() < 8)
3239 return error("Invalid record");
3240 Type *Ty = getTypeByID(Record[0]);
3242 return error("Invalid record");
3243 if (auto *PTy = dyn_cast<PointerType>(Ty))
3244 Ty = PTy->getElementType();
3245 auto *FTy = dyn_cast<FunctionType>(Ty);
3247 return error("Invalid type for value");
3249 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3252 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
3253 bool isProto = Record[2];
3254 uint64_t RawLinkage = Record[3];
3255 Func->setLinkage(getDecodedLinkage(RawLinkage));
3256 Func->setAttributes(getAttributes(Record[4]));
3259 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3261 Func->setAlignment(Alignment);
3263 if (Record[6]-1 >= SectionTable.size())
3264 return error("Invalid ID");
3265 Func->setSection(SectionTable[Record[6]-1]);
3267 // Local linkage must have default visibility.
3268 if (!Func->hasLocalLinkage())
3269 // FIXME: Change to an error if non-default in 4.0.
3270 Func->setVisibility(getDecodedVisibility(Record[7]));
3271 if (Record.size() > 8 && Record[8]) {
3272 if (Record[8]-1 >= GCTable.size())
3273 return error("Invalid ID");
3274 Func->setGC(GCTable[Record[8]-1].c_str());
3276 bool UnnamedAddr = false;
3277 if (Record.size() > 9)
3278 UnnamedAddr = Record[9];
3279 Func->setUnnamedAddr(UnnamedAddr);
3280 if (Record.size() > 10 && Record[10] != 0)
3281 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3283 if (Record.size() > 11)
3284 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3286 upgradeDLLImportExportLinkage(Func, RawLinkage);
3288 if (Record.size() > 12) {
3289 if (unsigned ComdatID = Record[12]) {
3290 if (ComdatID > ComdatList.size())
3291 return error("Invalid function comdat ID");
3292 Func->setComdat(ComdatList[ComdatID - 1]);
3294 } else if (hasImplicitComdat(RawLinkage)) {
3295 Func->setComdat(reinterpret_cast<Comdat *>(1));
3298 if (Record.size() > 13 && Record[13] != 0)
3299 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3301 if (Record.size() > 14 && Record[14] != 0)
3302 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3304 ValueList.push_back(Func);
3306 // If this is a function with a body, remember the prototype we are
3307 // creating now, so that we can match up the body with them later.
3309 Func->setIsMaterializable(true);
3310 FunctionsWithBodies.push_back(Func);
3311 DeferredFunctionInfo[Func] = 0;
3315 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3316 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3317 case bitc::MODULE_CODE_ALIAS:
3318 case bitc::MODULE_CODE_ALIAS_OLD: {
3319 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3320 if (Record.size() < (3 + (unsigned)NewRecord))
3321 return error("Invalid record");
3323 Type *Ty = getTypeByID(Record[OpNum++]);
3325 return error("Invalid record");
3329 auto *PTy = dyn_cast<PointerType>(Ty);
3331 return error("Invalid type for value");
3332 Ty = PTy->getElementType();
3333 AddrSpace = PTy->getAddressSpace();
3335 AddrSpace = Record[OpNum++];
3338 auto Val = Record[OpNum++];
3339 auto Linkage = Record[OpNum++];
3340 auto *NewGA = GlobalAlias::create(
3341 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3342 // Old bitcode files didn't have visibility field.
3343 // Local linkage must have default visibility.
3344 if (OpNum != Record.size()) {
3345 auto VisInd = OpNum++;
3346 if (!NewGA->hasLocalLinkage())
3347 // FIXME: Change to an error if non-default in 4.0.
3348 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3350 if (OpNum != Record.size())
3351 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3353 upgradeDLLImportExportLinkage(NewGA, Linkage);
3354 if (OpNum != Record.size())
3355 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3356 if (OpNum != Record.size())
3357 NewGA->setUnnamedAddr(Record[OpNum++]);
3358 ValueList.push_back(NewGA);
3359 AliasInits.push_back(std::make_pair(NewGA, Val));
3362 /// MODULE_CODE_PURGEVALS: [numvals]
3363 case bitc::MODULE_CODE_PURGEVALS:
3364 // Trim down the value list to the specified size.
3365 if (Record.size() < 1 || Record[0] > ValueList.size())
3366 return error("Invalid record");
3367 ValueList.shrinkTo(Record[0]);
3369 /// MODULE_CODE_VSTOFFSET: [offset]
3370 case bitc::MODULE_CODE_VSTOFFSET:
3371 if (Record.size() < 1)
3372 return error("Invalid record");
3373 VSTOffset = Record[0];
3381 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3382 Module *M, bool ShouldLazyLoadMetadata) {
3385 if (std::error_code EC = initStream(std::move(Streamer)))
3388 // Sniff for the signature.
3389 if (Stream.Read(8) != 'B' ||
3390 Stream.Read(8) != 'C' ||
3391 Stream.Read(4) != 0x0 ||
3392 Stream.Read(4) != 0xC ||
3393 Stream.Read(4) != 0xE ||
3394 Stream.Read(4) != 0xD)
3395 return error("Invalid bitcode signature");
3397 // We expect a number of well-defined blocks, though we don't necessarily
3398 // need to understand them all.
3400 if (Stream.AtEndOfStream()) {
3401 // We didn't really read a proper Module.
3402 return error("Malformed IR file");
3405 BitstreamEntry Entry =
3406 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3408 if (Entry.Kind != BitstreamEntry::SubBlock)
3409 return error("Malformed block");
3411 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3412 return parseModule(false, ShouldLazyLoadMetadata);
3414 if (Stream.SkipBlock())
3415 return error("Invalid record");
3419 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3420 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3421 return error("Invalid record");
3423 SmallVector<uint64_t, 64> Record;
3426 // Read all the records for this module.
3428 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3430 switch (Entry.Kind) {
3431 case BitstreamEntry::SubBlock: // Handled for us already.
3432 case BitstreamEntry::Error:
3433 return error("Malformed block");
3434 case BitstreamEntry::EndBlock:
3436 case BitstreamEntry::Record:
3437 // The interesting case.
3442 switch (Stream.readRecord(Entry.ID, Record)) {
3443 default: break; // Default behavior, ignore unknown content.
3444 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3446 if (convertToString(Record, 0, S))
3447 return error("Invalid record");
3454 llvm_unreachable("Exit infinite loop");
3457 ErrorOr<std::string> BitcodeReader::parseTriple() {
3458 if (std::error_code EC = initStream(nullptr))
3461 // Sniff for the signature.
3462 if (Stream.Read(8) != 'B' ||
3463 Stream.Read(8) != 'C' ||
3464 Stream.Read(4) != 0x0 ||
3465 Stream.Read(4) != 0xC ||
3466 Stream.Read(4) != 0xE ||
3467 Stream.Read(4) != 0xD)
3468 return error("Invalid bitcode signature");
3470 // We expect a number of well-defined blocks, though we don't necessarily
3471 // need to understand them all.
3473 BitstreamEntry Entry = Stream.advance();
3475 switch (Entry.Kind) {
3476 case BitstreamEntry::Error:
3477 return error("Malformed block");
3478 case BitstreamEntry::EndBlock:
3479 return std::error_code();
3481 case BitstreamEntry::SubBlock:
3482 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3483 return parseModuleTriple();
3485 // Ignore other sub-blocks.
3486 if (Stream.SkipBlock())
3487 return error("Malformed block");
3490 case BitstreamEntry::Record:
3491 Stream.skipRecord(Entry.ID);
3497 /// Parse metadata attachments.
3498 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3499 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3500 return error("Invalid record");
3502 SmallVector<uint64_t, 64> Record;
3504 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3506 switch (Entry.Kind) {
3507 case BitstreamEntry::SubBlock: // Handled for us already.
3508 case BitstreamEntry::Error:
3509 return error("Malformed block");
3510 case BitstreamEntry::EndBlock:
3511 return std::error_code();
3512 case BitstreamEntry::Record:
3513 // The interesting case.
3517 // Read a metadata attachment record.
3519 switch (Stream.readRecord(Entry.ID, Record)) {
3520 default: // Default behavior: ignore.
3522 case bitc::METADATA_ATTACHMENT: {
3523 unsigned RecordLength = Record.size();
3525 return error("Invalid record");
3526 if (RecordLength % 2 == 0) {
3527 // A function attachment.
3528 for (unsigned I = 0; I != RecordLength; I += 2) {
3529 auto K = MDKindMap.find(Record[I]);
3530 if (K == MDKindMap.end())
3531 return error("Invalid ID");
3532 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3533 F.setMetadata(K->second, cast<MDNode>(MD));
3538 // An instruction attachment.
3539 Instruction *Inst = InstructionList[Record[0]];
3540 for (unsigned i = 1; i != RecordLength; i = i+2) {
3541 unsigned Kind = Record[i];
3542 DenseMap<unsigned, unsigned>::iterator I =
3543 MDKindMap.find(Kind);
3544 if (I == MDKindMap.end())
3545 return error("Invalid ID");
3546 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3547 if (isa<LocalAsMetadata>(Node))
3548 // Drop the attachment. This used to be legal, but there's no
3551 Inst->setMetadata(I->second, cast<MDNode>(Node));
3552 if (I->second == LLVMContext::MD_tbaa)
3553 InstsWithTBAATag.push_back(Inst);
3561 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3562 Type *ValType, Type *PtrType) {
3563 if (!isa<PointerType>(PtrType))
3564 return error(DH, "Load/Store operand is not a pointer type");
3565 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3567 if (ValType && ValType != ElemType)
3568 return error(DH, "Explicit load/store type does not match pointee type of "
3570 if (!PointerType::isLoadableOrStorableType(ElemType))
3571 return error(DH, "Cannot load/store from pointer");
3572 return std::error_code();
3575 /// Lazily parse the specified function body block.
3576 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3577 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3578 return error("Invalid record");
3580 InstructionList.clear();
3581 unsigned ModuleValueListSize = ValueList.size();
3582 unsigned ModuleMDValueListSize = MDValueList.size();
3584 // Add all the function arguments to the value table.
3585 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3586 ValueList.push_back(I);
3588 unsigned NextValueNo = ValueList.size();
3589 BasicBlock *CurBB = nullptr;
3590 unsigned CurBBNo = 0;
3593 auto getLastInstruction = [&]() -> Instruction * {
3594 if (CurBB && !CurBB->empty())
3595 return &CurBB->back();
3596 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3597 !FunctionBBs[CurBBNo - 1]->empty())
3598 return &FunctionBBs[CurBBNo - 1]->back();
3602 std::vector<OperandBundleDef> OperandBundles;
3604 // Read all the records.
3605 SmallVector<uint64_t, 64> Record;
3607 BitstreamEntry Entry = Stream.advance();
3609 switch (Entry.Kind) {
3610 case BitstreamEntry::Error:
3611 return error("Malformed block");
3612 case BitstreamEntry::EndBlock:
3613 goto OutOfRecordLoop;
3615 case BitstreamEntry::SubBlock:
3617 default: // Skip unknown content.
3618 if (Stream.SkipBlock())
3619 return error("Invalid record");
3621 case bitc::CONSTANTS_BLOCK_ID:
3622 if (std::error_code EC = parseConstants())
3624 NextValueNo = ValueList.size();
3626 case bitc::VALUE_SYMTAB_BLOCK_ID:
3627 if (std::error_code EC = parseValueSymbolTable())
3630 case bitc::METADATA_ATTACHMENT_ID:
3631 if (std::error_code EC = parseMetadataAttachment(*F))
3634 case bitc::METADATA_BLOCK_ID:
3635 if (std::error_code EC = parseMetadata())
3638 case bitc::USELIST_BLOCK_ID:
3639 if (std::error_code EC = parseUseLists())
3645 case BitstreamEntry::Record:
3646 // The interesting case.
3652 Instruction *I = nullptr;
3653 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3655 default: // Default behavior: reject
3656 return error("Invalid value");
3657 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3658 if (Record.size() < 1 || Record[0] == 0)
3659 return error("Invalid record");
3660 // Create all the basic blocks for the function.
3661 FunctionBBs.resize(Record[0]);
3663 // See if anything took the address of blocks in this function.
3664 auto BBFRI = BasicBlockFwdRefs.find(F);
3665 if (BBFRI == BasicBlockFwdRefs.end()) {
3666 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3667 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3669 auto &BBRefs = BBFRI->second;
3670 // Check for invalid basic block references.
3671 if (BBRefs.size() > FunctionBBs.size())
3672 return error("Invalid ID");
3673 assert(!BBRefs.empty() && "Unexpected empty array");
3674 assert(!BBRefs.front() && "Invalid reference to entry block");
3675 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3677 if (I < RE && BBRefs[I]) {
3678 BBRefs[I]->insertInto(F);
3679 FunctionBBs[I] = BBRefs[I];
3681 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3684 // Erase from the table.
3685 BasicBlockFwdRefs.erase(BBFRI);
3688 CurBB = FunctionBBs[0];
3692 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3693 // This record indicates that the last instruction is at the same
3694 // location as the previous instruction with a location.
3695 I = getLastInstruction();
3698 return error("Invalid record");
3699 I->setDebugLoc(LastLoc);
3703 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3704 I = getLastInstruction();
3705 if (!I || Record.size() < 4)
3706 return error("Invalid record");
3708 unsigned Line = Record[0], Col = Record[1];
3709 unsigned ScopeID = Record[2], IAID = Record[3];
3711 MDNode *Scope = nullptr, *IA = nullptr;
3712 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3713 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3714 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3715 I->setDebugLoc(LastLoc);
3720 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3723 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3724 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3725 OpNum+1 > Record.size())
3726 return error("Invalid record");
3728 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3730 return error("Invalid record");
3731 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3732 InstructionList.push_back(I);
3733 if (OpNum < Record.size()) {
3734 if (Opc == Instruction::Add ||
3735 Opc == Instruction::Sub ||
3736 Opc == Instruction::Mul ||
3737 Opc == Instruction::Shl) {
3738 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3739 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3740 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3741 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3742 } else if (Opc == Instruction::SDiv ||
3743 Opc == Instruction::UDiv ||
3744 Opc == Instruction::LShr ||
3745 Opc == Instruction::AShr) {
3746 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3747 cast<BinaryOperator>(I)->setIsExact(true);
3748 } else if (isa<FPMathOperator>(I)) {
3749 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3751 I->setFastMathFlags(FMF);
3757 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3760 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3761 OpNum+2 != Record.size())
3762 return error("Invalid record");
3764 Type *ResTy = getTypeByID(Record[OpNum]);
3765 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3766 if (Opc == -1 || !ResTy)
3767 return error("Invalid record");
3768 Instruction *Temp = nullptr;
3769 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3771 InstructionList.push_back(Temp);
3772 CurBB->getInstList().push_back(Temp);
3775 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3777 InstructionList.push_back(I);
3780 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3781 case bitc::FUNC_CODE_INST_GEP_OLD:
3782 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3788 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3789 InBounds = Record[OpNum++];
3790 Ty = getTypeByID(Record[OpNum++]);
3792 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3797 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3798 return error("Invalid record");
3801 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3804 cast<SequentialType>(BasePtr->getType()->getScalarType())
3807 "Explicit gep type does not match pointee type of pointer operand");
3809 SmallVector<Value*, 16> GEPIdx;
3810 while (OpNum != Record.size()) {
3812 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3813 return error("Invalid record");
3814 GEPIdx.push_back(Op);
3817 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3819 InstructionList.push_back(I);
3821 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3825 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3826 // EXTRACTVAL: [opty, opval, n x indices]
3829 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3830 return error("Invalid record");
3832 unsigned RecSize = Record.size();
3833 if (OpNum == RecSize)
3834 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3836 SmallVector<unsigned, 4> EXTRACTVALIdx;
3837 Type *CurTy = Agg->getType();
3838 for (; OpNum != RecSize; ++OpNum) {
3839 bool IsArray = CurTy->isArrayTy();
3840 bool IsStruct = CurTy->isStructTy();
3841 uint64_t Index = Record[OpNum];
3843 if (!IsStruct && !IsArray)
3844 return error("EXTRACTVAL: Invalid type");
3845 if ((unsigned)Index != Index)
3846 return error("Invalid value");
3847 if (IsStruct && Index >= CurTy->subtypes().size())
3848 return error("EXTRACTVAL: Invalid struct index");
3849 if (IsArray && Index >= CurTy->getArrayNumElements())
3850 return error("EXTRACTVAL: Invalid array index");
3851 EXTRACTVALIdx.push_back((unsigned)Index);
3854 CurTy = CurTy->subtypes()[Index];
3856 CurTy = CurTy->subtypes()[0];
3859 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3860 InstructionList.push_back(I);
3864 case bitc::FUNC_CODE_INST_INSERTVAL: {
3865 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3868 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3869 return error("Invalid record");
3871 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3872 return error("Invalid record");
3874 unsigned RecSize = Record.size();
3875 if (OpNum == RecSize)
3876 return error("INSERTVAL: Invalid instruction with 0 indices");
3878 SmallVector<unsigned, 4> INSERTVALIdx;
3879 Type *CurTy = Agg->getType();
3880 for (; OpNum != RecSize; ++OpNum) {
3881 bool IsArray = CurTy->isArrayTy();
3882 bool IsStruct = CurTy->isStructTy();
3883 uint64_t Index = Record[OpNum];
3885 if (!IsStruct && !IsArray)
3886 return error("INSERTVAL: Invalid type");
3887 if ((unsigned)Index != Index)
3888 return error("Invalid value");
3889 if (IsStruct && Index >= CurTy->subtypes().size())
3890 return error("INSERTVAL: Invalid struct index");
3891 if (IsArray && Index >= CurTy->getArrayNumElements())
3892 return error("INSERTVAL: Invalid array index");
3894 INSERTVALIdx.push_back((unsigned)Index);
3896 CurTy = CurTy->subtypes()[Index];
3898 CurTy = CurTy->subtypes()[0];
3901 if (CurTy != Val->getType())
3902 return error("Inserted value type doesn't match aggregate type");
3904 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3905 InstructionList.push_back(I);
3909 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3910 // obsolete form of select
3911 // handles select i1 ... in old bitcode
3913 Value *TrueVal, *FalseVal, *Cond;
3914 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3915 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3916 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3917 return error("Invalid record");
3919 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3920 InstructionList.push_back(I);
3924 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3925 // new form of select
3926 // handles select i1 or select [N x i1]
3928 Value *TrueVal, *FalseVal, *Cond;
3929 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3930 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3931 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3932 return error("Invalid record");
3934 // select condition can be either i1 or [N x i1]
3935 if (VectorType* vector_type =
3936 dyn_cast<VectorType>(Cond->getType())) {
3938 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3939 return error("Invalid type for value");
3942 if (Cond->getType() != Type::getInt1Ty(Context))
3943 return error("Invalid type for value");
3946 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3947 InstructionList.push_back(I);
3951 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3954 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3955 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3956 return error("Invalid record");
3957 if (!Vec->getType()->isVectorTy())
3958 return error("Invalid type for value");
3959 I = ExtractElementInst::Create(Vec, Idx);
3960 InstructionList.push_back(I);
3964 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3966 Value *Vec, *Elt, *Idx;
3967 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3968 return error("Invalid record");
3969 if (!Vec->getType()->isVectorTy())
3970 return error("Invalid type for value");
3971 if (popValue(Record, OpNum, NextValueNo,
3972 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3973 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3974 return error("Invalid record");
3975 I = InsertElementInst::Create(Vec, Elt, Idx);
3976 InstructionList.push_back(I);
3980 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3982 Value *Vec1, *Vec2, *Mask;
3983 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3984 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3985 return error("Invalid record");
3987 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3988 return error("Invalid record");
3989 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3990 return error("Invalid type for value");
3991 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3992 InstructionList.push_back(I);
3996 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3997 // Old form of ICmp/FCmp returning bool
3998 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3999 // both legal on vectors but had different behaviour.
4000 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4001 // FCmp/ICmp returning bool or vector of bool
4005 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4006 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4007 return error("Invalid record");
4009 unsigned PredVal = Record[OpNum];
4010 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4012 if (IsFP && Record.size() > OpNum+1)
4013 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4015 if (OpNum+1 != Record.size())
4016 return error("Invalid record");
4018 if (LHS->getType()->isFPOrFPVectorTy())
4019 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4021 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4024 I->setFastMathFlags(FMF);
4025 InstructionList.push_back(I);
4029 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4031 unsigned Size = Record.size();
4033 I = ReturnInst::Create(Context);
4034 InstructionList.push_back(I);
4039 Value *Op = nullptr;
4040 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4041 return error("Invalid record");
4042 if (OpNum != Record.size())
4043 return error("Invalid record");
4045 I = ReturnInst::Create(Context, Op);
4046 InstructionList.push_back(I);
4049 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4050 if (Record.size() != 1 && Record.size() != 3)
4051 return error("Invalid record");
4052 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4054 return error("Invalid record");
4056 if (Record.size() == 1) {
4057 I = BranchInst::Create(TrueDest);
4058 InstructionList.push_back(I);
4061 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4062 Value *Cond = getValue(Record, 2, NextValueNo,
4063 Type::getInt1Ty(Context));
4064 if (!FalseDest || !Cond)
4065 return error("Invalid record");
4066 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4067 InstructionList.push_back(I);
4071 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4072 if (Record.size() != 1 && Record.size() != 2)
4073 return error("Invalid record");
4075 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4076 Type::getTokenTy(Context), OC_CleanupPad);
4078 return error("Invalid record");
4079 BasicBlock *UnwindDest = nullptr;
4080 if (Record.size() == 2) {
4081 UnwindDest = getBasicBlock(Record[Idx++]);
4083 return error("Invalid record");
4086 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4088 InstructionList.push_back(I);
4091 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4092 if (Record.size() != 2)
4093 return error("Invalid record");
4095 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4096 Type::getTokenTy(Context), OC_CatchPad);
4098 return error("Invalid record");
4099 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4101 return error("Invalid record");
4103 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4104 InstructionList.push_back(I);
4107 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4108 if (Record.size() < 3)
4109 return error("Invalid record");
4111 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4113 return error("Invalid record");
4114 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4116 return error("Invalid record");
4117 unsigned NumArgOperands = Record[Idx++];
4118 SmallVector<Value *, 2> Args;
4119 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4121 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4122 return error("Invalid record");
4123 Args.push_back(Val);
4125 if (Record.size() != Idx)
4126 return error("Invalid record");
4128 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4129 InstructionList.push_back(I);
4132 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4133 if (Record.size() < 1)
4134 return error("Invalid record");
4136 bool HasUnwindDest = !!Record[Idx++];
4137 BasicBlock *UnwindDest = nullptr;
4138 if (HasUnwindDest) {
4139 if (Idx == Record.size())
4140 return error("Invalid record");
4141 UnwindDest = getBasicBlock(Record[Idx++]);
4143 return error("Invalid record");
4145 unsigned NumArgOperands = Record[Idx++];
4146 SmallVector<Value *, 2> Args;
4147 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4149 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4150 return error("Invalid record");
4151 Args.push_back(Val);
4153 if (Record.size() != Idx)
4154 return error("Invalid record");
4156 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4157 InstructionList.push_back(I);
4160 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4161 if (Record.size() < 1)
4162 return error("Invalid record");
4164 unsigned NumArgOperands = Record[Idx++];
4165 SmallVector<Value *, 2> Args;
4166 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4168 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4169 return error("Invalid record");
4170 Args.push_back(Val);
4172 if (Record.size() != Idx)
4173 return error("Invalid record");
4175 I = CleanupPadInst::Create(Context, Args);
4176 InstructionList.push_back(I);
4179 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4180 if (Record.size() > 1)
4181 return error("Invalid record");
4182 BasicBlock *BB = nullptr;
4183 if (Record.size() == 1) {
4184 BB = getBasicBlock(Record[0]);
4186 return error("Invalid record");
4188 I = CatchEndPadInst::Create(Context, BB);
4189 InstructionList.push_back(I);
4192 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4193 if (Record.size() != 1 && Record.size() != 2)
4194 return error("Invalid record");
4196 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4197 Type::getTokenTy(Context), OC_CleanupPad);
4199 return error("Invalid record");
4201 BasicBlock *BB = nullptr;
4202 if (Record.size() == 2) {
4203 BB = getBasicBlock(Record[Idx++]);
4205 return error("Invalid record");
4207 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4208 InstructionList.push_back(I);
4211 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4213 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4214 // "New" SwitchInst format with case ranges. The changes to write this
4215 // format were reverted but we still recognize bitcode that uses it.
4216 // Hopefully someday we will have support for case ranges and can use
4217 // this format again.
4219 Type *OpTy = getTypeByID(Record[1]);
4220 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4222 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4223 BasicBlock *Default = getBasicBlock(Record[3]);
4224 if (!OpTy || !Cond || !Default)
4225 return error("Invalid record");
4227 unsigned NumCases = Record[4];
4229 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4230 InstructionList.push_back(SI);
4232 unsigned CurIdx = 5;
4233 for (unsigned i = 0; i != NumCases; ++i) {
4234 SmallVector<ConstantInt*, 1> CaseVals;
4235 unsigned NumItems = Record[CurIdx++];
4236 for (unsigned ci = 0; ci != NumItems; ++ci) {
4237 bool isSingleNumber = Record[CurIdx++];
4240 unsigned ActiveWords = 1;
4241 if (ValueBitWidth > 64)
4242 ActiveWords = Record[CurIdx++];
4243 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4245 CurIdx += ActiveWords;
4247 if (!isSingleNumber) {
4249 if (ValueBitWidth > 64)
4250 ActiveWords = Record[CurIdx++];
4251 APInt High = readWideAPInt(
4252 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4253 CurIdx += ActiveWords;
4255 // FIXME: It is not clear whether values in the range should be
4256 // compared as signed or unsigned values. The partially
4257 // implemented changes that used this format in the past used
4258 // unsigned comparisons.
4259 for ( ; Low.ule(High); ++Low)
4260 CaseVals.push_back(ConstantInt::get(Context, Low));
4262 CaseVals.push_back(ConstantInt::get(Context, Low));
4264 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4265 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4266 cve = CaseVals.end(); cvi != cve; ++cvi)
4267 SI->addCase(*cvi, DestBB);
4273 // Old SwitchInst format without case ranges.
4275 if (Record.size() < 3 || (Record.size() & 1) == 0)
4276 return error("Invalid record");
4277 Type *OpTy = getTypeByID(Record[0]);
4278 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4279 BasicBlock *Default = getBasicBlock(Record[2]);
4280 if (!OpTy || !Cond || !Default)
4281 return error("Invalid record");
4282 unsigned NumCases = (Record.size()-3)/2;
4283 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4284 InstructionList.push_back(SI);
4285 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4286 ConstantInt *CaseVal =
4287 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4288 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4289 if (!CaseVal || !DestBB) {
4291 return error("Invalid record");
4293 SI->addCase(CaseVal, DestBB);
4298 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4299 if (Record.size() < 2)
4300 return error("Invalid record");
4301 Type *OpTy = getTypeByID(Record[0]);
4302 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4303 if (!OpTy || !Address)
4304 return error("Invalid record");
4305 unsigned NumDests = Record.size()-2;
4306 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4307 InstructionList.push_back(IBI);
4308 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4309 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4310 IBI->addDestination(DestBB);
4313 return error("Invalid record");
4320 case bitc::FUNC_CODE_INST_INVOKE: {
4321 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4322 if (Record.size() < 4)
4323 return error("Invalid record");
4325 AttributeSet PAL = getAttributes(Record[OpNum++]);
4326 unsigned CCInfo = Record[OpNum++];
4327 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4328 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4330 FunctionType *FTy = nullptr;
4331 if (CCInfo >> 13 & 1 &&
4332 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4333 return error("Explicit invoke type is not a function type");
4336 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4337 return error("Invalid record");
4339 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4341 return error("Callee is not a pointer");
4343 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4345 return error("Callee is not of pointer to function type");
4346 } else if (CalleeTy->getElementType() != FTy)
4347 return error("Explicit invoke type does not match pointee type of "
4349 if (Record.size() < FTy->getNumParams() + OpNum)
4350 return error("Insufficient operands to call");
4352 SmallVector<Value*, 16> Ops;
4353 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4354 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4355 FTy->getParamType(i)));
4357 return error("Invalid record");
4360 if (!FTy->isVarArg()) {
4361 if (Record.size() != OpNum)
4362 return error("Invalid record");
4364 // Read type/value pairs for varargs params.
4365 while (OpNum != Record.size()) {
4367 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4368 return error("Invalid record");
4373 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4374 OperandBundles.clear();
4375 InstructionList.push_back(I);
4377 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
4378 cast<InvokeInst>(I)->setAttributes(PAL);
4381 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4383 Value *Val = nullptr;
4384 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4385 return error("Invalid record");
4386 I = ResumeInst::Create(Val);
4387 InstructionList.push_back(I);
4390 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4391 I = new UnreachableInst(Context);
4392 InstructionList.push_back(I);
4394 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4395 if (Record.size() < 1 || ((Record.size()-1)&1))
4396 return error("Invalid record");
4397 Type *Ty = getTypeByID(Record[0]);
4399 return error("Invalid record");
4401 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4402 InstructionList.push_back(PN);
4404 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4406 // With the new function encoding, it is possible that operands have
4407 // negative IDs (for forward references). Use a signed VBR
4408 // representation to keep the encoding small.
4410 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4412 V = getValue(Record, 1+i, NextValueNo, Ty);
4413 BasicBlock *BB = getBasicBlock(Record[2+i]);
4415 return error("Invalid record");
4416 PN->addIncoming(V, BB);
4422 case bitc::FUNC_CODE_INST_LANDINGPAD:
4423 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4424 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4426 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4427 if (Record.size() < 3)
4428 return error("Invalid record");
4430 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4431 if (Record.size() < 4)
4432 return error("Invalid record");
4434 Type *Ty = getTypeByID(Record[Idx++]);
4436 return error("Invalid record");
4437 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4438 Value *PersFn = nullptr;
4439 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4440 return error("Invalid record");
4442 if (!F->hasPersonalityFn())
4443 F->setPersonalityFn(cast<Constant>(PersFn));
4444 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4445 return error("Personality function mismatch");
4448 bool IsCleanup = !!Record[Idx++];
4449 unsigned NumClauses = Record[Idx++];
4450 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4451 LP->setCleanup(IsCleanup);
4452 for (unsigned J = 0; J != NumClauses; ++J) {
4453 LandingPadInst::ClauseType CT =
4454 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4457 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4459 return error("Invalid record");
4462 assert((CT != LandingPadInst::Catch ||
4463 !isa<ArrayType>(Val->getType())) &&
4464 "Catch clause has a invalid type!");
4465 assert((CT != LandingPadInst::Filter ||
4466 isa<ArrayType>(Val->getType())) &&
4467 "Filter clause has invalid type!");
4468 LP->addClause(cast<Constant>(Val));
4472 InstructionList.push_back(I);
4476 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4477 if (Record.size() != 4)
4478 return error("Invalid record");
4479 uint64_t AlignRecord = Record[3];
4480 const uint64_t InAllocaMask = uint64_t(1) << 5;
4481 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4482 // Reserve bit 7 for SwiftError flag.
4483 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4484 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4485 bool InAlloca = AlignRecord & InAllocaMask;
4486 Type *Ty = getTypeByID(Record[0]);
4487 if ((AlignRecord & ExplicitTypeMask) == 0) {
4488 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4490 return error("Old-style alloca with a non-pointer type");
4491 Ty = PTy->getElementType();
4493 Type *OpTy = getTypeByID(Record[1]);
4494 Value *Size = getFnValueByID(Record[2], OpTy);
4496 if (std::error_code EC =
4497 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4501 return error("Invalid record");
4502 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4503 AI->setUsedWithInAlloca(InAlloca);
4505 InstructionList.push_back(I);
4508 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4511 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4512 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4513 return error("Invalid record");
4516 if (OpNum + 3 == Record.size())
4517 Ty = getTypeByID(Record[OpNum++]);
4518 if (std::error_code EC =
4519 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4522 Ty = cast<PointerType>(Op->getType())->getElementType();
4525 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4527 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4529 InstructionList.push_back(I);
4532 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4533 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4536 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4537 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4538 return error("Invalid record");
4541 if (OpNum + 5 == Record.size())
4542 Ty = getTypeByID(Record[OpNum++]);
4543 if (std::error_code EC =
4544 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4547 Ty = cast<PointerType>(Op->getType())->getElementType();
4549 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4550 if (Ordering == NotAtomic || Ordering == Release ||
4551 Ordering == AcquireRelease)
4552 return error("Invalid record");
4553 if (Ordering != NotAtomic && Record[OpNum] == 0)
4554 return error("Invalid record");
4555 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4558 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4560 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4562 InstructionList.push_back(I);
4565 case bitc::FUNC_CODE_INST_STORE:
4566 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4569 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4570 (BitCode == bitc::FUNC_CODE_INST_STORE
4571 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4572 : popValue(Record, OpNum, NextValueNo,
4573 cast<PointerType>(Ptr->getType())->getElementType(),
4575 OpNum + 2 != Record.size())
4576 return error("Invalid record");
4578 if (std::error_code EC = typeCheckLoadStoreInst(
4579 DiagnosticHandler, Val->getType(), Ptr->getType()))
4582 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4584 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4585 InstructionList.push_back(I);
4588 case bitc::FUNC_CODE_INST_STOREATOMIC:
4589 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4590 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4593 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4594 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4595 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4596 : popValue(Record, OpNum, NextValueNo,
4597 cast<PointerType>(Ptr->getType())->getElementType(),
4599 OpNum + 4 != Record.size())
4600 return error("Invalid record");
4602 if (std::error_code EC = typeCheckLoadStoreInst(
4603 DiagnosticHandler, Val->getType(), Ptr->getType()))
4605 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4606 if (Ordering == NotAtomic || Ordering == Acquire ||
4607 Ordering == AcquireRelease)
4608 return error("Invalid record");
4609 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4610 if (Ordering != NotAtomic && Record[OpNum] == 0)
4611 return error("Invalid record");
4614 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4616 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4617 InstructionList.push_back(I);
4620 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4621 case bitc::FUNC_CODE_INST_CMPXCHG: {
4622 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4623 // failureordering?, isweak?]
4625 Value *Ptr, *Cmp, *New;
4626 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4627 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4628 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4629 : popValue(Record, OpNum, NextValueNo,
4630 cast<PointerType>(Ptr->getType())->getElementType(),
4632 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4633 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4634 return error("Invalid record");
4635 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4636 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4637 return error("Invalid record");
4638 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4640 if (std::error_code EC = typeCheckLoadStoreInst(
4641 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4643 AtomicOrdering FailureOrdering;
4644 if (Record.size() < 7)
4646 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4648 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4650 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4652 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4654 if (Record.size() < 8) {
4655 // Before weak cmpxchgs existed, the instruction simply returned the
4656 // value loaded from memory, so bitcode files from that era will be
4657 // expecting the first component of a modern cmpxchg.
4658 CurBB->getInstList().push_back(I);
4659 I = ExtractValueInst::Create(I, 0);
4661 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4664 InstructionList.push_back(I);
4667 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4668 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4671 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4672 popValue(Record, OpNum, NextValueNo,
4673 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4674 OpNum+4 != Record.size())
4675 return error("Invalid record");
4676 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4677 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4678 Operation > AtomicRMWInst::LAST_BINOP)
4679 return error("Invalid record");
4680 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4681 if (Ordering == NotAtomic || Ordering == Unordered)
4682 return error("Invalid record");
4683 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4684 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4685 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4686 InstructionList.push_back(I);
4689 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4690 if (2 != Record.size())
4691 return error("Invalid record");
4692 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4693 if (Ordering == NotAtomic || Ordering == Unordered ||
4694 Ordering == Monotonic)
4695 return error("Invalid record");
4696 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4697 I = new FenceInst(Context, Ordering, SynchScope);
4698 InstructionList.push_back(I);
4701 case bitc::FUNC_CODE_INST_CALL: {
4702 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4703 if (Record.size() < 3)
4704 return error("Invalid record");
4707 AttributeSet PAL = getAttributes(Record[OpNum++]);
4708 unsigned CCInfo = Record[OpNum++];
4710 FunctionType *FTy = nullptr;
4711 if (CCInfo >> 15 & 1 &&
4712 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4713 return error("Explicit call type is not a function type");
4716 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4717 return error("Invalid record");
4719 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4721 return error("Callee is not a pointer type");
4723 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4725 return error("Callee is not of pointer to function type");
4726 } else if (OpTy->getElementType() != FTy)
4727 return error("Explicit call type does not match pointee type of "
4729 if (Record.size() < FTy->getNumParams() + OpNum)
4730 return error("Insufficient operands to call");
4732 SmallVector<Value*, 16> Args;
4733 // Read the fixed params.
4734 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4735 if (FTy->getParamType(i)->isLabelTy())
4736 Args.push_back(getBasicBlock(Record[OpNum]));
4738 Args.push_back(getValue(Record, OpNum, NextValueNo,
4739 FTy->getParamType(i)));
4741 return error("Invalid record");
4744 // Read type/value pairs for varargs params.
4745 if (!FTy->isVarArg()) {
4746 if (OpNum != Record.size())
4747 return error("Invalid record");
4749 while (OpNum != Record.size()) {
4751 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4752 return error("Invalid record");
4757 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4758 OperandBundles.clear();
4759 InstructionList.push_back(I);
4760 cast<CallInst>(I)->setCallingConv(
4761 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4762 CallInst::TailCallKind TCK = CallInst::TCK_None;
4764 TCK = CallInst::TCK_Tail;
4765 if (CCInfo & (1 << 14))
4766 TCK = CallInst::TCK_MustTail;
4767 cast<CallInst>(I)->setTailCallKind(TCK);
4768 cast<CallInst>(I)->setAttributes(PAL);
4771 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4772 if (Record.size() < 3)
4773 return error("Invalid record");
4774 Type *OpTy = getTypeByID(Record[0]);
4775 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4776 Type *ResTy = getTypeByID(Record[2]);
4777 if (!OpTy || !Op || !ResTy)
4778 return error("Invalid record");
4779 I = new VAArgInst(Op, ResTy);
4780 InstructionList.push_back(I);
4784 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4785 // A call or an invoke can be optionally prefixed with some variable
4786 // number of operand bundle blocks. These blocks are read into
4787 // OperandBundles and consumed at the next call or invoke instruction.
4789 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4790 return error("Invalid record");
4792 OperandBundles.emplace_back();
4793 OperandBundles.back().Tag = BundleTags[Record[0]];
4795 std::vector<Value *> &Inputs = OperandBundles.back().Inputs;
4798 while (OpNum != Record.size()) {
4800 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4801 return error("Invalid record");
4802 Inputs.push_back(Op);
4809 // Add instruction to end of current BB. If there is no current BB, reject
4813 return error("Invalid instruction with no BB");
4815 if (!OperandBundles.empty()) {
4817 return error("Operand bundles found with no consumer");
4819 CurBB->getInstList().push_back(I);
4821 // If this was a terminator instruction, move to the next block.
4822 if (isa<TerminatorInst>(I)) {
4824 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4827 // Non-void values get registered in the value table for future use.
4828 if (I && !I->getType()->isVoidTy())
4829 if (ValueList.assignValue(I, NextValueNo++))
4830 return error("Invalid forward reference");
4835 if (!OperandBundles.empty())
4836 return error("Operand bundles found with no consumer");
4838 // Check the function list for unresolved values.
4839 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4840 if (!A->getParent()) {
4841 // We found at least one unresolved value. Nuke them all to avoid leaks.
4842 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4843 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4844 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4848 return error("Never resolved value found in function");
4852 // FIXME: Check for unresolved forward-declared metadata references
4853 // and clean up leaks.
4855 // Trim the value list down to the size it was before we parsed this function.
4856 ValueList.shrinkTo(ModuleValueListSize);
4857 MDValueList.shrinkTo(ModuleMDValueListSize);
4858 std::vector<BasicBlock*>().swap(FunctionBBs);
4859 return std::error_code();
4862 /// Find the function body in the bitcode stream
4863 std::error_code BitcodeReader::findFunctionInStream(
4865 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4866 while (DeferredFunctionInfoIterator->second == 0) {
4867 // This is the fallback handling for the old format bitcode that
4868 // didn't contain the function index in the VST. Assert if we end up
4869 // here for the new format (which is the only time the VSTOffset would
4871 assert(VSTOffset == 0);
4872 if (Stream.AtEndOfStream())
4873 return error("Could not find function in stream");
4874 // ParseModule will parse the next body in the stream and set its
4875 // position in the DeferredFunctionInfo map.
4876 if (std::error_code EC = parseModule(true))
4879 return std::error_code();
4882 //===----------------------------------------------------------------------===//
4883 // GVMaterializer implementation
4884 //===----------------------------------------------------------------------===//
4886 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4888 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4889 if (std::error_code EC = materializeMetadata())
4892 Function *F = dyn_cast<Function>(GV);
4893 // If it's not a function or is already material, ignore the request.
4894 if (!F || !F->isMaterializable())
4895 return std::error_code();
4897 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4898 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4899 // If its position is recorded as 0, its body is somewhere in the stream
4900 // but we haven't seen it yet.
4901 if (DFII->second == 0)
4902 if (std::error_code EC = findFunctionInStream(F, DFII))
4905 // Move the bit stream to the saved position of the deferred function body.
4906 Stream.JumpToBit(DFII->second);
4908 if (std::error_code EC = parseFunctionBody(F))
4910 F->setIsMaterializable(false);
4915 // Upgrade any old intrinsic calls in the function.
4916 for (auto &I : UpgradedIntrinsics) {
4917 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
4920 if (CallInst *CI = dyn_cast<CallInst>(U))
4921 UpgradeIntrinsicCall(CI, I.second);
4925 // Bring in any functions that this function forward-referenced via
4927 return materializeForwardReferencedFunctions();
4930 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4931 const Function *F = dyn_cast<Function>(GV);
4932 if (!F || F->isDeclaration())
4935 // Dematerializing F would leave dangling references that wouldn't be
4936 // reconnected on re-materialization.
4937 if (BlockAddressesTaken.count(F))
4940 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4943 void BitcodeReader::dematerialize(GlobalValue *GV) {
4944 Function *F = dyn_cast<Function>(GV);
4945 // If this function isn't dematerializable, this is a noop.
4946 if (!F || !isDematerializable(F))
4949 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4951 // Just forget the function body, we can remat it later.
4952 F->dropAllReferences();
4953 F->setIsMaterializable(true);
4956 std::error_code BitcodeReader::materializeModule(Module *M) {
4957 assert(M == TheModule &&
4958 "Can only Materialize the Module this BitcodeReader is attached to.");
4960 if (std::error_code EC = materializeMetadata())
4963 // Promise to materialize all forward references.
4964 WillMaterializeAllForwardRefs = true;
4966 // Iterate over the module, deserializing any functions that are still on
4968 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4970 if (std::error_code EC = materialize(F))
4973 // At this point, if there are any function bodies, the current bit is
4974 // pointing to the END_BLOCK record after them. Now make sure the rest
4975 // of the bits in the module have been read.
4979 // Check that all block address forward references got resolved (as we
4981 if (!BasicBlockFwdRefs.empty())
4982 return error("Never resolved function from blockaddress");
4984 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4985 // delete the old functions to clean up. We can't do this unless the entire
4986 // module is materialized because there could always be another function body
4987 // with calls to the old function.
4988 for (auto &I : UpgradedIntrinsics) {
4989 for (auto *U : I.first->users()) {
4990 if (CallInst *CI = dyn_cast<CallInst>(U))
4991 UpgradeIntrinsicCall(CI, I.second);
4993 if (!I.first->use_empty())
4994 I.first->replaceAllUsesWith(I.second);
4995 I.first->eraseFromParent();
4997 UpgradedIntrinsics.clear();
4999 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5000 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5002 UpgradeDebugInfo(*M);
5003 return std::error_code();
5006 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5007 return IdentifiedStructTypes;
5011 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5013 return initLazyStream(std::move(Streamer));
5014 return initStreamFromBuffer();
5017 std::error_code BitcodeReader::initStreamFromBuffer() {
5018 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5019 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5021 if (Buffer->getBufferSize() & 3)
5022 return error("Invalid bitcode signature");
5024 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5025 // The magic number is 0x0B17C0DE stored in little endian.
5026 if (isBitcodeWrapper(BufPtr, BufEnd))
5027 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5028 return error("Invalid bitcode wrapper header");
5030 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5031 Stream.init(&*StreamFile);
5033 return std::error_code();
5037 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5038 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5041 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5042 StreamingMemoryObject &Bytes = *OwnedBytes;
5043 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5044 Stream.init(&*StreamFile);
5046 unsigned char buf[16];
5047 if (Bytes.readBytes(buf, 16, 0) != 16)
5048 return error("Invalid bitcode signature");
5050 if (!isBitcode(buf, buf + 16))
5051 return error("Invalid bitcode signature");
5053 if (isBitcodeWrapper(buf, buf + 4)) {
5054 const unsigned char *bitcodeStart = buf;
5055 const unsigned char *bitcodeEnd = buf + 16;
5056 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5057 Bytes.dropLeadingBytes(bitcodeStart - buf);
5058 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5060 return std::error_code();
5064 class BitcodeErrorCategoryType : public std::error_category {
5065 const char *name() const LLVM_NOEXCEPT override {
5066 return "llvm.bitcode";
5068 std::string message(int IE) const override {
5069 BitcodeError E = static_cast<BitcodeError>(IE);
5071 case BitcodeError::InvalidBitcodeSignature:
5072 return "Invalid bitcode signature";
5073 case BitcodeError::CorruptedBitcode:
5074 return "Corrupted bitcode";
5076 llvm_unreachable("Unknown error type!");
5081 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5083 const std::error_category &llvm::BitcodeErrorCategory() {
5084 return *ErrorCategory;
5087 //===----------------------------------------------------------------------===//
5088 // External interface
5089 //===----------------------------------------------------------------------===//
5091 static ErrorOr<std::unique_ptr<Module>>
5092 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5093 BitcodeReader *R, LLVMContext &Context,
5094 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5095 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5096 M->setMaterializer(R);
5098 auto cleanupOnError = [&](std::error_code EC) {
5099 R->releaseBuffer(); // Never take ownership on error.
5103 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5104 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5105 ShouldLazyLoadMetadata))
5106 return cleanupOnError(EC);
5108 if (MaterializeAll) {
5109 // Read in the entire module, and destroy the BitcodeReader.
5110 if (std::error_code EC = M->materializeAllPermanently())
5111 return cleanupOnError(EC);
5113 // Resolve forward references from blockaddresses.
5114 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5115 return cleanupOnError(EC);
5117 return std::move(M);
5120 /// \brief Get a lazy one-at-time loading module from bitcode.
5122 /// This isn't always used in a lazy context. In particular, it's also used by
5123 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5124 /// in forward-referenced functions from block address references.
5126 /// \param[in] MaterializeAll Set to \c true if we should materialize
5128 static ErrorOr<std::unique_ptr<Module>>
5129 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5130 LLVMContext &Context, bool MaterializeAll,
5131 DiagnosticHandlerFunction DiagnosticHandler,
5132 bool ShouldLazyLoadMetadata = false) {
5134 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5136 ErrorOr<std::unique_ptr<Module>> Ret =
5137 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5138 MaterializeAll, ShouldLazyLoadMetadata);
5142 Buffer.release(); // The BitcodeReader owns it now.
5146 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5147 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5148 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5149 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5150 DiagnosticHandler, ShouldLazyLoadMetadata);
5153 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5154 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5155 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5156 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5157 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5159 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5163 ErrorOr<std::unique_ptr<Module>>
5164 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5165 DiagnosticHandlerFunction DiagnosticHandler) {
5166 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5167 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5169 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5170 // written. We must defer until the Module has been fully materialized.
5174 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5175 DiagnosticHandlerFunction DiagnosticHandler) {
5176 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5177 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5179 ErrorOr<std::string> Triple = R->parseTriple();
5180 if (Triple.getError())
5182 return Triple.get();