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 "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/DiagnosticPrinter.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/OperandTraits.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/Support/DataStream.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
35 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
38 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
39 DiagnosticSeverity Severity,
41 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
43 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
45 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
46 std::error_code EC, const Twine &Message) {
47 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
48 DiagnosticHandler(DI);
52 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
54 return Error(DiagnosticHandler, EC, EC.message());
57 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
58 return ::Error(DiagnosticHandler, make_error_code(E), Message);
61 std::error_code BitcodeReader::Error(const Twine &Message) {
62 return ::Error(DiagnosticHandler,
63 make_error_code(BitcodeError::CorruptedBitcode), Message);
66 std::error_code BitcodeReader::Error(BitcodeError E) {
67 return ::Error(DiagnosticHandler, make_error_code(E));
70 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
74 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
77 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
78 DiagnosticHandlerFunction DiagnosticHandler)
79 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
80 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
81 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
82 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
83 WillMaterializeAllForwardRefs(false) {}
85 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
86 DiagnosticHandlerFunction DiagnosticHandler)
87 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
88 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
89 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
90 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
91 WillMaterializeAllForwardRefs(false) {}
93 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
94 if (WillMaterializeAllForwardRefs)
95 return std::error_code();
98 WillMaterializeAllForwardRefs = true;
100 while (!BasicBlockFwdRefQueue.empty()) {
101 Function *F = BasicBlockFwdRefQueue.front();
102 BasicBlockFwdRefQueue.pop_front();
103 assert(F && "Expected valid function");
104 if (!BasicBlockFwdRefs.count(F))
105 // Already materialized.
108 // Check for a function that isn't materializable to prevent an infinite
109 // loop. When parsing a blockaddress stored in a global variable, there
110 // isn't a trivial way to check if a function will have a body without a
111 // linear search through FunctionsWithBodies, so just check it here.
112 if (!F->isMaterializable())
113 return Error("Never resolved function from blockaddress");
115 // Try to materialize F.
116 if (std::error_code EC = materialize(F))
119 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
122 WillMaterializeAllForwardRefs = false;
123 return std::error_code();
126 void BitcodeReader::FreeState() {
128 std::vector<Type*>().swap(TypeList);
131 std::vector<Comdat *>().swap(ComdatList);
133 std::vector<AttributeSet>().swap(MAttributes);
134 std::vector<BasicBlock*>().swap(FunctionBBs);
135 std::vector<Function*>().swap(FunctionsWithBodies);
136 DeferredFunctionInfo.clear();
139 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
140 BasicBlockFwdRefQueue.clear();
143 //===----------------------------------------------------------------------===//
144 // Helper functions to implement forward reference resolution, etc.
145 //===----------------------------------------------------------------------===//
147 /// ConvertToString - Convert a string from a record into an std::string, return
149 template<typename StrTy>
150 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
152 if (Idx > Record.size())
155 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
156 Result += (char)Record[i];
160 static bool hasImplicitComdat(size_t Val) {
164 case 1: // Old WeakAnyLinkage
165 case 4: // Old LinkOnceAnyLinkage
166 case 10: // Old WeakODRLinkage
167 case 11: // Old LinkOnceODRLinkage
172 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
174 default: // Map unknown/new linkages to external
176 return GlobalValue::ExternalLinkage;
178 return GlobalValue::AppendingLinkage;
180 return GlobalValue::InternalLinkage;
182 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
184 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
186 return GlobalValue::ExternalWeakLinkage;
188 return GlobalValue::CommonLinkage;
190 return GlobalValue::PrivateLinkage;
192 return GlobalValue::AvailableExternallyLinkage;
194 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
196 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
198 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
199 case 1: // Old value with implicit comdat.
201 return GlobalValue::WeakAnyLinkage;
202 case 10: // Old value with implicit comdat.
204 return GlobalValue::WeakODRLinkage;
205 case 4: // Old value with implicit comdat.
207 return GlobalValue::LinkOnceAnyLinkage;
208 case 11: // Old value with implicit comdat.
210 return GlobalValue::LinkOnceODRLinkage;
214 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
216 default: // Map unknown visibilities to default.
217 case 0: return GlobalValue::DefaultVisibility;
218 case 1: return GlobalValue::HiddenVisibility;
219 case 2: return GlobalValue::ProtectedVisibility;
223 static GlobalValue::DLLStorageClassTypes
224 GetDecodedDLLStorageClass(unsigned Val) {
226 default: // Map unknown values to default.
227 case 0: return GlobalValue::DefaultStorageClass;
228 case 1: return GlobalValue::DLLImportStorageClass;
229 case 2: return GlobalValue::DLLExportStorageClass;
233 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
235 case 0: return GlobalVariable::NotThreadLocal;
236 default: // Map unknown non-zero value to general dynamic.
237 case 1: return GlobalVariable::GeneralDynamicTLSModel;
238 case 2: return GlobalVariable::LocalDynamicTLSModel;
239 case 3: return GlobalVariable::InitialExecTLSModel;
240 case 4: return GlobalVariable::LocalExecTLSModel;
244 static int GetDecodedCastOpcode(unsigned Val) {
247 case bitc::CAST_TRUNC : return Instruction::Trunc;
248 case bitc::CAST_ZEXT : return Instruction::ZExt;
249 case bitc::CAST_SEXT : return Instruction::SExt;
250 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
251 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
252 case bitc::CAST_UITOFP : return Instruction::UIToFP;
253 case bitc::CAST_SITOFP : return Instruction::SIToFP;
254 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
255 case bitc::CAST_FPEXT : return Instruction::FPExt;
256 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
257 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
258 case bitc::CAST_BITCAST : return Instruction::BitCast;
259 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
262 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
265 case bitc::BINOP_ADD:
266 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
267 case bitc::BINOP_SUB:
268 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
269 case bitc::BINOP_MUL:
270 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
271 case bitc::BINOP_UDIV: return Instruction::UDiv;
272 case bitc::BINOP_SDIV:
273 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
274 case bitc::BINOP_UREM: return Instruction::URem;
275 case bitc::BINOP_SREM:
276 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
277 case bitc::BINOP_SHL: return Instruction::Shl;
278 case bitc::BINOP_LSHR: return Instruction::LShr;
279 case bitc::BINOP_ASHR: return Instruction::AShr;
280 case bitc::BINOP_AND: return Instruction::And;
281 case bitc::BINOP_OR: return Instruction::Or;
282 case bitc::BINOP_XOR: return Instruction::Xor;
286 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
288 default: return AtomicRMWInst::BAD_BINOP;
289 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
290 case bitc::RMW_ADD: return AtomicRMWInst::Add;
291 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
292 case bitc::RMW_AND: return AtomicRMWInst::And;
293 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
294 case bitc::RMW_OR: return AtomicRMWInst::Or;
295 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
296 case bitc::RMW_MAX: return AtomicRMWInst::Max;
297 case bitc::RMW_MIN: return AtomicRMWInst::Min;
298 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
299 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
303 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
305 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
306 case bitc::ORDERING_UNORDERED: return Unordered;
307 case bitc::ORDERING_MONOTONIC: return Monotonic;
308 case bitc::ORDERING_ACQUIRE: return Acquire;
309 case bitc::ORDERING_RELEASE: return Release;
310 case bitc::ORDERING_ACQREL: return AcquireRelease;
311 default: // Map unknown orderings to sequentially-consistent.
312 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
316 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
318 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
319 default: // Map unknown scopes to cross-thread.
320 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
324 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
326 default: // Map unknown selection kinds to any.
327 case bitc::COMDAT_SELECTION_KIND_ANY:
329 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
330 return Comdat::ExactMatch;
331 case bitc::COMDAT_SELECTION_KIND_LARGEST:
332 return Comdat::Largest;
333 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
334 return Comdat::NoDuplicates;
335 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
336 return Comdat::SameSize;
340 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
342 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
343 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
349 /// @brief A class for maintaining the slot number definition
350 /// as a placeholder for the actual definition for forward constants defs.
351 class ConstantPlaceHolder : public ConstantExpr {
352 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
354 // allocate space for exactly one operand
355 void *operator new(size_t s) {
356 return User::operator new(s, 1);
358 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
359 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
360 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
363 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
364 static bool classof(const Value *V) {
365 return isa<ConstantExpr>(V) &&
366 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
370 /// Provide fast operand accessors
371 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
375 // FIXME: can we inherit this from ConstantExpr?
377 struct OperandTraits<ConstantPlaceHolder> :
378 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
380 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
384 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
393 WeakVH &OldV = ValuePtrs[Idx];
399 // Handle constants and non-constants (e.g. instrs) differently for
401 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
402 ResolveConstants.push_back(std::make_pair(PHC, Idx));
405 // If there was a forward reference to this value, replace it.
406 Value *PrevVal = OldV;
407 OldV->replaceAllUsesWith(V);
413 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
418 if (Value *V = ValuePtrs[Idx]) {
419 assert(Ty == V->getType() && "Type mismatch in constant table!");
420 return cast<Constant>(V);
423 // Create and return a placeholder, which will later be RAUW'd.
424 Constant *C = new ConstantPlaceHolder(Ty, Context);
429 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
433 if (Value *V = ValuePtrs[Idx]) {
434 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
438 // No type specified, must be invalid reference.
439 if (!Ty) return nullptr;
441 // Create and return a placeholder, which will later be RAUW'd.
442 Value *V = new Argument(Ty);
447 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
448 /// resolves any forward references. The idea behind this is that we sometimes
449 /// get constants (such as large arrays) which reference *many* forward ref
450 /// constants. Replacing each of these causes a lot of thrashing when
451 /// building/reuniquing the constant. Instead of doing this, we look at all the
452 /// uses and rewrite all the place holders at once for any constant that uses
454 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
455 // Sort the values by-pointer so that they are efficient to look up with a
457 std::sort(ResolveConstants.begin(), ResolveConstants.end());
459 SmallVector<Constant*, 64> NewOps;
461 while (!ResolveConstants.empty()) {
462 Value *RealVal = operator[](ResolveConstants.back().second);
463 Constant *Placeholder = ResolveConstants.back().first;
464 ResolveConstants.pop_back();
466 // Loop over all users of the placeholder, updating them to reference the
467 // new value. If they reference more than one placeholder, update them all
469 while (!Placeholder->use_empty()) {
470 auto UI = Placeholder->user_begin();
473 // If the using object isn't uniqued, just update the operands. This
474 // handles instructions and initializers for global variables.
475 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
476 UI.getUse().set(RealVal);
480 // Otherwise, we have a constant that uses the placeholder. Replace that
481 // constant with a new constant that has *all* placeholder uses updated.
482 Constant *UserC = cast<Constant>(U);
483 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
486 if (!isa<ConstantPlaceHolder>(*I)) {
487 // Not a placeholder reference.
489 } else if (*I == Placeholder) {
490 // Common case is that it just references this one placeholder.
493 // Otherwise, look up the placeholder in ResolveConstants.
494 ResolveConstantsTy::iterator It =
495 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
496 std::pair<Constant*, unsigned>(cast<Constant>(*I),
498 assert(It != ResolveConstants.end() && It->first == *I);
499 NewOp = operator[](It->second);
502 NewOps.push_back(cast<Constant>(NewOp));
505 // Make the new constant.
507 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
508 NewC = ConstantArray::get(UserCA->getType(), NewOps);
509 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
510 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
511 } else if (isa<ConstantVector>(UserC)) {
512 NewC = ConstantVector::get(NewOps);
514 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
515 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
518 UserC->replaceAllUsesWith(NewC);
519 UserC->destroyConstant();
523 // Update all ValueHandles, they should be the only users at this point.
524 Placeholder->replaceAllUsesWith(RealVal);
529 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
538 TrackingMDRef &OldMD = MDValuePtrs[Idx];
544 // If there was a forward reference to this value, replace it.
545 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
546 PrevMD->replaceAllUsesWith(MD);
550 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
554 if (Metadata *MD = MDValuePtrs[Idx])
557 // Create and return a placeholder, which will later be RAUW'd.
560 Metadata *MD = MDNode::getTemporary(Context, None).release();
561 MDValuePtrs[Idx].reset(MD);
565 void BitcodeReaderMDValueList::tryToResolveCycles() {
571 // Still forward references... can't resolve cycles.
574 // Resolve any cycles.
575 for (auto &MD : MDValuePtrs) {
576 auto *N = dyn_cast_or_null<MDNode>(MD);
580 assert(!N->isTemporary() && "Unexpected forward reference");
585 Type *BitcodeReader::getTypeByID(unsigned ID) {
586 // The type table size is always specified correctly.
587 if (ID >= TypeList.size())
590 if (Type *Ty = TypeList[ID])
593 // If we have a forward reference, the only possible case is when it is to a
594 // named struct. Just create a placeholder for now.
595 return TypeList[ID] = createIdentifiedStructType(Context);
598 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
600 auto *Ret = StructType::create(Context, Name);
601 IdentifiedStructTypes.push_back(Ret);
605 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
606 auto *Ret = StructType::create(Context);
607 IdentifiedStructTypes.push_back(Ret);
612 //===----------------------------------------------------------------------===//
613 // Functions for parsing blocks from the bitcode file
614 //===----------------------------------------------------------------------===//
617 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
618 /// been decoded from the given integer. This function must stay in sync with
619 /// 'encodeLLVMAttributesForBitcode'.
620 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
621 uint64_t EncodedAttrs) {
622 // FIXME: Remove in 4.0.
624 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
625 // the bits above 31 down by 11 bits.
626 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
627 assert((!Alignment || isPowerOf2_32(Alignment)) &&
628 "Alignment must be a power of two.");
631 B.addAlignmentAttr(Alignment);
632 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
633 (EncodedAttrs & 0xffff));
636 std::error_code BitcodeReader::ParseAttributeBlock() {
637 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
638 return Error("Invalid record");
640 if (!MAttributes.empty())
641 return Error("Invalid multiple blocks");
643 SmallVector<uint64_t, 64> Record;
645 SmallVector<AttributeSet, 8> Attrs;
647 // Read all the records.
649 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
651 switch (Entry.Kind) {
652 case BitstreamEntry::SubBlock: // Handled for us already.
653 case BitstreamEntry::Error:
654 return Error("Malformed block");
655 case BitstreamEntry::EndBlock:
656 return std::error_code();
657 case BitstreamEntry::Record:
658 // The interesting case.
664 switch (Stream.readRecord(Entry.ID, Record)) {
665 default: // Default behavior: ignore.
667 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
668 // FIXME: Remove in 4.0.
669 if (Record.size() & 1)
670 return Error("Invalid record");
672 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
674 decodeLLVMAttributesForBitcode(B, Record[i+1]);
675 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
678 MAttributes.push_back(AttributeSet::get(Context, Attrs));
682 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
683 for (unsigned i = 0, e = Record.size(); i != e; ++i)
684 Attrs.push_back(MAttributeGroups[Record[i]]);
686 MAttributes.push_back(AttributeSet::get(Context, Attrs));
694 // Returns Attribute::None on unrecognized codes.
695 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
698 return Attribute::None;
699 case bitc::ATTR_KIND_ALIGNMENT:
700 return Attribute::Alignment;
701 case bitc::ATTR_KIND_ALWAYS_INLINE:
702 return Attribute::AlwaysInline;
703 case bitc::ATTR_KIND_BUILTIN:
704 return Attribute::Builtin;
705 case bitc::ATTR_KIND_BY_VAL:
706 return Attribute::ByVal;
707 case bitc::ATTR_KIND_IN_ALLOCA:
708 return Attribute::InAlloca;
709 case bitc::ATTR_KIND_COLD:
710 return Attribute::Cold;
711 case bitc::ATTR_KIND_INLINE_HINT:
712 return Attribute::InlineHint;
713 case bitc::ATTR_KIND_IN_REG:
714 return Attribute::InReg;
715 case bitc::ATTR_KIND_JUMP_TABLE:
716 return Attribute::JumpTable;
717 case bitc::ATTR_KIND_MIN_SIZE:
718 return Attribute::MinSize;
719 case bitc::ATTR_KIND_NAKED:
720 return Attribute::Naked;
721 case bitc::ATTR_KIND_NEST:
722 return Attribute::Nest;
723 case bitc::ATTR_KIND_NO_ALIAS:
724 return Attribute::NoAlias;
725 case bitc::ATTR_KIND_NO_BUILTIN:
726 return Attribute::NoBuiltin;
727 case bitc::ATTR_KIND_NO_CAPTURE:
728 return Attribute::NoCapture;
729 case bitc::ATTR_KIND_NO_DUPLICATE:
730 return Attribute::NoDuplicate;
731 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
732 return Attribute::NoImplicitFloat;
733 case bitc::ATTR_KIND_NO_INLINE:
734 return Attribute::NoInline;
735 case bitc::ATTR_KIND_NON_LAZY_BIND:
736 return Attribute::NonLazyBind;
737 case bitc::ATTR_KIND_NON_NULL:
738 return Attribute::NonNull;
739 case bitc::ATTR_KIND_DEREFERENCEABLE:
740 return Attribute::Dereferenceable;
741 case bitc::ATTR_KIND_NO_RED_ZONE:
742 return Attribute::NoRedZone;
743 case bitc::ATTR_KIND_NO_RETURN:
744 return Attribute::NoReturn;
745 case bitc::ATTR_KIND_NO_UNWIND:
746 return Attribute::NoUnwind;
747 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
748 return Attribute::OptimizeForSize;
749 case bitc::ATTR_KIND_OPTIMIZE_NONE:
750 return Attribute::OptimizeNone;
751 case bitc::ATTR_KIND_READ_NONE:
752 return Attribute::ReadNone;
753 case bitc::ATTR_KIND_READ_ONLY:
754 return Attribute::ReadOnly;
755 case bitc::ATTR_KIND_RETURNED:
756 return Attribute::Returned;
757 case bitc::ATTR_KIND_RETURNS_TWICE:
758 return Attribute::ReturnsTwice;
759 case bitc::ATTR_KIND_S_EXT:
760 return Attribute::SExt;
761 case bitc::ATTR_KIND_STACK_ALIGNMENT:
762 return Attribute::StackAlignment;
763 case bitc::ATTR_KIND_STACK_PROTECT:
764 return Attribute::StackProtect;
765 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
766 return Attribute::StackProtectReq;
767 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
768 return Attribute::StackProtectStrong;
769 case bitc::ATTR_KIND_STRUCT_RET:
770 return Attribute::StructRet;
771 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
772 return Attribute::SanitizeAddress;
773 case bitc::ATTR_KIND_SANITIZE_THREAD:
774 return Attribute::SanitizeThread;
775 case bitc::ATTR_KIND_SANITIZE_MEMORY:
776 return Attribute::SanitizeMemory;
777 case bitc::ATTR_KIND_UW_TABLE:
778 return Attribute::UWTable;
779 case bitc::ATTR_KIND_Z_EXT:
780 return Attribute::ZExt;
784 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
785 Attribute::AttrKind *Kind) {
786 *Kind = GetAttrFromCode(Code);
787 if (*Kind == Attribute::None)
788 return Error(BitcodeError::CorruptedBitcode,
789 "Unknown attribute kind (" + Twine(Code) + ")");
790 return std::error_code();
793 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
794 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
795 return Error("Invalid record");
797 if (!MAttributeGroups.empty())
798 return Error("Invalid multiple blocks");
800 SmallVector<uint64_t, 64> Record;
802 // Read all the records.
804 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
806 switch (Entry.Kind) {
807 case BitstreamEntry::SubBlock: // Handled for us already.
808 case BitstreamEntry::Error:
809 return Error("Malformed block");
810 case BitstreamEntry::EndBlock:
811 return std::error_code();
812 case BitstreamEntry::Record:
813 // The interesting case.
819 switch (Stream.readRecord(Entry.ID, Record)) {
820 default: // Default behavior: ignore.
822 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
823 if (Record.size() < 3)
824 return Error("Invalid record");
826 uint64_t GrpID = Record[0];
827 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
830 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
831 if (Record[i] == 0) { // Enum attribute
832 Attribute::AttrKind Kind;
833 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
836 B.addAttribute(Kind);
837 } else if (Record[i] == 1) { // Integer attribute
838 Attribute::AttrKind Kind;
839 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
841 if (Kind == Attribute::Alignment)
842 B.addAlignmentAttr(Record[++i]);
843 else if (Kind == Attribute::StackAlignment)
844 B.addStackAlignmentAttr(Record[++i]);
845 else if (Kind == Attribute::Dereferenceable)
846 B.addDereferenceableAttr(Record[++i]);
847 } else { // String attribute
848 assert((Record[i] == 3 || Record[i] == 4) &&
849 "Invalid attribute group entry");
850 bool HasValue = (Record[i++] == 4);
851 SmallString<64> KindStr;
852 SmallString<64> ValStr;
854 while (Record[i] != 0 && i != e)
855 KindStr += Record[i++];
856 assert(Record[i] == 0 && "Kind string not null terminated");
859 // Has a value associated with it.
860 ++i; // Skip the '0' that terminates the "kind" string.
861 while (Record[i] != 0 && i != e)
862 ValStr += Record[i++];
863 assert(Record[i] == 0 && "Value string not null terminated");
866 B.addAttribute(KindStr.str(), ValStr.str());
870 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
877 std::error_code BitcodeReader::ParseTypeTable() {
878 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
879 return Error("Invalid record");
881 return ParseTypeTableBody();
884 std::error_code BitcodeReader::ParseTypeTableBody() {
885 if (!TypeList.empty())
886 return Error("Invalid multiple blocks");
888 SmallVector<uint64_t, 64> Record;
889 unsigned NumRecords = 0;
891 SmallString<64> TypeName;
893 // Read all the records for this type table.
895 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
897 switch (Entry.Kind) {
898 case BitstreamEntry::SubBlock: // Handled for us already.
899 case BitstreamEntry::Error:
900 return Error("Malformed block");
901 case BitstreamEntry::EndBlock:
902 if (NumRecords != TypeList.size())
903 return Error("Malformed block");
904 return std::error_code();
905 case BitstreamEntry::Record:
906 // The interesting case.
912 Type *ResultTy = nullptr;
913 switch (Stream.readRecord(Entry.ID, Record)) {
915 return Error("Invalid value");
916 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
917 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
918 // type list. This allows us to reserve space.
919 if (Record.size() < 1)
920 return Error("Invalid record");
921 TypeList.resize(Record[0]);
923 case bitc::TYPE_CODE_VOID: // VOID
924 ResultTy = Type::getVoidTy(Context);
926 case bitc::TYPE_CODE_HALF: // HALF
927 ResultTy = Type::getHalfTy(Context);
929 case bitc::TYPE_CODE_FLOAT: // FLOAT
930 ResultTy = Type::getFloatTy(Context);
932 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
933 ResultTy = Type::getDoubleTy(Context);
935 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
936 ResultTy = Type::getX86_FP80Ty(Context);
938 case bitc::TYPE_CODE_FP128: // FP128
939 ResultTy = Type::getFP128Ty(Context);
941 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
942 ResultTy = Type::getPPC_FP128Ty(Context);
944 case bitc::TYPE_CODE_LABEL: // LABEL
945 ResultTy = Type::getLabelTy(Context);
947 case bitc::TYPE_CODE_METADATA: // METADATA
948 ResultTy = Type::getMetadataTy(Context);
950 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
951 ResultTy = Type::getX86_MMXTy(Context);
953 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
954 if (Record.size() < 1)
955 return Error("Invalid record");
957 ResultTy = IntegerType::get(Context, Record[0]);
959 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
960 // [pointee type, address space]
961 if (Record.size() < 1)
962 return Error("Invalid record");
963 unsigned AddressSpace = 0;
964 if (Record.size() == 2)
965 AddressSpace = Record[1];
966 ResultTy = getTypeByID(Record[0]);
968 return Error("Invalid type");
969 ResultTy = PointerType::get(ResultTy, AddressSpace);
972 case bitc::TYPE_CODE_FUNCTION_OLD: {
973 // FIXME: attrid is dead, remove it in LLVM 4.0
974 // FUNCTION: [vararg, attrid, retty, paramty x N]
975 if (Record.size() < 3)
976 return Error("Invalid record");
977 SmallVector<Type*, 8> ArgTys;
978 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
979 if (Type *T = getTypeByID(Record[i]))
985 ResultTy = getTypeByID(Record[2]);
986 if (!ResultTy || ArgTys.size() < Record.size()-3)
987 return Error("Invalid type");
989 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
992 case bitc::TYPE_CODE_FUNCTION: {
993 // FUNCTION: [vararg, retty, paramty x N]
994 if (Record.size() < 2)
995 return Error("Invalid record");
996 SmallVector<Type*, 8> ArgTys;
997 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
998 if (Type *T = getTypeByID(Record[i]))
1004 ResultTy = getTypeByID(Record[1]);
1005 if (!ResultTy || ArgTys.size() < Record.size()-2)
1006 return Error("Invalid type");
1008 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1011 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1012 if (Record.size() < 1)
1013 return Error("Invalid record");
1014 SmallVector<Type*, 8> EltTys;
1015 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1016 if (Type *T = getTypeByID(Record[i]))
1017 EltTys.push_back(T);
1021 if (EltTys.size() != Record.size()-1)
1022 return Error("Invalid type");
1023 ResultTy = StructType::get(Context, EltTys, Record[0]);
1026 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1027 if (ConvertToString(Record, 0, TypeName))
1028 return Error("Invalid record");
1031 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1032 if (Record.size() < 1)
1033 return Error("Invalid record");
1035 if (NumRecords >= TypeList.size())
1036 return Error("Invalid TYPE table");
1038 // Check to see if this was forward referenced, if so fill in the temp.
1039 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1041 Res->setName(TypeName);
1042 TypeList[NumRecords] = nullptr;
1043 } else // Otherwise, create a new struct.
1044 Res = createIdentifiedStructType(Context, TypeName);
1047 SmallVector<Type*, 8> EltTys;
1048 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1049 if (Type *T = getTypeByID(Record[i]))
1050 EltTys.push_back(T);
1054 if (EltTys.size() != Record.size()-1)
1055 return Error("Invalid record");
1056 Res->setBody(EltTys, Record[0]);
1060 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1061 if (Record.size() != 1)
1062 return Error("Invalid record");
1064 if (NumRecords >= TypeList.size())
1065 return Error("Invalid TYPE table");
1067 // Check to see if this was forward referenced, if so fill in the temp.
1068 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1070 Res->setName(TypeName);
1071 TypeList[NumRecords] = nullptr;
1072 } else // Otherwise, create a new struct with no body.
1073 Res = createIdentifiedStructType(Context, TypeName);
1078 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1079 if (Record.size() < 2)
1080 return Error("Invalid record");
1081 if ((ResultTy = getTypeByID(Record[1])))
1082 ResultTy = ArrayType::get(ResultTy, Record[0]);
1084 return Error("Invalid type");
1086 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1087 if (Record.size() < 2)
1088 return Error("Invalid record");
1089 if ((ResultTy = getTypeByID(Record[1])))
1090 ResultTy = VectorType::get(ResultTy, Record[0]);
1092 return Error("Invalid type");
1096 if (NumRecords >= TypeList.size())
1097 return Error("Invalid TYPE table");
1098 assert(ResultTy && "Didn't read a type?");
1099 assert(!TypeList[NumRecords] && "Already read type?");
1100 TypeList[NumRecords++] = ResultTy;
1104 std::error_code BitcodeReader::ParseValueSymbolTable() {
1105 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1106 return Error("Invalid record");
1108 SmallVector<uint64_t, 64> Record;
1110 Triple TT(TheModule->getTargetTriple());
1112 // Read all the records for this value table.
1113 SmallString<128> ValueName;
1115 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1117 switch (Entry.Kind) {
1118 case BitstreamEntry::SubBlock: // Handled for us already.
1119 case BitstreamEntry::Error:
1120 return Error("Malformed block");
1121 case BitstreamEntry::EndBlock:
1122 return std::error_code();
1123 case BitstreamEntry::Record:
1124 // The interesting case.
1130 switch (Stream.readRecord(Entry.ID, Record)) {
1131 default: // Default behavior: unknown type.
1133 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1134 if (ConvertToString(Record, 1, ValueName))
1135 return Error("Invalid record");
1136 unsigned ValueID = Record[0];
1137 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1138 return Error("Invalid record");
1139 Value *V = ValueList[ValueID];
1141 V->setName(StringRef(ValueName.data(), ValueName.size()));
1142 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1143 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1144 if (TT.isOSBinFormatMachO())
1145 GO->setComdat(nullptr);
1147 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1153 case bitc::VST_CODE_BBENTRY: {
1154 if (ConvertToString(Record, 1, ValueName))
1155 return Error("Invalid record");
1156 BasicBlock *BB = getBasicBlock(Record[0]);
1158 return Error("Invalid record");
1160 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1168 std::error_code BitcodeReader::ParseMetadata() {
1169 unsigned NextMDValueNo = MDValueList.size();
1171 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1172 return Error("Invalid record");
1174 SmallVector<uint64_t, 64> Record;
1176 // Read all the records.
1178 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1180 switch (Entry.Kind) {
1181 case BitstreamEntry::SubBlock: // Handled for us already.
1182 case BitstreamEntry::Error:
1183 return Error("Malformed block");
1184 case BitstreamEntry::EndBlock:
1185 MDValueList.tryToResolveCycles();
1186 return std::error_code();
1187 case BitstreamEntry::Record:
1188 // The interesting case.
1194 unsigned Code = Stream.readRecord(Entry.ID, Record);
1195 bool IsDistinct = false;
1197 default: // Default behavior: ignore.
1199 case bitc::METADATA_NAME: {
1200 // Read name of the named metadata.
1201 SmallString<8> Name(Record.begin(), Record.end());
1203 Code = Stream.ReadCode();
1205 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1206 unsigned NextBitCode = Stream.readRecord(Code, Record);
1207 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1209 // Read named metadata elements.
1210 unsigned Size = Record.size();
1211 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1212 for (unsigned i = 0; i != Size; ++i) {
1213 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1215 return Error("Invalid record");
1216 NMD->addOperand(MD);
1220 case bitc::METADATA_OLD_FN_NODE: {
1221 // FIXME: Remove in 4.0.
1222 // This is a LocalAsMetadata record, the only type of function-local
1224 if (Record.size() % 2 == 1)
1225 return Error("Invalid record");
1227 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1228 // to be legal, but there's no upgrade path.
1229 auto dropRecord = [&] {
1230 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1232 if (Record.size() != 2) {
1237 Type *Ty = getTypeByID(Record[0]);
1238 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1243 MDValueList.AssignValue(
1244 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1248 case bitc::METADATA_OLD_NODE: {
1249 // FIXME: Remove in 4.0.
1250 if (Record.size() % 2 == 1)
1251 return Error("Invalid record");
1253 unsigned Size = Record.size();
1254 SmallVector<Metadata *, 8> Elts;
1255 for (unsigned i = 0; i != Size; i += 2) {
1256 Type *Ty = getTypeByID(Record[i]);
1258 return Error("Invalid record");
1259 if (Ty->isMetadataTy())
1260 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1261 else if (!Ty->isVoidTy()) {
1263 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1264 assert(isa<ConstantAsMetadata>(MD) &&
1265 "Expected non-function-local metadata");
1268 Elts.push_back(nullptr);
1270 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1273 case bitc::METADATA_VALUE: {
1274 if (Record.size() != 2)
1275 return Error("Invalid record");
1277 Type *Ty = getTypeByID(Record[0]);
1278 if (Ty->isMetadataTy() || Ty->isVoidTy())
1279 return Error("Invalid record");
1281 MDValueList.AssignValue(
1282 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1286 case bitc::METADATA_DISTINCT_NODE:
1289 case bitc::METADATA_NODE: {
1290 SmallVector<Metadata *, 8> Elts;
1291 Elts.reserve(Record.size());
1292 for (unsigned ID : Record)
1293 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1294 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1295 : MDNode::get(Context, Elts),
1299 case bitc::METADATA_LOCATION: {
1300 if (Record.size() != 5)
1301 return Error("Invalid record");
1303 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1304 unsigned Line = Record[1];
1305 unsigned Column = Record[2];
1306 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1307 Metadata *InlinedAt =
1308 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1309 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1313 case bitc::METADATA_STRING: {
1314 std::string String(Record.begin(), Record.end());
1315 llvm::UpgradeMDStringConstant(String);
1316 Metadata *MD = MDString::get(Context, String);
1317 MDValueList.AssignValue(MD, NextMDValueNo++);
1320 case bitc::METADATA_KIND: {
1321 if (Record.size() < 2)
1322 return Error("Invalid record");
1324 unsigned Kind = Record[0];
1325 SmallString<8> Name(Record.begin()+1, Record.end());
1327 unsigned NewKind = TheModule->getMDKindID(Name.str());
1328 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1329 return Error("Conflicting METADATA_KIND records");
1336 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1337 /// the LSB for dense VBR encoding.
1338 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1343 // There is no such thing as -0 with integers. "-0" really means MININT.
1347 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1348 /// values and aliases that we can.
1349 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1350 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1351 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1352 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1353 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1355 GlobalInitWorklist.swap(GlobalInits);
1356 AliasInitWorklist.swap(AliasInits);
1357 FunctionPrefixWorklist.swap(FunctionPrefixes);
1358 FunctionPrologueWorklist.swap(FunctionPrologues);
1360 while (!GlobalInitWorklist.empty()) {
1361 unsigned ValID = GlobalInitWorklist.back().second;
1362 if (ValID >= ValueList.size()) {
1363 // Not ready to resolve this yet, it requires something later in the file.
1364 GlobalInits.push_back(GlobalInitWorklist.back());
1366 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1367 GlobalInitWorklist.back().first->setInitializer(C);
1369 return Error("Expected a constant");
1371 GlobalInitWorklist.pop_back();
1374 while (!AliasInitWorklist.empty()) {
1375 unsigned ValID = AliasInitWorklist.back().second;
1376 if (ValID >= ValueList.size()) {
1377 AliasInits.push_back(AliasInitWorklist.back());
1379 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1380 AliasInitWorklist.back().first->setAliasee(C);
1382 return Error("Expected a constant");
1384 AliasInitWorklist.pop_back();
1387 while (!FunctionPrefixWorklist.empty()) {
1388 unsigned ValID = FunctionPrefixWorklist.back().second;
1389 if (ValID >= ValueList.size()) {
1390 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1392 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1393 FunctionPrefixWorklist.back().first->setPrefixData(C);
1395 return Error("Expected a constant");
1397 FunctionPrefixWorklist.pop_back();
1400 while (!FunctionPrologueWorklist.empty()) {
1401 unsigned ValID = FunctionPrologueWorklist.back().second;
1402 if (ValID >= ValueList.size()) {
1403 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1405 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1406 FunctionPrologueWorklist.back().first->setPrologueData(C);
1408 return Error("Expected a constant");
1410 FunctionPrologueWorklist.pop_back();
1413 return std::error_code();
1416 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1417 SmallVector<uint64_t, 8> Words(Vals.size());
1418 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1419 BitcodeReader::decodeSignRotatedValue);
1421 return APInt(TypeBits, Words);
1424 std::error_code BitcodeReader::ParseConstants() {
1425 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1426 return Error("Invalid record");
1428 SmallVector<uint64_t, 64> Record;
1430 // Read all the records for this value table.
1431 Type *CurTy = Type::getInt32Ty(Context);
1432 unsigned NextCstNo = ValueList.size();
1434 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1436 switch (Entry.Kind) {
1437 case BitstreamEntry::SubBlock: // Handled for us already.
1438 case BitstreamEntry::Error:
1439 return Error("Malformed block");
1440 case BitstreamEntry::EndBlock:
1441 if (NextCstNo != ValueList.size())
1442 return Error("Invalid ronstant reference");
1444 // Once all the constants have been read, go through and resolve forward
1446 ValueList.ResolveConstantForwardRefs();
1447 return std::error_code();
1448 case BitstreamEntry::Record:
1449 // The interesting case.
1456 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1458 default: // Default behavior: unknown constant
1459 case bitc::CST_CODE_UNDEF: // UNDEF
1460 V = UndefValue::get(CurTy);
1462 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1464 return Error("Invalid record");
1465 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1466 return Error("Invalid record");
1467 CurTy = TypeList[Record[0]];
1468 continue; // Skip the ValueList manipulation.
1469 case bitc::CST_CODE_NULL: // NULL
1470 V = Constant::getNullValue(CurTy);
1472 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1473 if (!CurTy->isIntegerTy() || Record.empty())
1474 return Error("Invalid record");
1475 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1477 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1478 if (!CurTy->isIntegerTy() || Record.empty())
1479 return Error("Invalid record");
1481 APInt VInt = ReadWideAPInt(Record,
1482 cast<IntegerType>(CurTy)->getBitWidth());
1483 V = ConstantInt::get(Context, VInt);
1487 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1489 return Error("Invalid record");
1490 if (CurTy->isHalfTy())
1491 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1492 APInt(16, (uint16_t)Record[0])));
1493 else if (CurTy->isFloatTy())
1494 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1495 APInt(32, (uint32_t)Record[0])));
1496 else if (CurTy->isDoubleTy())
1497 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1498 APInt(64, Record[0])));
1499 else if (CurTy->isX86_FP80Ty()) {
1500 // Bits are not stored the same way as a normal i80 APInt, compensate.
1501 uint64_t Rearrange[2];
1502 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1503 Rearrange[1] = Record[0] >> 48;
1504 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1505 APInt(80, Rearrange)));
1506 } else if (CurTy->isFP128Ty())
1507 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1508 APInt(128, Record)));
1509 else if (CurTy->isPPC_FP128Ty())
1510 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1511 APInt(128, Record)));
1513 V = UndefValue::get(CurTy);
1517 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1519 return Error("Invalid record");
1521 unsigned Size = Record.size();
1522 SmallVector<Constant*, 16> Elts;
1524 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1525 for (unsigned i = 0; i != Size; ++i)
1526 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1527 STy->getElementType(i)));
1528 V = ConstantStruct::get(STy, Elts);
1529 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1530 Type *EltTy = ATy->getElementType();
1531 for (unsigned i = 0; i != Size; ++i)
1532 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1533 V = ConstantArray::get(ATy, Elts);
1534 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1535 Type *EltTy = VTy->getElementType();
1536 for (unsigned i = 0; i != Size; ++i)
1537 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1538 V = ConstantVector::get(Elts);
1540 V = UndefValue::get(CurTy);
1544 case bitc::CST_CODE_STRING: // STRING: [values]
1545 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1547 return Error("Invalid record");
1549 SmallString<16> Elts(Record.begin(), Record.end());
1550 V = ConstantDataArray::getString(Context, Elts,
1551 BitCode == bitc::CST_CODE_CSTRING);
1554 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1556 return Error("Invalid record");
1558 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1559 unsigned Size = Record.size();
1561 if (EltTy->isIntegerTy(8)) {
1562 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1563 if (isa<VectorType>(CurTy))
1564 V = ConstantDataVector::get(Context, Elts);
1566 V = ConstantDataArray::get(Context, Elts);
1567 } else if (EltTy->isIntegerTy(16)) {
1568 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1569 if (isa<VectorType>(CurTy))
1570 V = ConstantDataVector::get(Context, Elts);
1572 V = ConstantDataArray::get(Context, Elts);
1573 } else if (EltTy->isIntegerTy(32)) {
1574 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1575 if (isa<VectorType>(CurTy))
1576 V = ConstantDataVector::get(Context, Elts);
1578 V = ConstantDataArray::get(Context, Elts);
1579 } else if (EltTy->isIntegerTy(64)) {
1580 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1581 if (isa<VectorType>(CurTy))
1582 V = ConstantDataVector::get(Context, Elts);
1584 V = ConstantDataArray::get(Context, Elts);
1585 } else if (EltTy->isFloatTy()) {
1586 SmallVector<float, 16> Elts(Size);
1587 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1588 if (isa<VectorType>(CurTy))
1589 V = ConstantDataVector::get(Context, Elts);
1591 V = ConstantDataArray::get(Context, Elts);
1592 } else if (EltTy->isDoubleTy()) {
1593 SmallVector<double, 16> Elts(Size);
1594 std::transform(Record.begin(), Record.end(), Elts.begin(),
1596 if (isa<VectorType>(CurTy))
1597 V = ConstantDataVector::get(Context, Elts);
1599 V = ConstantDataArray::get(Context, Elts);
1601 return Error("Invalid type for value");
1606 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1607 if (Record.size() < 3)
1608 return Error("Invalid record");
1609 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1611 V = UndefValue::get(CurTy); // Unknown binop.
1613 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1614 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1616 if (Record.size() >= 4) {
1617 if (Opc == Instruction::Add ||
1618 Opc == Instruction::Sub ||
1619 Opc == Instruction::Mul ||
1620 Opc == Instruction::Shl) {
1621 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1622 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1623 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1624 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1625 } else if (Opc == Instruction::SDiv ||
1626 Opc == Instruction::UDiv ||
1627 Opc == Instruction::LShr ||
1628 Opc == Instruction::AShr) {
1629 if (Record[3] & (1 << bitc::PEO_EXACT))
1630 Flags |= SDivOperator::IsExact;
1633 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1637 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1638 if (Record.size() < 3)
1639 return Error("Invalid record");
1640 int Opc = GetDecodedCastOpcode(Record[0]);
1642 V = UndefValue::get(CurTy); // Unknown cast.
1644 Type *OpTy = getTypeByID(Record[1]);
1646 return Error("Invalid record");
1647 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1648 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1649 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1653 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1654 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1655 if (Record.size() & 1)
1656 return Error("Invalid record");
1657 SmallVector<Constant*, 16> Elts;
1658 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1659 Type *ElTy = getTypeByID(Record[i]);
1661 return Error("Invalid record");
1662 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1664 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1665 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1667 bitc::CST_CODE_CE_INBOUNDS_GEP);
1670 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1671 if (Record.size() < 3)
1672 return Error("Invalid record");
1674 Type *SelectorTy = Type::getInt1Ty(Context);
1676 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1677 // vector. Otherwise, it must be a single bit.
1678 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1679 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1680 VTy->getNumElements());
1682 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1684 ValueList.getConstantFwdRef(Record[1],CurTy),
1685 ValueList.getConstantFwdRef(Record[2],CurTy));
1688 case bitc::CST_CODE_CE_EXTRACTELT
1689 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1690 if (Record.size() < 3)
1691 return Error("Invalid record");
1693 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1695 return Error("Invalid record");
1696 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1697 Constant *Op1 = nullptr;
1698 if (Record.size() == 4) {
1699 Type *IdxTy = getTypeByID(Record[2]);
1701 return Error("Invalid record");
1702 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1703 } else // TODO: Remove with llvm 4.0
1704 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1706 return Error("Invalid record");
1707 V = ConstantExpr::getExtractElement(Op0, Op1);
1710 case bitc::CST_CODE_CE_INSERTELT
1711 : { // CE_INSERTELT: [opval, opval, opty, opval]
1712 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1713 if (Record.size() < 3 || !OpTy)
1714 return Error("Invalid record");
1715 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1716 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1717 OpTy->getElementType());
1718 Constant *Op2 = nullptr;
1719 if (Record.size() == 4) {
1720 Type *IdxTy = getTypeByID(Record[2]);
1722 return Error("Invalid record");
1723 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1724 } else // TODO: Remove with llvm 4.0
1725 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1727 return Error("Invalid record");
1728 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1731 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1732 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1733 if (Record.size() < 3 || !OpTy)
1734 return Error("Invalid record");
1735 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1736 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1737 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1738 OpTy->getNumElements());
1739 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1740 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1743 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1744 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1746 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1747 if (Record.size() < 4 || !RTy || !OpTy)
1748 return Error("Invalid record");
1749 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1750 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1751 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1752 RTy->getNumElements());
1753 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1754 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1757 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1758 if (Record.size() < 4)
1759 return Error("Invalid record");
1760 Type *OpTy = getTypeByID(Record[0]);
1762 return Error("Invalid record");
1763 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1764 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1766 if (OpTy->isFPOrFPVectorTy())
1767 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1769 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1772 // This maintains backward compatibility, pre-asm dialect keywords.
1773 // FIXME: Remove with the 4.0 release.
1774 case bitc::CST_CODE_INLINEASM_OLD: {
1775 if (Record.size() < 2)
1776 return Error("Invalid record");
1777 std::string AsmStr, ConstrStr;
1778 bool HasSideEffects = Record[0] & 1;
1779 bool IsAlignStack = Record[0] >> 1;
1780 unsigned AsmStrSize = Record[1];
1781 if (2+AsmStrSize >= Record.size())
1782 return Error("Invalid record");
1783 unsigned ConstStrSize = Record[2+AsmStrSize];
1784 if (3+AsmStrSize+ConstStrSize > Record.size())
1785 return Error("Invalid record");
1787 for (unsigned i = 0; i != AsmStrSize; ++i)
1788 AsmStr += (char)Record[2+i];
1789 for (unsigned i = 0; i != ConstStrSize; ++i)
1790 ConstrStr += (char)Record[3+AsmStrSize+i];
1791 PointerType *PTy = cast<PointerType>(CurTy);
1792 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1793 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1796 // This version adds support for the asm dialect keywords (e.g.,
1798 case bitc::CST_CODE_INLINEASM: {
1799 if (Record.size() < 2)
1800 return Error("Invalid record");
1801 std::string AsmStr, ConstrStr;
1802 bool HasSideEffects = Record[0] & 1;
1803 bool IsAlignStack = (Record[0] >> 1) & 1;
1804 unsigned AsmDialect = Record[0] >> 2;
1805 unsigned AsmStrSize = Record[1];
1806 if (2+AsmStrSize >= Record.size())
1807 return Error("Invalid record");
1808 unsigned ConstStrSize = Record[2+AsmStrSize];
1809 if (3+AsmStrSize+ConstStrSize > Record.size())
1810 return Error("Invalid record");
1812 for (unsigned i = 0; i != AsmStrSize; ++i)
1813 AsmStr += (char)Record[2+i];
1814 for (unsigned i = 0; i != ConstStrSize; ++i)
1815 ConstrStr += (char)Record[3+AsmStrSize+i];
1816 PointerType *PTy = cast<PointerType>(CurTy);
1817 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1818 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1819 InlineAsm::AsmDialect(AsmDialect));
1822 case bitc::CST_CODE_BLOCKADDRESS:{
1823 if (Record.size() < 3)
1824 return Error("Invalid record");
1825 Type *FnTy = getTypeByID(Record[0]);
1827 return Error("Invalid record");
1829 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1831 return Error("Invalid record");
1833 // Don't let Fn get dematerialized.
1834 BlockAddressesTaken.insert(Fn);
1836 // If the function is already parsed we can insert the block address right
1839 unsigned BBID = Record[2];
1841 // Invalid reference to entry block.
1842 return Error("Invalid ID");
1844 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1845 for (size_t I = 0, E = BBID; I != E; ++I) {
1847 return Error("Invalid ID");
1852 // Otherwise insert a placeholder and remember it so it can be inserted
1853 // when the function is parsed.
1854 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1856 BasicBlockFwdRefQueue.push_back(Fn);
1857 if (FwdBBs.size() < BBID + 1)
1858 FwdBBs.resize(BBID + 1);
1860 FwdBBs[BBID] = BasicBlock::Create(Context);
1863 V = BlockAddress::get(Fn, BB);
1868 ValueList.AssignValue(V, NextCstNo);
1873 std::error_code BitcodeReader::ParseUseLists() {
1874 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1875 return Error("Invalid record");
1877 // Read all the records.
1878 SmallVector<uint64_t, 64> Record;
1880 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1882 switch (Entry.Kind) {
1883 case BitstreamEntry::SubBlock: // Handled for us already.
1884 case BitstreamEntry::Error:
1885 return Error("Malformed block");
1886 case BitstreamEntry::EndBlock:
1887 return std::error_code();
1888 case BitstreamEntry::Record:
1889 // The interesting case.
1893 // Read a use list record.
1896 switch (Stream.readRecord(Entry.ID, Record)) {
1897 default: // Default behavior: unknown type.
1899 case bitc::USELIST_CODE_BB:
1902 case bitc::USELIST_CODE_DEFAULT: {
1903 unsigned RecordLength = Record.size();
1904 if (RecordLength < 3)
1905 // Records should have at least an ID and two indexes.
1906 return Error("Invalid record");
1907 unsigned ID = Record.back();
1912 assert(ID < FunctionBBs.size() && "Basic block not found");
1913 V = FunctionBBs[ID];
1916 unsigned NumUses = 0;
1917 SmallDenseMap<const Use *, unsigned, 16> Order;
1918 for (const Use &U : V->uses()) {
1919 if (++NumUses > Record.size())
1921 Order[&U] = Record[NumUses - 1];
1923 if (Order.size() != Record.size() || NumUses > Record.size())
1924 // Mismatches can happen if the functions are being materialized lazily
1925 // (out-of-order), or a value has been upgraded.
1928 V->sortUseList([&](const Use &L, const Use &R) {
1929 return Order.lookup(&L) < Order.lookup(&R);
1937 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1938 /// remember where it is and then skip it. This lets us lazily deserialize the
1940 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1941 // Get the function we are talking about.
1942 if (FunctionsWithBodies.empty())
1943 return Error("Insufficient function protos");
1945 Function *Fn = FunctionsWithBodies.back();
1946 FunctionsWithBodies.pop_back();
1948 // Save the current stream state.
1949 uint64_t CurBit = Stream.GetCurrentBitNo();
1950 DeferredFunctionInfo[Fn] = CurBit;
1952 // Skip over the function block for now.
1953 if (Stream.SkipBlock())
1954 return Error("Invalid record");
1955 return std::error_code();
1958 std::error_code BitcodeReader::GlobalCleanup() {
1959 // Patch the initializers for globals and aliases up.
1960 ResolveGlobalAndAliasInits();
1961 if (!GlobalInits.empty() || !AliasInits.empty())
1962 return Error("Malformed global initializer set");
1964 // Look for intrinsic functions which need to be upgraded at some point
1965 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1968 if (UpgradeIntrinsicFunction(FI, NewFn))
1969 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1972 // Look for global variables which need to be renamed.
1973 for (Module::global_iterator
1974 GI = TheModule->global_begin(), GE = TheModule->global_end();
1976 GlobalVariable *GV = GI++;
1977 UpgradeGlobalVariable(GV);
1980 // Force deallocation of memory for these vectors to favor the client that
1981 // want lazy deserialization.
1982 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1983 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1984 return std::error_code();
1987 std::error_code BitcodeReader::ParseModule(bool Resume) {
1989 Stream.JumpToBit(NextUnreadBit);
1990 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1991 return Error("Invalid record");
1993 SmallVector<uint64_t, 64> Record;
1994 std::vector<std::string> SectionTable;
1995 std::vector<std::string> GCTable;
1997 // Read all the records for this module.
1999 BitstreamEntry Entry = Stream.advance();
2001 switch (Entry.Kind) {
2002 case BitstreamEntry::Error:
2003 return Error("Malformed block");
2004 case BitstreamEntry::EndBlock:
2005 return GlobalCleanup();
2007 case BitstreamEntry::SubBlock:
2009 default: // Skip unknown content.
2010 if (Stream.SkipBlock())
2011 return Error("Invalid record");
2013 case bitc::BLOCKINFO_BLOCK_ID:
2014 if (Stream.ReadBlockInfoBlock())
2015 return Error("Malformed block");
2017 case bitc::PARAMATTR_BLOCK_ID:
2018 if (std::error_code EC = ParseAttributeBlock())
2021 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2022 if (std::error_code EC = ParseAttributeGroupBlock())
2025 case bitc::TYPE_BLOCK_ID_NEW:
2026 if (std::error_code EC = ParseTypeTable())
2029 case bitc::VALUE_SYMTAB_BLOCK_ID:
2030 if (std::error_code EC = ParseValueSymbolTable())
2032 SeenValueSymbolTable = true;
2034 case bitc::CONSTANTS_BLOCK_ID:
2035 if (std::error_code EC = ParseConstants())
2037 if (std::error_code EC = ResolveGlobalAndAliasInits())
2040 case bitc::METADATA_BLOCK_ID:
2041 if (std::error_code EC = ParseMetadata())
2044 case bitc::FUNCTION_BLOCK_ID:
2045 // If this is the first function body we've seen, reverse the
2046 // FunctionsWithBodies list.
2047 if (!SeenFirstFunctionBody) {
2048 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2049 if (std::error_code EC = GlobalCleanup())
2051 SeenFirstFunctionBody = true;
2054 if (std::error_code EC = RememberAndSkipFunctionBody())
2056 // For streaming bitcode, suspend parsing when we reach the function
2057 // bodies. Subsequent materialization calls will resume it when
2058 // necessary. For streaming, the function bodies must be at the end of
2059 // the bitcode. If the bitcode file is old, the symbol table will be
2060 // at the end instead and will not have been seen yet. In this case,
2061 // just finish the parse now.
2062 if (LazyStreamer && SeenValueSymbolTable) {
2063 NextUnreadBit = Stream.GetCurrentBitNo();
2064 return std::error_code();
2067 case bitc::USELIST_BLOCK_ID:
2068 if (std::error_code EC = ParseUseLists())
2074 case BitstreamEntry::Record:
2075 // The interesting case.
2081 switch (Stream.readRecord(Entry.ID, Record)) {
2082 default: break; // Default behavior, ignore unknown content.
2083 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2084 if (Record.size() < 1)
2085 return Error("Invalid record");
2086 // Only version #0 and #1 are supported so far.
2087 unsigned module_version = Record[0];
2088 switch (module_version) {
2090 return Error("Invalid value");
2092 UseRelativeIDs = false;
2095 UseRelativeIDs = true;
2100 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2102 if (ConvertToString(Record, 0, S))
2103 return Error("Invalid record");
2104 TheModule->setTargetTriple(S);
2107 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2109 if (ConvertToString(Record, 0, S))
2110 return Error("Invalid record");
2111 TheModule->setDataLayout(S);
2114 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2116 if (ConvertToString(Record, 0, S))
2117 return Error("Invalid record");
2118 TheModule->setModuleInlineAsm(S);
2121 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2122 // FIXME: Remove in 4.0.
2124 if (ConvertToString(Record, 0, S))
2125 return Error("Invalid record");
2129 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2131 if (ConvertToString(Record, 0, S))
2132 return Error("Invalid record");
2133 SectionTable.push_back(S);
2136 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2138 if (ConvertToString(Record, 0, S))
2139 return Error("Invalid record");
2140 GCTable.push_back(S);
2143 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2144 if (Record.size() < 2)
2145 return Error("Invalid record");
2146 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2147 unsigned ComdatNameSize = Record[1];
2148 std::string ComdatName;
2149 ComdatName.reserve(ComdatNameSize);
2150 for (unsigned i = 0; i != ComdatNameSize; ++i)
2151 ComdatName += (char)Record[2 + i];
2152 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2153 C->setSelectionKind(SK);
2154 ComdatList.push_back(C);
2157 // GLOBALVAR: [pointer type, isconst, initid,
2158 // linkage, alignment, section, visibility, threadlocal,
2159 // unnamed_addr, dllstorageclass]
2160 case bitc::MODULE_CODE_GLOBALVAR: {
2161 if (Record.size() < 6)
2162 return Error("Invalid record");
2163 Type *Ty = getTypeByID(Record[0]);
2165 return Error("Invalid record");
2166 if (!Ty->isPointerTy())
2167 return Error("Invalid type for value");
2168 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2169 Ty = cast<PointerType>(Ty)->getElementType();
2171 bool isConstant = Record[1];
2172 uint64_t RawLinkage = Record[3];
2173 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2174 unsigned Alignment = (1 << Record[4]) >> 1;
2175 std::string Section;
2177 if (Record[5]-1 >= SectionTable.size())
2178 return Error("Invalid ID");
2179 Section = SectionTable[Record[5]-1];
2181 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2182 // Local linkage must have default visibility.
2183 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2184 // FIXME: Change to an error if non-default in 4.0.
2185 Visibility = GetDecodedVisibility(Record[6]);
2187 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2188 if (Record.size() > 7)
2189 TLM = GetDecodedThreadLocalMode(Record[7]);
2191 bool UnnamedAddr = false;
2192 if (Record.size() > 8)
2193 UnnamedAddr = Record[8];
2195 bool ExternallyInitialized = false;
2196 if (Record.size() > 9)
2197 ExternallyInitialized = Record[9];
2199 GlobalVariable *NewGV =
2200 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2201 TLM, AddressSpace, ExternallyInitialized);
2202 NewGV->setAlignment(Alignment);
2203 if (!Section.empty())
2204 NewGV->setSection(Section);
2205 NewGV->setVisibility(Visibility);
2206 NewGV->setUnnamedAddr(UnnamedAddr);
2208 if (Record.size() > 10)
2209 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2211 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2213 ValueList.push_back(NewGV);
2215 // Remember which value to use for the global initializer.
2216 if (unsigned InitID = Record[2])
2217 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2219 if (Record.size() > 11) {
2220 if (unsigned ComdatID = Record[11]) {
2221 assert(ComdatID <= ComdatList.size());
2222 NewGV->setComdat(ComdatList[ComdatID - 1]);
2224 } else if (hasImplicitComdat(RawLinkage)) {
2225 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2229 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2230 // alignment, section, visibility, gc, unnamed_addr,
2231 // prologuedata, dllstorageclass, comdat, prefixdata]
2232 case bitc::MODULE_CODE_FUNCTION: {
2233 if (Record.size() < 8)
2234 return Error("Invalid record");
2235 Type *Ty = getTypeByID(Record[0]);
2237 return Error("Invalid record");
2238 if (!Ty->isPointerTy())
2239 return Error("Invalid type for value");
2241 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2243 return Error("Invalid type for value");
2245 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2248 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2249 bool isProto = Record[2];
2250 uint64_t RawLinkage = Record[3];
2251 Func->setLinkage(getDecodedLinkage(RawLinkage));
2252 Func->setAttributes(getAttributes(Record[4]));
2254 Func->setAlignment((1 << Record[5]) >> 1);
2256 if (Record[6]-1 >= SectionTable.size())
2257 return Error("Invalid ID");
2258 Func->setSection(SectionTable[Record[6]-1]);
2260 // Local linkage must have default visibility.
2261 if (!Func->hasLocalLinkage())
2262 // FIXME: Change to an error if non-default in 4.0.
2263 Func->setVisibility(GetDecodedVisibility(Record[7]));
2264 if (Record.size() > 8 && Record[8]) {
2265 if (Record[8]-1 > GCTable.size())
2266 return Error("Invalid ID");
2267 Func->setGC(GCTable[Record[8]-1].c_str());
2269 bool UnnamedAddr = false;
2270 if (Record.size() > 9)
2271 UnnamedAddr = Record[9];
2272 Func->setUnnamedAddr(UnnamedAddr);
2273 if (Record.size() > 10 && Record[10] != 0)
2274 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2276 if (Record.size() > 11)
2277 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2279 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2281 if (Record.size() > 12) {
2282 if (unsigned ComdatID = Record[12]) {
2283 assert(ComdatID <= ComdatList.size());
2284 Func->setComdat(ComdatList[ComdatID - 1]);
2286 } else if (hasImplicitComdat(RawLinkage)) {
2287 Func->setComdat(reinterpret_cast<Comdat *>(1));
2290 if (Record.size() > 13 && Record[13] != 0)
2291 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2293 ValueList.push_back(Func);
2295 // If this is a function with a body, remember the prototype we are
2296 // creating now, so that we can match up the body with them later.
2298 Func->setIsMaterializable(true);
2299 FunctionsWithBodies.push_back(Func);
2301 DeferredFunctionInfo[Func] = 0;
2305 // ALIAS: [alias type, aliasee val#, linkage]
2306 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2307 case bitc::MODULE_CODE_ALIAS: {
2308 if (Record.size() < 3)
2309 return Error("Invalid record");
2310 Type *Ty = getTypeByID(Record[0]);
2312 return Error("Invalid record");
2313 auto *PTy = dyn_cast<PointerType>(Ty);
2315 return Error("Invalid type for value");
2318 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2319 getDecodedLinkage(Record[2]), "", TheModule);
2320 // Old bitcode files didn't have visibility field.
2321 // Local linkage must have default visibility.
2322 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2323 // FIXME: Change to an error if non-default in 4.0.
2324 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2325 if (Record.size() > 4)
2326 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2328 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2329 if (Record.size() > 5)
2330 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2331 if (Record.size() > 6)
2332 NewGA->setUnnamedAddr(Record[6]);
2333 ValueList.push_back(NewGA);
2334 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2337 /// MODULE_CODE_PURGEVALS: [numvals]
2338 case bitc::MODULE_CODE_PURGEVALS:
2339 // Trim down the value list to the specified size.
2340 if (Record.size() < 1 || Record[0] > ValueList.size())
2341 return Error("Invalid record");
2342 ValueList.shrinkTo(Record[0]);
2349 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2350 TheModule = nullptr;
2352 if (std::error_code EC = InitStream())
2355 // Sniff for the signature.
2356 if (Stream.Read(8) != 'B' ||
2357 Stream.Read(8) != 'C' ||
2358 Stream.Read(4) != 0x0 ||
2359 Stream.Read(4) != 0xC ||
2360 Stream.Read(4) != 0xE ||
2361 Stream.Read(4) != 0xD)
2362 return Error("Invalid bitcode signature");
2364 // We expect a number of well-defined blocks, though we don't necessarily
2365 // need to understand them all.
2367 if (Stream.AtEndOfStream())
2368 return std::error_code();
2370 BitstreamEntry Entry =
2371 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2373 switch (Entry.Kind) {
2374 case BitstreamEntry::Error:
2375 return Error("Malformed block");
2376 case BitstreamEntry::EndBlock:
2377 return std::error_code();
2379 case BitstreamEntry::SubBlock:
2381 case bitc::BLOCKINFO_BLOCK_ID:
2382 if (Stream.ReadBlockInfoBlock())
2383 return Error("Malformed block");
2385 case bitc::MODULE_BLOCK_ID:
2386 // Reject multiple MODULE_BLOCK's in a single bitstream.
2388 return Error("Invalid multiple blocks");
2390 if (std::error_code EC = ParseModule(false))
2393 return std::error_code();
2396 if (Stream.SkipBlock())
2397 return Error("Invalid record");
2401 case BitstreamEntry::Record:
2402 // There should be no records in the top-level of blocks.
2404 // The ranlib in Xcode 4 will align archive members by appending newlines
2405 // to the end of them. If this file size is a multiple of 4 but not 8, we
2406 // have to read and ignore these final 4 bytes :-(
2407 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2408 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2409 Stream.AtEndOfStream())
2410 return std::error_code();
2412 return Error("Invalid record");
2417 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2418 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2419 return Error("Invalid record");
2421 SmallVector<uint64_t, 64> Record;
2424 // Read all the records for this module.
2426 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2428 switch (Entry.Kind) {
2429 case BitstreamEntry::SubBlock: // Handled for us already.
2430 case BitstreamEntry::Error:
2431 return Error("Malformed block");
2432 case BitstreamEntry::EndBlock:
2434 case BitstreamEntry::Record:
2435 // The interesting case.
2440 switch (Stream.readRecord(Entry.ID, Record)) {
2441 default: break; // Default behavior, ignore unknown content.
2442 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2444 if (ConvertToString(Record, 0, S))
2445 return Error("Invalid record");
2452 llvm_unreachable("Exit infinite loop");
2455 ErrorOr<std::string> BitcodeReader::parseTriple() {
2456 if (std::error_code EC = InitStream())
2459 // Sniff for the signature.
2460 if (Stream.Read(8) != 'B' ||
2461 Stream.Read(8) != 'C' ||
2462 Stream.Read(4) != 0x0 ||
2463 Stream.Read(4) != 0xC ||
2464 Stream.Read(4) != 0xE ||
2465 Stream.Read(4) != 0xD)
2466 return Error("Invalid bitcode signature");
2468 // We expect a number of well-defined blocks, though we don't necessarily
2469 // need to understand them all.
2471 BitstreamEntry Entry = Stream.advance();
2473 switch (Entry.Kind) {
2474 case BitstreamEntry::Error:
2475 return Error("Malformed block");
2476 case BitstreamEntry::EndBlock:
2477 return std::error_code();
2479 case BitstreamEntry::SubBlock:
2480 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2481 return parseModuleTriple();
2483 // Ignore other sub-blocks.
2484 if (Stream.SkipBlock())
2485 return Error("Malformed block");
2488 case BitstreamEntry::Record:
2489 Stream.skipRecord(Entry.ID);
2495 /// ParseMetadataAttachment - Parse metadata attachments.
2496 std::error_code BitcodeReader::ParseMetadataAttachment() {
2497 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2498 return Error("Invalid record");
2500 SmallVector<uint64_t, 64> Record;
2502 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2504 switch (Entry.Kind) {
2505 case BitstreamEntry::SubBlock: // Handled for us already.
2506 case BitstreamEntry::Error:
2507 return Error("Malformed block");
2508 case BitstreamEntry::EndBlock:
2509 return std::error_code();
2510 case BitstreamEntry::Record:
2511 // The interesting case.
2515 // Read a metadata attachment record.
2517 switch (Stream.readRecord(Entry.ID, Record)) {
2518 default: // Default behavior: ignore.
2520 case bitc::METADATA_ATTACHMENT: {
2521 unsigned RecordLength = Record.size();
2522 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2523 return Error("Invalid record");
2524 Instruction *Inst = InstructionList[Record[0]];
2525 for (unsigned i = 1; i != RecordLength; i = i+2) {
2526 unsigned Kind = Record[i];
2527 DenseMap<unsigned, unsigned>::iterator I =
2528 MDKindMap.find(Kind);
2529 if (I == MDKindMap.end())
2530 return Error("Invalid ID");
2531 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2532 if (isa<LocalAsMetadata>(Node))
2533 // Drop the attachment. This used to be legal, but there's no
2536 Inst->setMetadata(I->second, cast<MDNode>(Node));
2537 if (I->second == LLVMContext::MD_tbaa)
2538 InstsWithTBAATag.push_back(Inst);
2546 /// ParseFunctionBody - Lazily parse the specified function body block.
2547 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2548 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2549 return Error("Invalid record");
2551 InstructionList.clear();
2552 unsigned ModuleValueListSize = ValueList.size();
2553 unsigned ModuleMDValueListSize = MDValueList.size();
2555 // Add all the function arguments to the value table.
2556 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2557 ValueList.push_back(I);
2559 unsigned NextValueNo = ValueList.size();
2560 BasicBlock *CurBB = nullptr;
2561 unsigned CurBBNo = 0;
2564 auto getLastInstruction = [&]() -> Instruction * {
2565 if (CurBB && !CurBB->empty())
2566 return &CurBB->back();
2567 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2568 !FunctionBBs[CurBBNo - 1]->empty())
2569 return &FunctionBBs[CurBBNo - 1]->back();
2573 // Read all the records.
2574 SmallVector<uint64_t, 64> Record;
2576 BitstreamEntry Entry = Stream.advance();
2578 switch (Entry.Kind) {
2579 case BitstreamEntry::Error:
2580 return Error("Malformed block");
2581 case BitstreamEntry::EndBlock:
2582 goto OutOfRecordLoop;
2584 case BitstreamEntry::SubBlock:
2586 default: // Skip unknown content.
2587 if (Stream.SkipBlock())
2588 return Error("Invalid record");
2590 case bitc::CONSTANTS_BLOCK_ID:
2591 if (std::error_code EC = ParseConstants())
2593 NextValueNo = ValueList.size();
2595 case bitc::VALUE_SYMTAB_BLOCK_ID:
2596 if (std::error_code EC = ParseValueSymbolTable())
2599 case bitc::METADATA_ATTACHMENT_ID:
2600 if (std::error_code EC = ParseMetadataAttachment())
2603 case bitc::METADATA_BLOCK_ID:
2604 if (std::error_code EC = ParseMetadata())
2607 case bitc::USELIST_BLOCK_ID:
2608 if (std::error_code EC = ParseUseLists())
2614 case BitstreamEntry::Record:
2615 // The interesting case.
2621 Instruction *I = nullptr;
2622 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2624 default: // Default behavior: reject
2625 return Error("Invalid value");
2626 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2627 if (Record.size() < 1 || Record[0] == 0)
2628 return Error("Invalid record");
2629 // Create all the basic blocks for the function.
2630 FunctionBBs.resize(Record[0]);
2632 // See if anything took the address of blocks in this function.
2633 auto BBFRI = BasicBlockFwdRefs.find(F);
2634 if (BBFRI == BasicBlockFwdRefs.end()) {
2635 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2636 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2638 auto &BBRefs = BBFRI->second;
2639 // Check for invalid basic block references.
2640 if (BBRefs.size() > FunctionBBs.size())
2641 return Error("Invalid ID");
2642 assert(!BBRefs.empty() && "Unexpected empty array");
2643 assert(!BBRefs.front() && "Invalid reference to entry block");
2644 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2646 if (I < RE && BBRefs[I]) {
2647 BBRefs[I]->insertInto(F);
2648 FunctionBBs[I] = BBRefs[I];
2650 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2653 // Erase from the table.
2654 BasicBlockFwdRefs.erase(BBFRI);
2657 CurBB = FunctionBBs[0];
2661 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2662 // This record indicates that the last instruction is at the same
2663 // location as the previous instruction with a location.
2664 I = getLastInstruction();
2667 return Error("Invalid record");
2668 I->setDebugLoc(LastLoc);
2672 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2673 I = getLastInstruction();
2674 if (!I || Record.size() < 4)
2675 return Error("Invalid record");
2677 unsigned Line = Record[0], Col = Record[1];
2678 unsigned ScopeID = Record[2], IAID = Record[3];
2680 MDNode *Scope = nullptr, *IA = nullptr;
2681 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2682 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2683 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2684 I->setDebugLoc(LastLoc);
2689 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2692 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2693 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2694 OpNum+1 > Record.size())
2695 return Error("Invalid record");
2697 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2699 return Error("Invalid record");
2700 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2701 InstructionList.push_back(I);
2702 if (OpNum < Record.size()) {
2703 if (Opc == Instruction::Add ||
2704 Opc == Instruction::Sub ||
2705 Opc == Instruction::Mul ||
2706 Opc == Instruction::Shl) {
2707 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2708 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2709 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2710 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2711 } else if (Opc == Instruction::SDiv ||
2712 Opc == Instruction::UDiv ||
2713 Opc == Instruction::LShr ||
2714 Opc == Instruction::AShr) {
2715 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2716 cast<BinaryOperator>(I)->setIsExact(true);
2717 } else if (isa<FPMathOperator>(I)) {
2719 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2720 FMF.setUnsafeAlgebra();
2721 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2723 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2725 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2726 FMF.setNoSignedZeros();
2727 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2728 FMF.setAllowReciprocal();
2730 I->setFastMathFlags(FMF);
2736 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2739 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2740 OpNum+2 != Record.size())
2741 return Error("Invalid record");
2743 Type *ResTy = getTypeByID(Record[OpNum]);
2744 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2745 if (Opc == -1 || !ResTy)
2746 return Error("Invalid record");
2747 Instruction *Temp = nullptr;
2748 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2750 InstructionList.push_back(Temp);
2751 CurBB->getInstList().push_back(Temp);
2754 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2756 InstructionList.push_back(I);
2759 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2760 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2763 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2764 return Error("Invalid record");
2766 SmallVector<Value*, 16> GEPIdx;
2767 while (OpNum != Record.size()) {
2769 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2770 return Error("Invalid record");
2771 GEPIdx.push_back(Op);
2774 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2775 InstructionList.push_back(I);
2776 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2777 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2781 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2782 // EXTRACTVAL: [opty, opval, n x indices]
2785 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2786 return Error("Invalid record");
2788 SmallVector<unsigned, 4> EXTRACTVALIdx;
2789 for (unsigned RecSize = Record.size();
2790 OpNum != RecSize; ++OpNum) {
2791 uint64_t Index = Record[OpNum];
2792 if ((unsigned)Index != Index)
2793 return Error("Invalid value");
2794 EXTRACTVALIdx.push_back((unsigned)Index);
2797 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2798 InstructionList.push_back(I);
2802 case bitc::FUNC_CODE_INST_INSERTVAL: {
2803 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2806 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2807 return Error("Invalid record");
2809 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2810 return Error("Invalid record");
2812 SmallVector<unsigned, 4> INSERTVALIdx;
2813 for (unsigned RecSize = Record.size();
2814 OpNum != RecSize; ++OpNum) {
2815 uint64_t Index = Record[OpNum];
2816 if ((unsigned)Index != Index)
2817 return Error("Invalid value");
2818 INSERTVALIdx.push_back((unsigned)Index);
2821 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2822 InstructionList.push_back(I);
2826 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2827 // obsolete form of select
2828 // handles select i1 ... in old bitcode
2830 Value *TrueVal, *FalseVal, *Cond;
2831 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2832 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2833 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2834 return Error("Invalid record");
2836 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2837 InstructionList.push_back(I);
2841 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2842 // new form of select
2843 // handles select i1 or select [N x i1]
2845 Value *TrueVal, *FalseVal, *Cond;
2846 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2847 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2848 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2849 return Error("Invalid record");
2851 // select condition can be either i1 or [N x i1]
2852 if (VectorType* vector_type =
2853 dyn_cast<VectorType>(Cond->getType())) {
2855 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2856 return Error("Invalid type for value");
2859 if (Cond->getType() != Type::getInt1Ty(Context))
2860 return Error("Invalid type for value");
2863 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2864 InstructionList.push_back(I);
2868 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2871 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2872 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2873 return Error("Invalid record");
2874 I = ExtractElementInst::Create(Vec, Idx);
2875 InstructionList.push_back(I);
2879 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2881 Value *Vec, *Elt, *Idx;
2882 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2883 popValue(Record, OpNum, NextValueNo,
2884 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2885 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2886 return Error("Invalid record");
2887 I = InsertElementInst::Create(Vec, Elt, Idx);
2888 InstructionList.push_back(I);
2892 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2894 Value *Vec1, *Vec2, *Mask;
2895 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2896 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2897 return Error("Invalid record");
2899 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2900 return Error("Invalid record");
2901 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2902 InstructionList.push_back(I);
2906 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2907 // Old form of ICmp/FCmp returning bool
2908 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2909 // both legal on vectors but had different behaviour.
2910 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2911 // FCmp/ICmp returning bool or vector of bool
2915 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2916 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2917 OpNum+1 != Record.size())
2918 return Error("Invalid record");
2920 if (LHS->getType()->isFPOrFPVectorTy())
2921 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2923 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2924 InstructionList.push_back(I);
2928 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2930 unsigned Size = Record.size();
2932 I = ReturnInst::Create(Context);
2933 InstructionList.push_back(I);
2938 Value *Op = nullptr;
2939 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2940 return Error("Invalid record");
2941 if (OpNum != Record.size())
2942 return Error("Invalid record");
2944 I = ReturnInst::Create(Context, Op);
2945 InstructionList.push_back(I);
2948 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2949 if (Record.size() != 1 && Record.size() != 3)
2950 return Error("Invalid record");
2951 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2953 return Error("Invalid record");
2955 if (Record.size() == 1) {
2956 I = BranchInst::Create(TrueDest);
2957 InstructionList.push_back(I);
2960 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2961 Value *Cond = getValue(Record, 2, NextValueNo,
2962 Type::getInt1Ty(Context));
2963 if (!FalseDest || !Cond)
2964 return Error("Invalid record");
2965 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2966 InstructionList.push_back(I);
2970 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2972 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2973 // "New" SwitchInst format with case ranges. The changes to write this
2974 // format were reverted but we still recognize bitcode that uses it.
2975 // Hopefully someday we will have support for case ranges and can use
2976 // this format again.
2978 Type *OpTy = getTypeByID(Record[1]);
2979 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2981 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2982 BasicBlock *Default = getBasicBlock(Record[3]);
2983 if (!OpTy || !Cond || !Default)
2984 return Error("Invalid record");
2986 unsigned NumCases = Record[4];
2988 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2989 InstructionList.push_back(SI);
2991 unsigned CurIdx = 5;
2992 for (unsigned i = 0; i != NumCases; ++i) {
2993 SmallVector<ConstantInt*, 1> CaseVals;
2994 unsigned NumItems = Record[CurIdx++];
2995 for (unsigned ci = 0; ci != NumItems; ++ci) {
2996 bool isSingleNumber = Record[CurIdx++];
2999 unsigned ActiveWords = 1;
3000 if (ValueBitWidth > 64)
3001 ActiveWords = Record[CurIdx++];
3002 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3004 CurIdx += ActiveWords;
3006 if (!isSingleNumber) {
3008 if (ValueBitWidth > 64)
3009 ActiveWords = Record[CurIdx++];
3011 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3013 CurIdx += ActiveWords;
3015 // FIXME: It is not clear whether values in the range should be
3016 // compared as signed or unsigned values. The partially
3017 // implemented changes that used this format in the past used
3018 // unsigned comparisons.
3019 for ( ; Low.ule(High); ++Low)
3020 CaseVals.push_back(ConstantInt::get(Context, Low));
3022 CaseVals.push_back(ConstantInt::get(Context, Low));
3024 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3025 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3026 cve = CaseVals.end(); cvi != cve; ++cvi)
3027 SI->addCase(*cvi, DestBB);
3033 // Old SwitchInst format without case ranges.
3035 if (Record.size() < 3 || (Record.size() & 1) == 0)
3036 return Error("Invalid record");
3037 Type *OpTy = getTypeByID(Record[0]);
3038 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3039 BasicBlock *Default = getBasicBlock(Record[2]);
3040 if (!OpTy || !Cond || !Default)
3041 return Error("Invalid record");
3042 unsigned NumCases = (Record.size()-3)/2;
3043 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3044 InstructionList.push_back(SI);
3045 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3046 ConstantInt *CaseVal =
3047 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3048 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3049 if (!CaseVal || !DestBB) {
3051 return Error("Invalid record");
3053 SI->addCase(CaseVal, DestBB);
3058 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3059 if (Record.size() < 2)
3060 return Error("Invalid record");
3061 Type *OpTy = getTypeByID(Record[0]);
3062 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3063 if (!OpTy || !Address)
3064 return Error("Invalid record");
3065 unsigned NumDests = Record.size()-2;
3066 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3067 InstructionList.push_back(IBI);
3068 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3069 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3070 IBI->addDestination(DestBB);
3073 return Error("Invalid record");
3080 case bitc::FUNC_CODE_INST_INVOKE: {
3081 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3082 if (Record.size() < 4)
3083 return Error("Invalid record");
3084 AttributeSet PAL = getAttributes(Record[0]);
3085 unsigned CCInfo = Record[1];
3086 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3087 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3091 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3092 return Error("Invalid record");
3094 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3095 FunctionType *FTy = !CalleeTy ? nullptr :
3096 dyn_cast<FunctionType>(CalleeTy->getElementType());
3098 // Check that the right number of fixed parameters are here.
3099 if (!FTy || !NormalBB || !UnwindBB ||
3100 Record.size() < OpNum+FTy->getNumParams())
3101 return Error("Invalid record");
3103 SmallVector<Value*, 16> Ops;
3104 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3105 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3106 FTy->getParamType(i)));
3108 return Error("Invalid record");
3111 if (!FTy->isVarArg()) {
3112 if (Record.size() != OpNum)
3113 return Error("Invalid record");
3115 // Read type/value pairs for varargs params.
3116 while (OpNum != Record.size()) {
3118 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3119 return Error("Invalid record");
3124 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3125 InstructionList.push_back(I);
3126 cast<InvokeInst>(I)->setCallingConv(
3127 static_cast<CallingConv::ID>(CCInfo));
3128 cast<InvokeInst>(I)->setAttributes(PAL);
3131 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3133 Value *Val = nullptr;
3134 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3135 return Error("Invalid record");
3136 I = ResumeInst::Create(Val);
3137 InstructionList.push_back(I);
3140 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3141 I = new UnreachableInst(Context);
3142 InstructionList.push_back(I);
3144 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3145 if (Record.size() < 1 || ((Record.size()-1)&1))
3146 return Error("Invalid record");
3147 Type *Ty = getTypeByID(Record[0]);
3149 return Error("Invalid record");
3151 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3152 InstructionList.push_back(PN);
3154 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3156 // With the new function encoding, it is possible that operands have
3157 // negative IDs (for forward references). Use a signed VBR
3158 // representation to keep the encoding small.
3160 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3162 V = getValue(Record, 1+i, NextValueNo, Ty);
3163 BasicBlock *BB = getBasicBlock(Record[2+i]);
3165 return Error("Invalid record");
3166 PN->addIncoming(V, BB);
3172 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3173 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3175 if (Record.size() < 4)
3176 return Error("Invalid record");
3177 Type *Ty = getTypeByID(Record[Idx++]);
3179 return Error("Invalid record");
3180 Value *PersFn = nullptr;
3181 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3182 return Error("Invalid record");
3184 bool IsCleanup = !!Record[Idx++];
3185 unsigned NumClauses = Record[Idx++];
3186 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3187 LP->setCleanup(IsCleanup);
3188 for (unsigned J = 0; J != NumClauses; ++J) {
3189 LandingPadInst::ClauseType CT =
3190 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3193 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3195 return Error("Invalid record");
3198 assert((CT != LandingPadInst::Catch ||
3199 !isa<ArrayType>(Val->getType())) &&
3200 "Catch clause has a invalid type!");
3201 assert((CT != LandingPadInst::Filter ||
3202 isa<ArrayType>(Val->getType())) &&
3203 "Filter clause has invalid type!");
3204 LP->addClause(cast<Constant>(Val));
3208 InstructionList.push_back(I);
3212 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3213 if (Record.size() != 4)
3214 return Error("Invalid record");
3216 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3217 Type *OpTy = getTypeByID(Record[1]);
3218 Value *Size = getFnValueByID(Record[2], OpTy);
3219 unsigned AlignRecord = Record[3];
3220 bool InAlloca = AlignRecord & (1 << 5);
3221 unsigned Align = AlignRecord & ((1 << 5) - 1);
3223 return Error("Invalid record");
3224 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3225 AI->setUsedWithInAlloca(InAlloca);
3227 InstructionList.push_back(I);
3230 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3233 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3234 OpNum+2 != Record.size())
3235 return Error("Invalid record");
3237 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3238 InstructionList.push_back(I);
3241 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3242 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3245 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3246 OpNum+4 != Record.size())
3247 return Error("Invalid record");
3249 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3250 if (Ordering == NotAtomic || Ordering == Release ||
3251 Ordering == AcquireRelease)
3252 return Error("Invalid record");
3253 if (Ordering != NotAtomic && Record[OpNum] == 0)
3254 return Error("Invalid record");
3255 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3257 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3258 Ordering, SynchScope);
3259 InstructionList.push_back(I);
3262 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3265 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3266 popValue(Record, OpNum, NextValueNo,
3267 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3268 OpNum+2 != Record.size())
3269 return Error("Invalid record");
3271 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3272 InstructionList.push_back(I);
3275 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3276 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3279 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3280 popValue(Record, OpNum, NextValueNo,
3281 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3282 OpNum+4 != Record.size())
3283 return Error("Invalid record");
3285 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3286 if (Ordering == NotAtomic || Ordering == Acquire ||
3287 Ordering == AcquireRelease)
3288 return Error("Invalid record");
3289 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3290 if (Ordering != NotAtomic && Record[OpNum] == 0)
3291 return Error("Invalid record");
3293 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3294 Ordering, SynchScope);
3295 InstructionList.push_back(I);
3298 case bitc::FUNC_CODE_INST_CMPXCHG: {
3299 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3300 // failureordering?, isweak?]
3302 Value *Ptr, *Cmp, *New;
3303 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3304 popValue(Record, OpNum, NextValueNo,
3305 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3306 popValue(Record, OpNum, NextValueNo,
3307 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3308 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3309 return Error("Invalid record");
3310 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3311 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3312 return Error("Invalid record");
3313 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3315 AtomicOrdering FailureOrdering;
3316 if (Record.size() < 7)
3318 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3320 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3322 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3324 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3326 if (Record.size() < 8) {
3327 // Before weak cmpxchgs existed, the instruction simply returned the
3328 // value loaded from memory, so bitcode files from that era will be
3329 // expecting the first component of a modern cmpxchg.
3330 CurBB->getInstList().push_back(I);
3331 I = ExtractValueInst::Create(I, 0);
3333 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3336 InstructionList.push_back(I);
3339 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3340 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3343 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3344 popValue(Record, OpNum, NextValueNo,
3345 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3346 OpNum+4 != Record.size())
3347 return Error("Invalid record");
3348 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3349 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3350 Operation > AtomicRMWInst::LAST_BINOP)
3351 return Error("Invalid record");
3352 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3353 if (Ordering == NotAtomic || Ordering == Unordered)
3354 return Error("Invalid record");
3355 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3356 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3357 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3358 InstructionList.push_back(I);
3361 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3362 if (2 != Record.size())
3363 return Error("Invalid record");
3364 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3365 if (Ordering == NotAtomic || Ordering == Unordered ||
3366 Ordering == Monotonic)
3367 return Error("Invalid record");
3368 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3369 I = new FenceInst(Context, Ordering, SynchScope);
3370 InstructionList.push_back(I);
3373 case bitc::FUNC_CODE_INST_CALL: {
3374 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3375 if (Record.size() < 3)
3376 return Error("Invalid record");
3378 AttributeSet PAL = getAttributes(Record[0]);
3379 unsigned CCInfo = Record[1];
3383 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3384 return Error("Invalid record");
3386 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3387 FunctionType *FTy = nullptr;
3388 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3389 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3390 return Error("Invalid record");
3392 SmallVector<Value*, 16> Args;
3393 // Read the fixed params.
3394 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3395 if (FTy->getParamType(i)->isLabelTy())
3396 Args.push_back(getBasicBlock(Record[OpNum]));
3398 Args.push_back(getValue(Record, OpNum, NextValueNo,
3399 FTy->getParamType(i)));
3401 return Error("Invalid record");
3404 // Read type/value pairs for varargs params.
3405 if (!FTy->isVarArg()) {
3406 if (OpNum != Record.size())
3407 return Error("Invalid record");
3409 while (OpNum != Record.size()) {
3411 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3412 return Error("Invalid record");
3417 I = CallInst::Create(Callee, Args);
3418 InstructionList.push_back(I);
3419 cast<CallInst>(I)->setCallingConv(
3420 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3421 CallInst::TailCallKind TCK = CallInst::TCK_None;
3423 TCK = CallInst::TCK_Tail;
3424 if (CCInfo & (1 << 14))
3425 TCK = CallInst::TCK_MustTail;
3426 cast<CallInst>(I)->setTailCallKind(TCK);
3427 cast<CallInst>(I)->setAttributes(PAL);
3430 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3431 if (Record.size() < 3)
3432 return Error("Invalid record");
3433 Type *OpTy = getTypeByID(Record[0]);
3434 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3435 Type *ResTy = getTypeByID(Record[2]);
3436 if (!OpTy || !Op || !ResTy)
3437 return Error("Invalid record");
3438 I = new VAArgInst(Op, ResTy);
3439 InstructionList.push_back(I);
3444 // Add instruction to end of current BB. If there is no current BB, reject
3448 return Error("Invalid instruction with no BB");
3450 CurBB->getInstList().push_back(I);
3452 // If this was a terminator instruction, move to the next block.
3453 if (isa<TerminatorInst>(I)) {
3455 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3458 // Non-void values get registered in the value table for future use.
3459 if (I && !I->getType()->isVoidTy())
3460 ValueList.AssignValue(I, NextValueNo++);
3465 // Check the function list for unresolved values.
3466 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3467 if (!A->getParent()) {
3468 // We found at least one unresolved value. Nuke them all to avoid leaks.
3469 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3470 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3471 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3475 return Error("Never resolved value found in function");
3479 // FIXME: Check for unresolved forward-declared metadata references
3480 // and clean up leaks.
3482 // Trim the value list down to the size it was before we parsed this function.
3483 ValueList.shrinkTo(ModuleValueListSize);
3484 MDValueList.shrinkTo(ModuleMDValueListSize);
3485 std::vector<BasicBlock*>().swap(FunctionBBs);
3486 return std::error_code();
3489 /// Find the function body in the bitcode stream
3490 std::error_code BitcodeReader::FindFunctionInStream(
3492 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3493 while (DeferredFunctionInfoIterator->second == 0) {
3494 if (Stream.AtEndOfStream())
3495 return Error("Could not find function in stream");
3496 // ParseModule will parse the next body in the stream and set its
3497 // position in the DeferredFunctionInfo map.
3498 if (std::error_code EC = ParseModule(true))
3501 return std::error_code();
3504 //===----------------------------------------------------------------------===//
3505 // GVMaterializer implementation
3506 //===----------------------------------------------------------------------===//
3508 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3510 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3511 Function *F = dyn_cast<Function>(GV);
3512 // If it's not a function or is already material, ignore the request.
3513 if (!F || !F->isMaterializable())
3514 return std::error_code();
3516 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3517 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3518 // If its position is recorded as 0, its body is somewhere in the stream
3519 // but we haven't seen it yet.
3520 if (DFII->second == 0 && LazyStreamer)
3521 if (std::error_code EC = FindFunctionInStream(F, DFII))
3524 // Move the bit stream to the saved position of the deferred function body.
3525 Stream.JumpToBit(DFII->second);
3527 if (std::error_code EC = ParseFunctionBody(F))
3529 F->setIsMaterializable(false);
3531 // Upgrade any old intrinsic calls in the function.
3532 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3533 E = UpgradedIntrinsics.end(); I != E; ++I) {
3534 if (I->first != I->second) {
3535 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3537 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3538 UpgradeIntrinsicCall(CI, I->second);
3543 // Bring in any functions that this function forward-referenced via
3545 return materializeForwardReferencedFunctions();
3548 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3549 const Function *F = dyn_cast<Function>(GV);
3550 if (!F || F->isDeclaration())
3553 // Dematerializing F would leave dangling references that wouldn't be
3554 // reconnected on re-materialization.
3555 if (BlockAddressesTaken.count(F))
3558 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3561 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3562 Function *F = dyn_cast<Function>(GV);
3563 // If this function isn't dematerializable, this is a noop.
3564 if (!F || !isDematerializable(F))
3567 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3569 // Just forget the function body, we can remat it later.
3570 F->dropAllReferences();
3571 F->setIsMaterializable(true);
3574 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3575 assert(M == TheModule &&
3576 "Can only Materialize the Module this BitcodeReader is attached to.");
3578 // Promise to materialize all forward references.
3579 WillMaterializeAllForwardRefs = true;
3581 // Iterate over the module, deserializing any functions that are still on
3583 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3585 if (std::error_code EC = materialize(F))
3588 // At this point, if there are any function bodies, the current bit is
3589 // pointing to the END_BLOCK record after them. Now make sure the rest
3590 // of the bits in the module have been read.
3594 // Check that all block address forward references got resolved (as we
3596 if (!BasicBlockFwdRefs.empty())
3597 return Error("Never resolved function from blockaddress");
3599 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3600 // delete the old functions to clean up. We can't do this unless the entire
3601 // module is materialized because there could always be another function body
3602 // with calls to the old function.
3603 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3604 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3605 if (I->first != I->second) {
3606 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3608 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3609 UpgradeIntrinsicCall(CI, I->second);
3611 if (!I->first->use_empty())
3612 I->first->replaceAllUsesWith(I->second);
3613 I->first->eraseFromParent();
3616 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3618 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3619 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3621 UpgradeDebugInfo(*M);
3622 return std::error_code();
3625 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3626 return IdentifiedStructTypes;
3629 std::error_code BitcodeReader::InitStream() {
3631 return InitLazyStream();
3632 return InitStreamFromBuffer();
3635 std::error_code BitcodeReader::InitStreamFromBuffer() {
3636 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3637 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3639 if (Buffer->getBufferSize() & 3)
3640 return Error("Invalid bitcode signature");
3642 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3643 // The magic number is 0x0B17C0DE stored in little endian.
3644 if (isBitcodeWrapper(BufPtr, BufEnd))
3645 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3646 return Error("Invalid bitcode wrapper header");
3648 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3649 Stream.init(&*StreamFile);
3651 return std::error_code();
3654 std::error_code BitcodeReader::InitLazyStream() {
3655 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3657 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3658 StreamingMemoryObject &Bytes = *OwnedBytes;
3659 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3660 Stream.init(&*StreamFile);
3662 unsigned char buf[16];
3663 if (Bytes.readBytes(buf, 16, 0) != 16)
3664 return Error("Invalid bitcode signature");
3666 if (!isBitcode(buf, buf + 16))
3667 return Error("Invalid bitcode signature");
3669 if (isBitcodeWrapper(buf, buf + 4)) {
3670 const unsigned char *bitcodeStart = buf;
3671 const unsigned char *bitcodeEnd = buf + 16;
3672 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3673 Bytes.dropLeadingBytes(bitcodeStart - buf);
3674 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3676 return std::error_code();
3680 class BitcodeErrorCategoryType : public std::error_category {
3681 const char *name() const LLVM_NOEXCEPT override {
3682 return "llvm.bitcode";
3684 std::string message(int IE) const override {
3685 BitcodeError E = static_cast<BitcodeError>(IE);
3687 case BitcodeError::InvalidBitcodeSignature:
3688 return "Invalid bitcode signature";
3689 case BitcodeError::CorruptedBitcode:
3690 return "Corrupted bitcode";
3692 llvm_unreachable("Unknown error type!");
3697 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3699 const std::error_category &llvm::BitcodeErrorCategory() {
3700 return *ErrorCategory;
3703 //===----------------------------------------------------------------------===//
3704 // External interface
3705 //===----------------------------------------------------------------------===//
3707 /// \brief Get a lazy one-at-time loading module from bitcode.
3709 /// This isn't always used in a lazy context. In particular, it's also used by
3710 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3711 /// in forward-referenced functions from block address references.
3713 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3714 /// materialize everything -- in particular, if this isn't truly lazy.
3715 static ErrorOr<Module *>
3716 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3717 LLVMContext &Context, bool WillMaterializeAll,
3718 DiagnosticHandlerFunction DiagnosticHandler) {
3719 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3721 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3722 M->setMaterializer(R);
3724 auto cleanupOnError = [&](std::error_code EC) {
3725 R->releaseBuffer(); // Never take ownership on error.
3726 delete M; // Also deletes R.
3730 if (std::error_code EC = R->ParseBitcodeInto(M))
3731 return cleanupOnError(EC);
3733 if (!WillMaterializeAll)
3734 // Resolve forward references from blockaddresses.
3735 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3736 return cleanupOnError(EC);
3738 Buffer.release(); // The BitcodeReader owns it now.
3743 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3744 LLVMContext &Context,
3745 DiagnosticHandlerFunction DiagnosticHandler) {
3746 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3750 ErrorOr<std::unique_ptr<Module>>
3751 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3752 LLVMContext &Context,
3753 DiagnosticHandlerFunction DiagnosticHandler) {
3754 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3755 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
3756 M->setMaterializer(R);
3757 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3759 return std::move(M);
3763 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3764 DiagnosticHandlerFunction DiagnosticHandler) {
3765 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3766 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3767 std::move(Buf), Context, true, DiagnosticHandler);
3770 Module *M = ModuleOrErr.get();
3771 // Read in the entire module, and destroy the BitcodeReader.
3772 if (std::error_code EC = M->materializeAllPermanently()) {
3777 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3778 // written. We must defer until the Module has been fully materialized.
3784 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3785 DiagnosticHandlerFunction DiagnosticHandler) {
3786 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3787 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3789 ErrorOr<std::string> Triple = R->parseTriple();
3790 if (Triple.getError())
3792 return Triple.get();