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/Bitcode/LLVMBitCodes.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/InlineAsm.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/OperandTraits.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/DataStream.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
34 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
37 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
38 DiagnosticSeverity Severity,
40 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
42 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
44 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
45 std::error_code EC, const Twine &Message) {
46 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
47 DiagnosticHandler(DI);
51 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
53 return Error(DiagnosticHandler, EC, EC.message());
56 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
57 return ::Error(DiagnosticHandler, make_error_code(E), Message);
60 std::error_code BitcodeReader::Error(const Twine &Message) {
61 return ::Error(DiagnosticHandler,
62 make_error_code(BitcodeError::CorruptedBitcode), Message);
65 std::error_code BitcodeReader::Error(BitcodeError E) {
66 return ::Error(DiagnosticHandler, make_error_code(E));
69 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
73 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
76 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
77 DiagnosticHandlerFunction DiagnosticHandler)
78 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
79 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
80 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
81 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
82 WillMaterializeAllForwardRefs(false) {}
84 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
85 DiagnosticHandlerFunction DiagnosticHandler)
86 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
87 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
88 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
89 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
90 WillMaterializeAllForwardRefs(false) {}
92 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
93 if (WillMaterializeAllForwardRefs)
94 return std::error_code();
97 WillMaterializeAllForwardRefs = true;
99 while (!BasicBlockFwdRefQueue.empty()) {
100 Function *F = BasicBlockFwdRefQueue.front();
101 BasicBlockFwdRefQueue.pop_front();
102 assert(F && "Expected valid function");
103 if (!BasicBlockFwdRefs.count(F))
104 // Already materialized.
107 // Check for a function that isn't materializable to prevent an infinite
108 // loop. When parsing a blockaddress stored in a global variable, there
109 // isn't a trivial way to check if a function will have a body without a
110 // linear search through FunctionsWithBodies, so just check it here.
111 if (!F->isMaterializable())
112 return Error("Never resolved function from blockaddress");
114 // Try to materialize F.
115 if (std::error_code EC = materialize(F))
118 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
121 WillMaterializeAllForwardRefs = false;
122 return std::error_code();
125 void BitcodeReader::FreeState() {
127 std::vector<Type*>().swap(TypeList);
130 std::vector<Comdat *>().swap(ComdatList);
132 std::vector<AttributeSet>().swap(MAttributes);
133 std::vector<BasicBlock*>().swap(FunctionBBs);
134 std::vector<Function*>().swap(FunctionsWithBodies);
135 DeferredFunctionInfo.clear();
138 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
139 BasicBlockFwdRefQueue.clear();
142 //===----------------------------------------------------------------------===//
143 // Helper functions to implement forward reference resolution, etc.
144 //===----------------------------------------------------------------------===//
146 /// ConvertToString - Convert a string from a record into an std::string, return
148 template<typename StrTy>
149 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
151 if (Idx > Record.size())
154 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
155 Result += (char)Record[i];
159 static bool hasImplicitComdat(size_t Val) {
163 case 1: // Old WeakAnyLinkage
164 case 4: // Old LinkOnceAnyLinkage
165 case 10: // Old WeakODRLinkage
166 case 11: // Old LinkOnceODRLinkage
171 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
173 default: // Map unknown/new linkages to external
175 return GlobalValue::ExternalLinkage;
177 return GlobalValue::AppendingLinkage;
179 return GlobalValue::InternalLinkage;
181 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
183 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
185 return GlobalValue::ExternalWeakLinkage;
187 return GlobalValue::CommonLinkage;
189 return GlobalValue::PrivateLinkage;
191 return GlobalValue::AvailableExternallyLinkage;
193 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
195 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
197 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
198 case 1: // Old value with implicit comdat.
200 return GlobalValue::WeakAnyLinkage;
201 case 10: // Old value with implicit comdat.
203 return GlobalValue::WeakODRLinkage;
204 case 4: // Old value with implicit comdat.
206 return GlobalValue::LinkOnceAnyLinkage;
207 case 11: // Old value with implicit comdat.
209 return GlobalValue::LinkOnceODRLinkage;
213 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
215 default: // Map unknown visibilities to default.
216 case 0: return GlobalValue::DefaultVisibility;
217 case 1: return GlobalValue::HiddenVisibility;
218 case 2: return GlobalValue::ProtectedVisibility;
222 static GlobalValue::DLLStorageClassTypes
223 GetDecodedDLLStorageClass(unsigned Val) {
225 default: // Map unknown values to default.
226 case 0: return GlobalValue::DefaultStorageClass;
227 case 1: return GlobalValue::DLLImportStorageClass;
228 case 2: return GlobalValue::DLLExportStorageClass;
232 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
234 case 0: return GlobalVariable::NotThreadLocal;
235 default: // Map unknown non-zero value to general dynamic.
236 case 1: return GlobalVariable::GeneralDynamicTLSModel;
237 case 2: return GlobalVariable::LocalDynamicTLSModel;
238 case 3: return GlobalVariable::InitialExecTLSModel;
239 case 4: return GlobalVariable::LocalExecTLSModel;
243 static int GetDecodedCastOpcode(unsigned Val) {
246 case bitc::CAST_TRUNC : return Instruction::Trunc;
247 case bitc::CAST_ZEXT : return Instruction::ZExt;
248 case bitc::CAST_SEXT : return Instruction::SExt;
249 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
250 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
251 case bitc::CAST_UITOFP : return Instruction::UIToFP;
252 case bitc::CAST_SITOFP : return Instruction::SIToFP;
253 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
254 case bitc::CAST_FPEXT : return Instruction::FPExt;
255 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
256 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
257 case bitc::CAST_BITCAST : return Instruction::BitCast;
258 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
261 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
264 case bitc::BINOP_ADD:
265 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
266 case bitc::BINOP_SUB:
267 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
268 case bitc::BINOP_MUL:
269 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
270 case bitc::BINOP_UDIV: return Instruction::UDiv;
271 case bitc::BINOP_SDIV:
272 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
273 case bitc::BINOP_UREM: return Instruction::URem;
274 case bitc::BINOP_SREM:
275 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
276 case bitc::BINOP_SHL: return Instruction::Shl;
277 case bitc::BINOP_LSHR: return Instruction::LShr;
278 case bitc::BINOP_ASHR: return Instruction::AShr;
279 case bitc::BINOP_AND: return Instruction::And;
280 case bitc::BINOP_OR: return Instruction::Or;
281 case bitc::BINOP_XOR: return Instruction::Xor;
285 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
287 default: return AtomicRMWInst::BAD_BINOP;
288 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
289 case bitc::RMW_ADD: return AtomicRMWInst::Add;
290 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
291 case bitc::RMW_AND: return AtomicRMWInst::And;
292 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
293 case bitc::RMW_OR: return AtomicRMWInst::Or;
294 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
295 case bitc::RMW_MAX: return AtomicRMWInst::Max;
296 case bitc::RMW_MIN: return AtomicRMWInst::Min;
297 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
298 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
302 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
304 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
305 case bitc::ORDERING_UNORDERED: return Unordered;
306 case bitc::ORDERING_MONOTONIC: return Monotonic;
307 case bitc::ORDERING_ACQUIRE: return Acquire;
308 case bitc::ORDERING_RELEASE: return Release;
309 case bitc::ORDERING_ACQREL: return AcquireRelease;
310 default: // Map unknown orderings to sequentially-consistent.
311 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
315 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
317 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
318 default: // Map unknown scopes to cross-thread.
319 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
323 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
325 default: // Map unknown selection kinds to any.
326 case bitc::COMDAT_SELECTION_KIND_ANY:
328 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
329 return Comdat::ExactMatch;
330 case bitc::COMDAT_SELECTION_KIND_LARGEST:
331 return Comdat::Largest;
332 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
333 return Comdat::NoDuplicates;
334 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
335 return Comdat::SameSize;
339 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
341 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
342 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
348 /// @brief A class for maintaining the slot number definition
349 /// as a placeholder for the actual definition for forward constants defs.
350 class ConstantPlaceHolder : public ConstantExpr {
351 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
353 // allocate space for exactly one operand
354 void *operator new(size_t s) {
355 return User::operator new(s, 1);
357 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
358 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
359 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
362 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
363 static bool classof(const Value *V) {
364 return isa<ConstantExpr>(V) &&
365 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
369 /// Provide fast operand accessors
370 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
374 // FIXME: can we inherit this from ConstantExpr?
376 struct OperandTraits<ConstantPlaceHolder> :
377 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
379 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
383 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
392 WeakVH &OldV = ValuePtrs[Idx];
398 // Handle constants and non-constants (e.g. instrs) differently for
400 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
401 ResolveConstants.push_back(std::make_pair(PHC, Idx));
404 // If there was a forward reference to this value, replace it.
405 Value *PrevVal = OldV;
406 OldV->replaceAllUsesWith(V);
412 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
417 if (Value *V = ValuePtrs[Idx]) {
418 assert(Ty == V->getType() && "Type mismatch in constant table!");
419 return cast<Constant>(V);
422 // Create and return a placeholder, which will later be RAUW'd.
423 Constant *C = new ConstantPlaceHolder(Ty, Context);
428 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
432 if (Value *V = ValuePtrs[Idx]) {
433 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
437 // No type specified, must be invalid reference.
438 if (!Ty) return nullptr;
440 // Create and return a placeholder, which will later be RAUW'd.
441 Value *V = new Argument(Ty);
446 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
447 /// resolves any forward references. The idea behind this is that we sometimes
448 /// get constants (such as large arrays) which reference *many* forward ref
449 /// constants. Replacing each of these causes a lot of thrashing when
450 /// building/reuniquing the constant. Instead of doing this, we look at all the
451 /// uses and rewrite all the place holders at once for any constant that uses
453 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
454 // Sort the values by-pointer so that they are efficient to look up with a
456 std::sort(ResolveConstants.begin(), ResolveConstants.end());
458 SmallVector<Constant*, 64> NewOps;
460 while (!ResolveConstants.empty()) {
461 Value *RealVal = operator[](ResolveConstants.back().second);
462 Constant *Placeholder = ResolveConstants.back().first;
463 ResolveConstants.pop_back();
465 // Loop over all users of the placeholder, updating them to reference the
466 // new value. If they reference more than one placeholder, update them all
468 while (!Placeholder->use_empty()) {
469 auto UI = Placeholder->user_begin();
472 // If the using object isn't uniqued, just update the operands. This
473 // handles instructions and initializers for global variables.
474 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
475 UI.getUse().set(RealVal);
479 // Otherwise, we have a constant that uses the placeholder. Replace that
480 // constant with a new constant that has *all* placeholder uses updated.
481 Constant *UserC = cast<Constant>(U);
482 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
485 if (!isa<ConstantPlaceHolder>(*I)) {
486 // Not a placeholder reference.
488 } else if (*I == Placeholder) {
489 // Common case is that it just references this one placeholder.
492 // Otherwise, look up the placeholder in ResolveConstants.
493 ResolveConstantsTy::iterator It =
494 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
495 std::pair<Constant*, unsigned>(cast<Constant>(*I),
497 assert(It != ResolveConstants.end() && It->first == *I);
498 NewOp = operator[](It->second);
501 NewOps.push_back(cast<Constant>(NewOp));
504 // Make the new constant.
506 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
507 NewC = ConstantArray::get(UserCA->getType(), NewOps);
508 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
509 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
510 } else if (isa<ConstantVector>(UserC)) {
511 NewC = ConstantVector::get(NewOps);
513 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
514 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
517 UserC->replaceAllUsesWith(NewC);
518 UserC->destroyConstant();
522 // Update all ValueHandles, they should be the only users at this point.
523 Placeholder->replaceAllUsesWith(RealVal);
528 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
537 TrackingMDRef &OldMD = MDValuePtrs[Idx];
543 // If there was a forward reference to this value, replace it.
544 MDTuple *PrevMD = cast<MDTuple>(OldMD.get());
545 PrevMD->replaceAllUsesWith(MD);
546 MDNode::deleteTemporary(PrevMD);
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);
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<UniquableMDNode>(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 // Read all the records for this value table.
1111 SmallString<128> ValueName;
1113 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1115 switch (Entry.Kind) {
1116 case BitstreamEntry::SubBlock: // Handled for us already.
1117 case BitstreamEntry::Error:
1118 return Error("Malformed block");
1119 case BitstreamEntry::EndBlock:
1120 return std::error_code();
1121 case BitstreamEntry::Record:
1122 // The interesting case.
1128 switch (Stream.readRecord(Entry.ID, Record)) {
1129 default: // Default behavior: unknown type.
1131 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1132 if (ConvertToString(Record, 1, ValueName))
1133 return Error("Invalid record");
1134 unsigned ValueID = Record[0];
1135 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1136 return Error("Invalid record");
1137 Value *V = ValueList[ValueID];
1139 V->setName(StringRef(ValueName.data(), ValueName.size()));
1140 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1141 if (GO->getComdat() == reinterpret_cast<Comdat *>(1))
1142 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1147 case bitc::VST_CODE_BBENTRY: {
1148 if (ConvertToString(Record, 1, ValueName))
1149 return Error("Invalid record");
1150 BasicBlock *BB = getBasicBlock(Record[0]);
1152 return Error("Invalid record");
1154 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1162 std::error_code BitcodeReader::ParseMetadata() {
1163 unsigned NextMDValueNo = MDValueList.size();
1165 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1166 return Error("Invalid record");
1168 SmallVector<uint64_t, 64> Record;
1170 // Read all the records.
1172 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1174 switch (Entry.Kind) {
1175 case BitstreamEntry::SubBlock: // Handled for us already.
1176 case BitstreamEntry::Error:
1177 return Error("Malformed block");
1178 case BitstreamEntry::EndBlock:
1179 MDValueList.tryToResolveCycles();
1180 return std::error_code();
1181 case BitstreamEntry::Record:
1182 // The interesting case.
1188 unsigned Code = Stream.readRecord(Entry.ID, Record);
1189 bool IsDistinct = false;
1191 default: // Default behavior: ignore.
1193 case bitc::METADATA_NAME: {
1194 // Read name of the named metadata.
1195 SmallString<8> Name(Record.begin(), Record.end());
1197 Code = Stream.ReadCode();
1199 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1200 unsigned NextBitCode = Stream.readRecord(Code, Record);
1201 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1203 // Read named metadata elements.
1204 unsigned Size = Record.size();
1205 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1206 for (unsigned i = 0; i != Size; ++i) {
1207 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1209 return Error("Invalid record");
1210 NMD->addOperand(MD);
1214 case bitc::METADATA_OLD_FN_NODE: {
1215 // FIXME: Remove in 4.0.
1216 // This is a LocalAsMetadata record, the only type of function-local
1218 if (Record.size() % 2 == 1)
1219 return Error("Invalid record");
1221 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1222 // to be legal, but there's no upgrade path.
1223 auto dropRecord = [&] {
1224 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1226 if (Record.size() != 2) {
1231 Type *Ty = getTypeByID(Record[0]);
1232 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1237 MDValueList.AssignValue(
1238 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1242 case bitc::METADATA_OLD_NODE: {
1243 // FIXME: Remove in 4.0.
1244 if (Record.size() % 2 == 1)
1245 return Error("Invalid record");
1247 unsigned Size = Record.size();
1248 SmallVector<Metadata *, 8> Elts;
1249 for (unsigned i = 0; i != Size; i += 2) {
1250 Type *Ty = getTypeByID(Record[i]);
1252 return Error("Invalid record");
1253 if (Ty->isMetadataTy())
1254 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1255 else if (!Ty->isVoidTy()) {
1257 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1258 assert(isa<ConstantAsMetadata>(MD) &&
1259 "Expected non-function-local metadata");
1262 Elts.push_back(nullptr);
1264 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1267 case bitc::METADATA_VALUE: {
1268 if (Record.size() != 2)
1269 return Error("Invalid record");
1271 Type *Ty = getTypeByID(Record[0]);
1272 if (Ty->isMetadataTy() || Ty->isVoidTy())
1273 return Error("Invalid record");
1275 MDValueList.AssignValue(
1276 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1280 case bitc::METADATA_DISTINCT_NODE:
1283 case bitc::METADATA_NODE: {
1284 SmallVector<Metadata *, 8> Elts;
1285 Elts.reserve(Record.size());
1286 for (unsigned ID : Record)
1287 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1288 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1289 : MDNode::get(Context, Elts),
1293 case bitc::METADATA_LOCATION: {
1294 if (Record.size() != 5)
1295 return Error("Invalid record");
1297 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1298 unsigned Line = Record[1];
1299 unsigned Column = Record[2];
1300 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1301 Metadata *InlinedAt =
1302 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1303 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1307 case bitc::METADATA_STRING: {
1308 std::string String(Record.begin(), Record.end());
1309 llvm::UpgradeMDStringConstant(String);
1310 Metadata *MD = MDString::get(Context, String);
1311 MDValueList.AssignValue(MD, NextMDValueNo++);
1314 case bitc::METADATA_KIND: {
1315 if (Record.size() < 2)
1316 return Error("Invalid record");
1318 unsigned Kind = Record[0];
1319 SmallString<8> Name(Record.begin()+1, Record.end());
1321 unsigned NewKind = TheModule->getMDKindID(Name.str());
1322 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1323 return Error("Conflicting METADATA_KIND records");
1330 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1331 /// the LSB for dense VBR encoding.
1332 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1337 // There is no such thing as -0 with integers. "-0" really means MININT.
1341 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1342 /// values and aliases that we can.
1343 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1344 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1345 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1346 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1347 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1349 GlobalInitWorklist.swap(GlobalInits);
1350 AliasInitWorklist.swap(AliasInits);
1351 FunctionPrefixWorklist.swap(FunctionPrefixes);
1352 FunctionPrologueWorklist.swap(FunctionPrologues);
1354 while (!GlobalInitWorklist.empty()) {
1355 unsigned ValID = GlobalInitWorklist.back().second;
1356 if (ValID >= ValueList.size()) {
1357 // Not ready to resolve this yet, it requires something later in the file.
1358 GlobalInits.push_back(GlobalInitWorklist.back());
1360 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1361 GlobalInitWorklist.back().first->setInitializer(C);
1363 return Error("Expected a constant");
1365 GlobalInitWorklist.pop_back();
1368 while (!AliasInitWorklist.empty()) {
1369 unsigned ValID = AliasInitWorklist.back().second;
1370 if (ValID >= ValueList.size()) {
1371 AliasInits.push_back(AliasInitWorklist.back());
1373 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1374 AliasInitWorklist.back().first->setAliasee(C);
1376 return Error("Expected a constant");
1378 AliasInitWorklist.pop_back();
1381 while (!FunctionPrefixWorklist.empty()) {
1382 unsigned ValID = FunctionPrefixWorklist.back().second;
1383 if (ValID >= ValueList.size()) {
1384 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1386 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1387 FunctionPrefixWorklist.back().first->setPrefixData(C);
1389 return Error("Expected a constant");
1391 FunctionPrefixWorklist.pop_back();
1394 while (!FunctionPrologueWorklist.empty()) {
1395 unsigned ValID = FunctionPrologueWorklist.back().second;
1396 if (ValID >= ValueList.size()) {
1397 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1399 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1400 FunctionPrologueWorklist.back().first->setPrologueData(C);
1402 return Error("Expected a constant");
1404 FunctionPrologueWorklist.pop_back();
1407 return std::error_code();
1410 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1411 SmallVector<uint64_t, 8> Words(Vals.size());
1412 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1413 BitcodeReader::decodeSignRotatedValue);
1415 return APInt(TypeBits, Words);
1418 std::error_code BitcodeReader::ParseConstants() {
1419 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1420 return Error("Invalid record");
1422 SmallVector<uint64_t, 64> Record;
1424 // Read all the records for this value table.
1425 Type *CurTy = Type::getInt32Ty(Context);
1426 unsigned NextCstNo = ValueList.size();
1428 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1430 switch (Entry.Kind) {
1431 case BitstreamEntry::SubBlock: // Handled for us already.
1432 case BitstreamEntry::Error:
1433 return Error("Malformed block");
1434 case BitstreamEntry::EndBlock:
1435 if (NextCstNo != ValueList.size())
1436 return Error("Invalid ronstant reference");
1438 // Once all the constants have been read, go through and resolve forward
1440 ValueList.ResolveConstantForwardRefs();
1441 return std::error_code();
1442 case BitstreamEntry::Record:
1443 // The interesting case.
1450 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1452 default: // Default behavior: unknown constant
1453 case bitc::CST_CODE_UNDEF: // UNDEF
1454 V = UndefValue::get(CurTy);
1456 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1458 return Error("Invalid record");
1459 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1460 return Error("Invalid record");
1461 CurTy = TypeList[Record[0]];
1462 continue; // Skip the ValueList manipulation.
1463 case bitc::CST_CODE_NULL: // NULL
1464 V = Constant::getNullValue(CurTy);
1466 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1467 if (!CurTy->isIntegerTy() || Record.empty())
1468 return Error("Invalid record");
1469 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1471 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1472 if (!CurTy->isIntegerTy() || Record.empty())
1473 return Error("Invalid record");
1475 APInt VInt = ReadWideAPInt(Record,
1476 cast<IntegerType>(CurTy)->getBitWidth());
1477 V = ConstantInt::get(Context, VInt);
1481 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1483 return Error("Invalid record");
1484 if (CurTy->isHalfTy())
1485 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1486 APInt(16, (uint16_t)Record[0])));
1487 else if (CurTy->isFloatTy())
1488 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1489 APInt(32, (uint32_t)Record[0])));
1490 else if (CurTy->isDoubleTy())
1491 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1492 APInt(64, Record[0])));
1493 else if (CurTy->isX86_FP80Ty()) {
1494 // Bits are not stored the same way as a normal i80 APInt, compensate.
1495 uint64_t Rearrange[2];
1496 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1497 Rearrange[1] = Record[0] >> 48;
1498 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1499 APInt(80, Rearrange)));
1500 } else if (CurTy->isFP128Ty())
1501 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1502 APInt(128, Record)));
1503 else if (CurTy->isPPC_FP128Ty())
1504 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1505 APInt(128, Record)));
1507 V = UndefValue::get(CurTy);
1511 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1513 return Error("Invalid record");
1515 unsigned Size = Record.size();
1516 SmallVector<Constant*, 16> Elts;
1518 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1519 for (unsigned i = 0; i != Size; ++i)
1520 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1521 STy->getElementType(i)));
1522 V = ConstantStruct::get(STy, Elts);
1523 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1524 Type *EltTy = ATy->getElementType();
1525 for (unsigned i = 0; i != Size; ++i)
1526 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1527 V = ConstantArray::get(ATy, Elts);
1528 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1529 Type *EltTy = VTy->getElementType();
1530 for (unsigned i = 0; i != Size; ++i)
1531 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1532 V = ConstantVector::get(Elts);
1534 V = UndefValue::get(CurTy);
1538 case bitc::CST_CODE_STRING: // STRING: [values]
1539 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1541 return Error("Invalid record");
1543 SmallString<16> Elts(Record.begin(), Record.end());
1544 V = ConstantDataArray::getString(Context, Elts,
1545 BitCode == bitc::CST_CODE_CSTRING);
1548 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1550 return Error("Invalid record");
1552 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1553 unsigned Size = Record.size();
1555 if (EltTy->isIntegerTy(8)) {
1556 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1557 if (isa<VectorType>(CurTy))
1558 V = ConstantDataVector::get(Context, Elts);
1560 V = ConstantDataArray::get(Context, Elts);
1561 } else if (EltTy->isIntegerTy(16)) {
1562 SmallVector<uint16_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(32)) {
1568 SmallVector<uint32_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(64)) {
1574 SmallVector<uint64_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->isFloatTy()) {
1580 SmallVector<float, 16> Elts(Size);
1581 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1582 if (isa<VectorType>(CurTy))
1583 V = ConstantDataVector::get(Context, Elts);
1585 V = ConstantDataArray::get(Context, Elts);
1586 } else if (EltTy->isDoubleTy()) {
1587 SmallVector<double, 16> Elts(Size);
1588 std::transform(Record.begin(), Record.end(), Elts.begin(),
1590 if (isa<VectorType>(CurTy))
1591 V = ConstantDataVector::get(Context, Elts);
1593 V = ConstantDataArray::get(Context, Elts);
1595 return Error("Invalid type for value");
1600 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1601 if (Record.size() < 3)
1602 return Error("Invalid record");
1603 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1605 V = UndefValue::get(CurTy); // Unknown binop.
1607 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1608 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1610 if (Record.size() >= 4) {
1611 if (Opc == Instruction::Add ||
1612 Opc == Instruction::Sub ||
1613 Opc == Instruction::Mul ||
1614 Opc == Instruction::Shl) {
1615 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1616 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1617 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1618 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1619 } else if (Opc == Instruction::SDiv ||
1620 Opc == Instruction::UDiv ||
1621 Opc == Instruction::LShr ||
1622 Opc == Instruction::AShr) {
1623 if (Record[3] & (1 << bitc::PEO_EXACT))
1624 Flags |= SDivOperator::IsExact;
1627 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1631 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1632 if (Record.size() < 3)
1633 return Error("Invalid record");
1634 int Opc = GetDecodedCastOpcode(Record[0]);
1636 V = UndefValue::get(CurTy); // Unknown cast.
1638 Type *OpTy = getTypeByID(Record[1]);
1640 return Error("Invalid record");
1641 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1642 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1643 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1647 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1648 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1649 if (Record.size() & 1)
1650 return Error("Invalid record");
1651 SmallVector<Constant*, 16> Elts;
1652 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1653 Type *ElTy = getTypeByID(Record[i]);
1655 return Error("Invalid record");
1656 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1658 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1659 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1661 bitc::CST_CODE_CE_INBOUNDS_GEP);
1664 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1665 if (Record.size() < 3)
1666 return Error("Invalid record");
1668 Type *SelectorTy = Type::getInt1Ty(Context);
1670 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1671 // vector. Otherwise, it must be a single bit.
1672 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1673 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1674 VTy->getNumElements());
1676 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1678 ValueList.getConstantFwdRef(Record[1],CurTy),
1679 ValueList.getConstantFwdRef(Record[2],CurTy));
1682 case bitc::CST_CODE_CE_EXTRACTELT
1683 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1684 if (Record.size() < 3)
1685 return Error("Invalid record");
1687 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1689 return Error("Invalid record");
1690 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1691 Constant *Op1 = nullptr;
1692 if (Record.size() == 4) {
1693 Type *IdxTy = getTypeByID(Record[2]);
1695 return Error("Invalid record");
1696 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1697 } else // TODO: Remove with llvm 4.0
1698 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1700 return Error("Invalid record");
1701 V = ConstantExpr::getExtractElement(Op0, Op1);
1704 case bitc::CST_CODE_CE_INSERTELT
1705 : { // CE_INSERTELT: [opval, opval, opty, opval]
1706 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1707 if (Record.size() < 3 || !OpTy)
1708 return Error("Invalid record");
1709 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1710 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1711 OpTy->getElementType());
1712 Constant *Op2 = nullptr;
1713 if (Record.size() == 4) {
1714 Type *IdxTy = getTypeByID(Record[2]);
1716 return Error("Invalid record");
1717 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1718 } else // TODO: Remove with llvm 4.0
1719 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1721 return Error("Invalid record");
1722 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1725 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1726 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1727 if (Record.size() < 3 || !OpTy)
1728 return Error("Invalid record");
1729 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1730 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1731 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1732 OpTy->getNumElements());
1733 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1734 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1737 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1738 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1740 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1741 if (Record.size() < 4 || !RTy || !OpTy)
1742 return Error("Invalid record");
1743 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1744 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1745 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1746 RTy->getNumElements());
1747 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1748 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1751 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1752 if (Record.size() < 4)
1753 return Error("Invalid record");
1754 Type *OpTy = getTypeByID(Record[0]);
1756 return Error("Invalid record");
1757 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1758 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1760 if (OpTy->isFPOrFPVectorTy())
1761 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1763 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1766 // This maintains backward compatibility, pre-asm dialect keywords.
1767 // FIXME: Remove with the 4.0 release.
1768 case bitc::CST_CODE_INLINEASM_OLD: {
1769 if (Record.size() < 2)
1770 return Error("Invalid record");
1771 std::string AsmStr, ConstrStr;
1772 bool HasSideEffects = Record[0] & 1;
1773 bool IsAlignStack = Record[0] >> 1;
1774 unsigned AsmStrSize = Record[1];
1775 if (2+AsmStrSize >= Record.size())
1776 return Error("Invalid record");
1777 unsigned ConstStrSize = Record[2+AsmStrSize];
1778 if (3+AsmStrSize+ConstStrSize > Record.size())
1779 return Error("Invalid record");
1781 for (unsigned i = 0; i != AsmStrSize; ++i)
1782 AsmStr += (char)Record[2+i];
1783 for (unsigned i = 0; i != ConstStrSize; ++i)
1784 ConstrStr += (char)Record[3+AsmStrSize+i];
1785 PointerType *PTy = cast<PointerType>(CurTy);
1786 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1787 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1790 // This version adds support for the asm dialect keywords (e.g.,
1792 case bitc::CST_CODE_INLINEASM: {
1793 if (Record.size() < 2)
1794 return Error("Invalid record");
1795 std::string AsmStr, ConstrStr;
1796 bool HasSideEffects = Record[0] & 1;
1797 bool IsAlignStack = (Record[0] >> 1) & 1;
1798 unsigned AsmDialect = Record[0] >> 2;
1799 unsigned AsmStrSize = Record[1];
1800 if (2+AsmStrSize >= Record.size())
1801 return Error("Invalid record");
1802 unsigned ConstStrSize = Record[2+AsmStrSize];
1803 if (3+AsmStrSize+ConstStrSize > Record.size())
1804 return Error("Invalid record");
1806 for (unsigned i = 0; i != AsmStrSize; ++i)
1807 AsmStr += (char)Record[2+i];
1808 for (unsigned i = 0; i != ConstStrSize; ++i)
1809 ConstrStr += (char)Record[3+AsmStrSize+i];
1810 PointerType *PTy = cast<PointerType>(CurTy);
1811 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1812 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1813 InlineAsm::AsmDialect(AsmDialect));
1816 case bitc::CST_CODE_BLOCKADDRESS:{
1817 if (Record.size() < 3)
1818 return Error("Invalid record");
1819 Type *FnTy = getTypeByID(Record[0]);
1821 return Error("Invalid record");
1823 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1825 return Error("Invalid record");
1827 // Don't let Fn get dematerialized.
1828 BlockAddressesTaken.insert(Fn);
1830 // If the function is already parsed we can insert the block address right
1833 unsigned BBID = Record[2];
1835 // Invalid reference to entry block.
1836 return Error("Invalid ID");
1838 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1839 for (size_t I = 0, E = BBID; I != E; ++I) {
1841 return Error("Invalid ID");
1846 // Otherwise insert a placeholder and remember it so it can be inserted
1847 // when the function is parsed.
1848 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1850 BasicBlockFwdRefQueue.push_back(Fn);
1851 if (FwdBBs.size() < BBID + 1)
1852 FwdBBs.resize(BBID + 1);
1854 FwdBBs[BBID] = BasicBlock::Create(Context);
1857 V = BlockAddress::get(Fn, BB);
1862 ValueList.AssignValue(V, NextCstNo);
1867 std::error_code BitcodeReader::ParseUseLists() {
1868 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1869 return Error("Invalid record");
1871 // Read all the records.
1872 SmallVector<uint64_t, 64> Record;
1874 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1876 switch (Entry.Kind) {
1877 case BitstreamEntry::SubBlock: // Handled for us already.
1878 case BitstreamEntry::Error:
1879 return Error("Malformed block");
1880 case BitstreamEntry::EndBlock:
1881 return std::error_code();
1882 case BitstreamEntry::Record:
1883 // The interesting case.
1887 // Read a use list record.
1890 switch (Stream.readRecord(Entry.ID, Record)) {
1891 default: // Default behavior: unknown type.
1893 case bitc::USELIST_CODE_BB:
1896 case bitc::USELIST_CODE_DEFAULT: {
1897 unsigned RecordLength = Record.size();
1898 if (RecordLength < 3)
1899 // Records should have at least an ID and two indexes.
1900 return Error("Invalid record");
1901 unsigned ID = Record.back();
1906 assert(ID < FunctionBBs.size() && "Basic block not found");
1907 V = FunctionBBs[ID];
1910 unsigned NumUses = 0;
1911 SmallDenseMap<const Use *, unsigned, 16> Order;
1912 for (const Use &U : V->uses()) {
1913 if (++NumUses > Record.size())
1915 Order[&U] = Record[NumUses - 1];
1917 if (Order.size() != Record.size() || NumUses > Record.size())
1918 // Mismatches can happen if the functions are being materialized lazily
1919 // (out-of-order), or a value has been upgraded.
1922 V->sortUseList([&](const Use &L, const Use &R) {
1923 return Order.lookup(&L) < Order.lookup(&R);
1931 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1932 /// remember where it is and then skip it. This lets us lazily deserialize the
1934 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1935 // Get the function we are talking about.
1936 if (FunctionsWithBodies.empty())
1937 return Error("Insufficient function protos");
1939 Function *Fn = FunctionsWithBodies.back();
1940 FunctionsWithBodies.pop_back();
1942 // Save the current stream state.
1943 uint64_t CurBit = Stream.GetCurrentBitNo();
1944 DeferredFunctionInfo[Fn] = CurBit;
1946 // Skip over the function block for now.
1947 if (Stream.SkipBlock())
1948 return Error("Invalid record");
1949 return std::error_code();
1952 std::error_code BitcodeReader::GlobalCleanup() {
1953 // Patch the initializers for globals and aliases up.
1954 ResolveGlobalAndAliasInits();
1955 if (!GlobalInits.empty() || !AliasInits.empty())
1956 return Error("Malformed global initializer set");
1958 // Look for intrinsic functions which need to be upgraded at some point
1959 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1962 if (UpgradeIntrinsicFunction(FI, NewFn))
1963 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1966 // Look for global variables which need to be renamed.
1967 for (Module::global_iterator
1968 GI = TheModule->global_begin(), GE = TheModule->global_end();
1970 GlobalVariable *GV = GI++;
1971 UpgradeGlobalVariable(GV);
1974 // Force deallocation of memory for these vectors to favor the client that
1975 // want lazy deserialization.
1976 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1977 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1978 return std::error_code();
1981 std::error_code BitcodeReader::ParseModule(bool Resume) {
1983 Stream.JumpToBit(NextUnreadBit);
1984 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1985 return Error("Invalid record");
1987 SmallVector<uint64_t, 64> Record;
1988 std::vector<std::string> SectionTable;
1989 std::vector<std::string> GCTable;
1991 // Read all the records for this module.
1993 BitstreamEntry Entry = Stream.advance();
1995 switch (Entry.Kind) {
1996 case BitstreamEntry::Error:
1997 return Error("Malformed block");
1998 case BitstreamEntry::EndBlock:
1999 return GlobalCleanup();
2001 case BitstreamEntry::SubBlock:
2003 default: // Skip unknown content.
2004 if (Stream.SkipBlock())
2005 return Error("Invalid record");
2007 case bitc::BLOCKINFO_BLOCK_ID:
2008 if (Stream.ReadBlockInfoBlock())
2009 return Error("Malformed block");
2011 case bitc::PARAMATTR_BLOCK_ID:
2012 if (std::error_code EC = ParseAttributeBlock())
2015 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2016 if (std::error_code EC = ParseAttributeGroupBlock())
2019 case bitc::TYPE_BLOCK_ID_NEW:
2020 if (std::error_code EC = ParseTypeTable())
2023 case bitc::VALUE_SYMTAB_BLOCK_ID:
2024 if (std::error_code EC = ParseValueSymbolTable())
2026 SeenValueSymbolTable = true;
2028 case bitc::CONSTANTS_BLOCK_ID:
2029 if (std::error_code EC = ParseConstants())
2031 if (std::error_code EC = ResolveGlobalAndAliasInits())
2034 case bitc::METADATA_BLOCK_ID:
2035 if (std::error_code EC = ParseMetadata())
2038 case bitc::FUNCTION_BLOCK_ID:
2039 // If this is the first function body we've seen, reverse the
2040 // FunctionsWithBodies list.
2041 if (!SeenFirstFunctionBody) {
2042 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2043 if (std::error_code EC = GlobalCleanup())
2045 SeenFirstFunctionBody = true;
2048 if (std::error_code EC = RememberAndSkipFunctionBody())
2050 // For streaming bitcode, suspend parsing when we reach the function
2051 // bodies. Subsequent materialization calls will resume it when
2052 // necessary. For streaming, the function bodies must be at the end of
2053 // the bitcode. If the bitcode file is old, the symbol table will be
2054 // at the end instead and will not have been seen yet. In this case,
2055 // just finish the parse now.
2056 if (LazyStreamer && SeenValueSymbolTable) {
2057 NextUnreadBit = Stream.GetCurrentBitNo();
2058 return std::error_code();
2061 case bitc::USELIST_BLOCK_ID:
2062 if (std::error_code EC = ParseUseLists())
2068 case BitstreamEntry::Record:
2069 // The interesting case.
2075 switch (Stream.readRecord(Entry.ID, Record)) {
2076 default: break; // Default behavior, ignore unknown content.
2077 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2078 if (Record.size() < 1)
2079 return Error("Invalid record");
2080 // Only version #0 and #1 are supported so far.
2081 unsigned module_version = Record[0];
2082 switch (module_version) {
2084 return Error("Invalid value");
2086 UseRelativeIDs = false;
2089 UseRelativeIDs = true;
2094 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2096 if (ConvertToString(Record, 0, S))
2097 return Error("Invalid record");
2098 TheModule->setTargetTriple(S);
2101 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2103 if (ConvertToString(Record, 0, S))
2104 return Error("Invalid record");
2105 TheModule->setDataLayout(S);
2108 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2110 if (ConvertToString(Record, 0, S))
2111 return Error("Invalid record");
2112 TheModule->setModuleInlineAsm(S);
2115 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2116 // FIXME: Remove in 4.0.
2118 if (ConvertToString(Record, 0, S))
2119 return Error("Invalid record");
2123 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2125 if (ConvertToString(Record, 0, S))
2126 return Error("Invalid record");
2127 SectionTable.push_back(S);
2130 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2132 if (ConvertToString(Record, 0, S))
2133 return Error("Invalid record");
2134 GCTable.push_back(S);
2137 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2138 if (Record.size() < 2)
2139 return Error("Invalid record");
2140 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2141 unsigned ComdatNameSize = Record[1];
2142 std::string ComdatName;
2143 ComdatName.reserve(ComdatNameSize);
2144 for (unsigned i = 0; i != ComdatNameSize; ++i)
2145 ComdatName += (char)Record[2 + i];
2146 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2147 C->setSelectionKind(SK);
2148 ComdatList.push_back(C);
2151 // GLOBALVAR: [pointer type, isconst, initid,
2152 // linkage, alignment, section, visibility, threadlocal,
2153 // unnamed_addr, dllstorageclass]
2154 case bitc::MODULE_CODE_GLOBALVAR: {
2155 if (Record.size() < 6)
2156 return Error("Invalid record");
2157 Type *Ty = getTypeByID(Record[0]);
2159 return Error("Invalid record");
2160 if (!Ty->isPointerTy())
2161 return Error("Invalid type for value");
2162 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2163 Ty = cast<PointerType>(Ty)->getElementType();
2165 bool isConstant = Record[1];
2166 uint64_t RawLinkage = Record[3];
2167 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2168 unsigned Alignment = (1 << Record[4]) >> 1;
2169 std::string Section;
2171 if (Record[5]-1 >= SectionTable.size())
2172 return Error("Invalid ID");
2173 Section = SectionTable[Record[5]-1];
2175 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2176 // Local linkage must have default visibility.
2177 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2178 // FIXME: Change to an error if non-default in 4.0.
2179 Visibility = GetDecodedVisibility(Record[6]);
2181 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2182 if (Record.size() > 7)
2183 TLM = GetDecodedThreadLocalMode(Record[7]);
2185 bool UnnamedAddr = false;
2186 if (Record.size() > 8)
2187 UnnamedAddr = Record[8];
2189 bool ExternallyInitialized = false;
2190 if (Record.size() > 9)
2191 ExternallyInitialized = Record[9];
2193 GlobalVariable *NewGV =
2194 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2195 TLM, AddressSpace, ExternallyInitialized);
2196 NewGV->setAlignment(Alignment);
2197 if (!Section.empty())
2198 NewGV->setSection(Section);
2199 NewGV->setVisibility(Visibility);
2200 NewGV->setUnnamedAddr(UnnamedAddr);
2202 if (Record.size() > 10)
2203 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2205 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2207 ValueList.push_back(NewGV);
2209 // Remember which value to use for the global initializer.
2210 if (unsigned InitID = Record[2])
2211 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2213 if (Record.size() > 11) {
2214 if (unsigned ComdatID = Record[11]) {
2215 assert(ComdatID <= ComdatList.size());
2216 NewGV->setComdat(ComdatList[ComdatID - 1]);
2218 } else if (hasImplicitComdat(RawLinkage)) {
2219 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2223 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2224 // alignment, section, visibility, gc, unnamed_addr,
2225 // prologuedata, dllstorageclass, comdat, prefixdata]
2226 case bitc::MODULE_CODE_FUNCTION: {
2227 if (Record.size() < 8)
2228 return Error("Invalid record");
2229 Type *Ty = getTypeByID(Record[0]);
2231 return Error("Invalid record");
2232 if (!Ty->isPointerTy())
2233 return Error("Invalid type for value");
2235 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2237 return Error("Invalid type for value");
2239 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2242 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2243 bool isProto = Record[2];
2244 uint64_t RawLinkage = Record[3];
2245 Func->setLinkage(getDecodedLinkage(RawLinkage));
2246 Func->setAttributes(getAttributes(Record[4]));
2248 Func->setAlignment((1 << Record[5]) >> 1);
2250 if (Record[6]-1 >= SectionTable.size())
2251 return Error("Invalid ID");
2252 Func->setSection(SectionTable[Record[6]-1]);
2254 // Local linkage must have default visibility.
2255 if (!Func->hasLocalLinkage())
2256 // FIXME: Change to an error if non-default in 4.0.
2257 Func->setVisibility(GetDecodedVisibility(Record[7]));
2258 if (Record.size() > 8 && Record[8]) {
2259 if (Record[8]-1 > GCTable.size())
2260 return Error("Invalid ID");
2261 Func->setGC(GCTable[Record[8]-1].c_str());
2263 bool UnnamedAddr = false;
2264 if (Record.size() > 9)
2265 UnnamedAddr = Record[9];
2266 Func->setUnnamedAddr(UnnamedAddr);
2267 if (Record.size() > 10 && Record[10] != 0)
2268 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2270 if (Record.size() > 11)
2271 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2273 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2275 if (Record.size() > 12) {
2276 if (unsigned ComdatID = Record[12]) {
2277 assert(ComdatID <= ComdatList.size());
2278 Func->setComdat(ComdatList[ComdatID - 1]);
2280 } else if (hasImplicitComdat(RawLinkage)) {
2281 Func->setComdat(reinterpret_cast<Comdat *>(1));
2284 if (Record.size() > 13 && Record[13] != 0)
2285 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2287 ValueList.push_back(Func);
2289 // If this is a function with a body, remember the prototype we are
2290 // creating now, so that we can match up the body with them later.
2292 Func->setIsMaterializable(true);
2293 FunctionsWithBodies.push_back(Func);
2295 DeferredFunctionInfo[Func] = 0;
2299 // ALIAS: [alias type, aliasee val#, linkage]
2300 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2301 case bitc::MODULE_CODE_ALIAS: {
2302 if (Record.size() < 3)
2303 return Error("Invalid record");
2304 Type *Ty = getTypeByID(Record[0]);
2306 return Error("Invalid record");
2307 auto *PTy = dyn_cast<PointerType>(Ty);
2309 return Error("Invalid type for value");
2312 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2313 getDecodedLinkage(Record[2]), "", TheModule);
2314 // Old bitcode files didn't have visibility field.
2315 // Local linkage must have default visibility.
2316 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2317 // FIXME: Change to an error if non-default in 4.0.
2318 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2319 if (Record.size() > 4)
2320 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2322 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2323 if (Record.size() > 5)
2324 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2325 if (Record.size() > 6)
2326 NewGA->setUnnamedAddr(Record[6]);
2327 ValueList.push_back(NewGA);
2328 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2331 /// MODULE_CODE_PURGEVALS: [numvals]
2332 case bitc::MODULE_CODE_PURGEVALS:
2333 // Trim down the value list to the specified size.
2334 if (Record.size() < 1 || Record[0] > ValueList.size())
2335 return Error("Invalid record");
2336 ValueList.shrinkTo(Record[0]);
2343 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2344 TheModule = nullptr;
2346 if (std::error_code EC = InitStream())
2349 // Sniff for the signature.
2350 if (Stream.Read(8) != 'B' ||
2351 Stream.Read(8) != 'C' ||
2352 Stream.Read(4) != 0x0 ||
2353 Stream.Read(4) != 0xC ||
2354 Stream.Read(4) != 0xE ||
2355 Stream.Read(4) != 0xD)
2356 return Error("Invalid bitcode signature");
2358 // We expect a number of well-defined blocks, though we don't necessarily
2359 // need to understand them all.
2361 if (Stream.AtEndOfStream())
2362 return std::error_code();
2364 BitstreamEntry Entry =
2365 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2367 switch (Entry.Kind) {
2368 case BitstreamEntry::Error:
2369 return Error("Malformed block");
2370 case BitstreamEntry::EndBlock:
2371 return std::error_code();
2373 case BitstreamEntry::SubBlock:
2375 case bitc::BLOCKINFO_BLOCK_ID:
2376 if (Stream.ReadBlockInfoBlock())
2377 return Error("Malformed block");
2379 case bitc::MODULE_BLOCK_ID:
2380 // Reject multiple MODULE_BLOCK's in a single bitstream.
2382 return Error("Invalid multiple blocks");
2384 if (std::error_code EC = ParseModule(false))
2387 return std::error_code();
2390 if (Stream.SkipBlock())
2391 return Error("Invalid record");
2395 case BitstreamEntry::Record:
2396 // There should be no records in the top-level of blocks.
2398 // The ranlib in Xcode 4 will align archive members by appending newlines
2399 // to the end of them. If this file size is a multiple of 4 but not 8, we
2400 // have to read and ignore these final 4 bytes :-(
2401 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2402 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2403 Stream.AtEndOfStream())
2404 return std::error_code();
2406 return Error("Invalid record");
2411 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2412 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2413 return Error("Invalid record");
2415 SmallVector<uint64_t, 64> Record;
2418 // Read all the records for this module.
2420 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2422 switch (Entry.Kind) {
2423 case BitstreamEntry::SubBlock: // Handled for us already.
2424 case BitstreamEntry::Error:
2425 return Error("Malformed block");
2426 case BitstreamEntry::EndBlock:
2428 case BitstreamEntry::Record:
2429 // The interesting case.
2434 switch (Stream.readRecord(Entry.ID, Record)) {
2435 default: break; // Default behavior, ignore unknown content.
2436 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2438 if (ConvertToString(Record, 0, S))
2439 return Error("Invalid record");
2446 llvm_unreachable("Exit infinite loop");
2449 ErrorOr<std::string> BitcodeReader::parseTriple() {
2450 if (std::error_code EC = InitStream())
2453 // Sniff for the signature.
2454 if (Stream.Read(8) != 'B' ||
2455 Stream.Read(8) != 'C' ||
2456 Stream.Read(4) != 0x0 ||
2457 Stream.Read(4) != 0xC ||
2458 Stream.Read(4) != 0xE ||
2459 Stream.Read(4) != 0xD)
2460 return Error("Invalid bitcode signature");
2462 // We expect a number of well-defined blocks, though we don't necessarily
2463 // need to understand them all.
2465 BitstreamEntry Entry = Stream.advance();
2467 switch (Entry.Kind) {
2468 case BitstreamEntry::Error:
2469 return Error("Malformed block");
2470 case BitstreamEntry::EndBlock:
2471 return std::error_code();
2473 case BitstreamEntry::SubBlock:
2474 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2475 return parseModuleTriple();
2477 // Ignore other sub-blocks.
2478 if (Stream.SkipBlock())
2479 return Error("Malformed block");
2482 case BitstreamEntry::Record:
2483 Stream.skipRecord(Entry.ID);
2489 /// ParseMetadataAttachment - Parse metadata attachments.
2490 std::error_code BitcodeReader::ParseMetadataAttachment() {
2491 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2492 return Error("Invalid record");
2494 SmallVector<uint64_t, 64> Record;
2496 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2498 switch (Entry.Kind) {
2499 case BitstreamEntry::SubBlock: // Handled for us already.
2500 case BitstreamEntry::Error:
2501 return Error("Malformed block");
2502 case BitstreamEntry::EndBlock:
2503 return std::error_code();
2504 case BitstreamEntry::Record:
2505 // The interesting case.
2509 // Read a metadata attachment record.
2511 switch (Stream.readRecord(Entry.ID, Record)) {
2512 default: // Default behavior: ignore.
2514 case bitc::METADATA_ATTACHMENT: {
2515 unsigned RecordLength = Record.size();
2516 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2517 return Error("Invalid record");
2518 Instruction *Inst = InstructionList[Record[0]];
2519 for (unsigned i = 1; i != RecordLength; i = i+2) {
2520 unsigned Kind = Record[i];
2521 DenseMap<unsigned, unsigned>::iterator I =
2522 MDKindMap.find(Kind);
2523 if (I == MDKindMap.end())
2524 return Error("Invalid ID");
2525 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2526 if (isa<LocalAsMetadata>(Node))
2527 // Drop the attachment. This used to be legal, but there's no
2530 Inst->setMetadata(I->second, cast<MDNode>(Node));
2531 if (I->second == LLVMContext::MD_tbaa)
2532 InstsWithTBAATag.push_back(Inst);
2540 /// ParseFunctionBody - Lazily parse the specified function body block.
2541 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2542 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2543 return Error("Invalid record");
2545 InstructionList.clear();
2546 unsigned ModuleValueListSize = ValueList.size();
2547 unsigned ModuleMDValueListSize = MDValueList.size();
2549 // Add all the function arguments to the value table.
2550 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2551 ValueList.push_back(I);
2553 unsigned NextValueNo = ValueList.size();
2554 BasicBlock *CurBB = nullptr;
2555 unsigned CurBBNo = 0;
2558 auto getLastInstruction = [&]() -> Instruction * {
2559 if (CurBB && !CurBB->empty())
2560 return &CurBB->back();
2561 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2562 !FunctionBBs[CurBBNo - 1]->empty())
2563 return &FunctionBBs[CurBBNo - 1]->back();
2567 // Read all the records.
2568 SmallVector<uint64_t, 64> Record;
2570 BitstreamEntry Entry = Stream.advance();
2572 switch (Entry.Kind) {
2573 case BitstreamEntry::Error:
2574 return Error("Malformed block");
2575 case BitstreamEntry::EndBlock:
2576 goto OutOfRecordLoop;
2578 case BitstreamEntry::SubBlock:
2580 default: // Skip unknown content.
2581 if (Stream.SkipBlock())
2582 return Error("Invalid record");
2584 case bitc::CONSTANTS_BLOCK_ID:
2585 if (std::error_code EC = ParseConstants())
2587 NextValueNo = ValueList.size();
2589 case bitc::VALUE_SYMTAB_BLOCK_ID:
2590 if (std::error_code EC = ParseValueSymbolTable())
2593 case bitc::METADATA_ATTACHMENT_ID:
2594 if (std::error_code EC = ParseMetadataAttachment())
2597 case bitc::METADATA_BLOCK_ID:
2598 if (std::error_code EC = ParseMetadata())
2601 case bitc::USELIST_BLOCK_ID:
2602 if (std::error_code EC = ParseUseLists())
2608 case BitstreamEntry::Record:
2609 // The interesting case.
2615 Instruction *I = nullptr;
2616 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2618 default: // Default behavior: reject
2619 return Error("Invalid value");
2620 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2621 if (Record.size() < 1 || Record[0] == 0)
2622 return Error("Invalid record");
2623 // Create all the basic blocks for the function.
2624 FunctionBBs.resize(Record[0]);
2626 // See if anything took the address of blocks in this function.
2627 auto BBFRI = BasicBlockFwdRefs.find(F);
2628 if (BBFRI == BasicBlockFwdRefs.end()) {
2629 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2630 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2632 auto &BBRefs = BBFRI->second;
2633 // Check for invalid basic block references.
2634 if (BBRefs.size() > FunctionBBs.size())
2635 return Error("Invalid ID");
2636 assert(!BBRefs.empty() && "Unexpected empty array");
2637 assert(!BBRefs.front() && "Invalid reference to entry block");
2638 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2640 if (I < RE && BBRefs[I]) {
2641 BBRefs[I]->insertInto(F);
2642 FunctionBBs[I] = BBRefs[I];
2644 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2647 // Erase from the table.
2648 BasicBlockFwdRefs.erase(BBFRI);
2651 CurBB = FunctionBBs[0];
2655 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2656 // This record indicates that the last instruction is at the same
2657 // location as the previous instruction with a location.
2658 I = getLastInstruction();
2661 return Error("Invalid record");
2662 I->setDebugLoc(LastLoc);
2666 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2667 I = getLastInstruction();
2668 if (!I || Record.size() < 4)
2669 return Error("Invalid record");
2671 unsigned Line = Record[0], Col = Record[1];
2672 unsigned ScopeID = Record[2], IAID = Record[3];
2674 MDNode *Scope = nullptr, *IA = nullptr;
2675 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2676 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2677 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2678 I->setDebugLoc(LastLoc);
2683 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2686 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2687 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2688 OpNum+1 > Record.size())
2689 return Error("Invalid record");
2691 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2693 return Error("Invalid record");
2694 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2695 InstructionList.push_back(I);
2696 if (OpNum < Record.size()) {
2697 if (Opc == Instruction::Add ||
2698 Opc == Instruction::Sub ||
2699 Opc == Instruction::Mul ||
2700 Opc == Instruction::Shl) {
2701 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2702 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2703 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2704 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2705 } else if (Opc == Instruction::SDiv ||
2706 Opc == Instruction::UDiv ||
2707 Opc == Instruction::LShr ||
2708 Opc == Instruction::AShr) {
2709 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2710 cast<BinaryOperator>(I)->setIsExact(true);
2711 } else if (isa<FPMathOperator>(I)) {
2713 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2714 FMF.setUnsafeAlgebra();
2715 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2717 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2719 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2720 FMF.setNoSignedZeros();
2721 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2722 FMF.setAllowReciprocal();
2724 I->setFastMathFlags(FMF);
2730 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2733 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2734 OpNum+2 != Record.size())
2735 return Error("Invalid record");
2737 Type *ResTy = getTypeByID(Record[OpNum]);
2738 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2739 if (Opc == -1 || !ResTy)
2740 return Error("Invalid record");
2741 Instruction *Temp = nullptr;
2742 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2744 InstructionList.push_back(Temp);
2745 CurBB->getInstList().push_back(Temp);
2748 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2750 InstructionList.push_back(I);
2753 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2754 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2757 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2758 return Error("Invalid record");
2760 SmallVector<Value*, 16> GEPIdx;
2761 while (OpNum != Record.size()) {
2763 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2764 return Error("Invalid record");
2765 GEPIdx.push_back(Op);
2768 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2769 InstructionList.push_back(I);
2770 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2771 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2775 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2776 // EXTRACTVAL: [opty, opval, n x indices]
2779 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2780 return Error("Invalid record");
2782 SmallVector<unsigned, 4> EXTRACTVALIdx;
2783 for (unsigned RecSize = Record.size();
2784 OpNum != RecSize; ++OpNum) {
2785 uint64_t Index = Record[OpNum];
2786 if ((unsigned)Index != Index)
2787 return Error("Invalid value");
2788 EXTRACTVALIdx.push_back((unsigned)Index);
2791 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2792 InstructionList.push_back(I);
2796 case bitc::FUNC_CODE_INST_INSERTVAL: {
2797 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2800 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2801 return Error("Invalid record");
2803 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2804 return Error("Invalid record");
2806 SmallVector<unsigned, 4> INSERTVALIdx;
2807 for (unsigned RecSize = Record.size();
2808 OpNum != RecSize; ++OpNum) {
2809 uint64_t Index = Record[OpNum];
2810 if ((unsigned)Index != Index)
2811 return Error("Invalid value");
2812 INSERTVALIdx.push_back((unsigned)Index);
2815 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2816 InstructionList.push_back(I);
2820 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2821 // obsolete form of select
2822 // handles select i1 ... in old bitcode
2824 Value *TrueVal, *FalseVal, *Cond;
2825 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2826 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2827 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2828 return Error("Invalid record");
2830 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2831 InstructionList.push_back(I);
2835 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2836 // new form of select
2837 // handles select i1 or select [N x i1]
2839 Value *TrueVal, *FalseVal, *Cond;
2840 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2841 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2842 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2843 return Error("Invalid record");
2845 // select condition can be either i1 or [N x i1]
2846 if (VectorType* vector_type =
2847 dyn_cast<VectorType>(Cond->getType())) {
2849 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2850 return Error("Invalid type for value");
2853 if (Cond->getType() != Type::getInt1Ty(Context))
2854 return Error("Invalid type for value");
2857 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2858 InstructionList.push_back(I);
2862 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2865 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2866 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2867 return Error("Invalid record");
2868 I = ExtractElementInst::Create(Vec, Idx);
2869 InstructionList.push_back(I);
2873 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2875 Value *Vec, *Elt, *Idx;
2876 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2877 popValue(Record, OpNum, NextValueNo,
2878 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2879 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2880 return Error("Invalid record");
2881 I = InsertElementInst::Create(Vec, Elt, Idx);
2882 InstructionList.push_back(I);
2886 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2888 Value *Vec1, *Vec2, *Mask;
2889 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2890 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2891 return Error("Invalid record");
2893 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2894 return Error("Invalid record");
2895 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2896 InstructionList.push_back(I);
2900 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2901 // Old form of ICmp/FCmp returning bool
2902 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2903 // both legal on vectors but had different behaviour.
2904 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2905 // FCmp/ICmp returning bool or vector of bool
2909 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2910 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2911 OpNum+1 != Record.size())
2912 return Error("Invalid record");
2914 if (LHS->getType()->isFPOrFPVectorTy())
2915 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2917 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2918 InstructionList.push_back(I);
2922 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2924 unsigned Size = Record.size();
2926 I = ReturnInst::Create(Context);
2927 InstructionList.push_back(I);
2932 Value *Op = nullptr;
2933 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2934 return Error("Invalid record");
2935 if (OpNum != Record.size())
2936 return Error("Invalid record");
2938 I = ReturnInst::Create(Context, Op);
2939 InstructionList.push_back(I);
2942 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2943 if (Record.size() != 1 && Record.size() != 3)
2944 return Error("Invalid record");
2945 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2947 return Error("Invalid record");
2949 if (Record.size() == 1) {
2950 I = BranchInst::Create(TrueDest);
2951 InstructionList.push_back(I);
2954 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2955 Value *Cond = getValue(Record, 2, NextValueNo,
2956 Type::getInt1Ty(Context));
2957 if (!FalseDest || !Cond)
2958 return Error("Invalid record");
2959 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2960 InstructionList.push_back(I);
2964 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2966 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2967 // "New" SwitchInst format with case ranges. The changes to write this
2968 // format were reverted but we still recognize bitcode that uses it.
2969 // Hopefully someday we will have support for case ranges and can use
2970 // this format again.
2972 Type *OpTy = getTypeByID(Record[1]);
2973 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2975 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2976 BasicBlock *Default = getBasicBlock(Record[3]);
2977 if (!OpTy || !Cond || !Default)
2978 return Error("Invalid record");
2980 unsigned NumCases = Record[4];
2982 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2983 InstructionList.push_back(SI);
2985 unsigned CurIdx = 5;
2986 for (unsigned i = 0; i != NumCases; ++i) {
2987 SmallVector<ConstantInt*, 1> CaseVals;
2988 unsigned NumItems = Record[CurIdx++];
2989 for (unsigned ci = 0; ci != NumItems; ++ci) {
2990 bool isSingleNumber = Record[CurIdx++];
2993 unsigned ActiveWords = 1;
2994 if (ValueBitWidth > 64)
2995 ActiveWords = Record[CurIdx++];
2996 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2998 CurIdx += ActiveWords;
3000 if (!isSingleNumber) {
3002 if (ValueBitWidth > 64)
3003 ActiveWords = Record[CurIdx++];
3005 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3007 CurIdx += ActiveWords;
3009 // FIXME: It is not clear whether values in the range should be
3010 // compared as signed or unsigned values. The partially
3011 // implemented changes that used this format in the past used
3012 // unsigned comparisons.
3013 for ( ; Low.ule(High); ++Low)
3014 CaseVals.push_back(ConstantInt::get(Context, Low));
3016 CaseVals.push_back(ConstantInt::get(Context, Low));
3018 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3019 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3020 cve = CaseVals.end(); cvi != cve; ++cvi)
3021 SI->addCase(*cvi, DestBB);
3027 // Old SwitchInst format without case ranges.
3029 if (Record.size() < 3 || (Record.size() & 1) == 0)
3030 return Error("Invalid record");
3031 Type *OpTy = getTypeByID(Record[0]);
3032 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3033 BasicBlock *Default = getBasicBlock(Record[2]);
3034 if (!OpTy || !Cond || !Default)
3035 return Error("Invalid record");
3036 unsigned NumCases = (Record.size()-3)/2;
3037 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3038 InstructionList.push_back(SI);
3039 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3040 ConstantInt *CaseVal =
3041 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3042 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3043 if (!CaseVal || !DestBB) {
3045 return Error("Invalid record");
3047 SI->addCase(CaseVal, DestBB);
3052 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3053 if (Record.size() < 2)
3054 return Error("Invalid record");
3055 Type *OpTy = getTypeByID(Record[0]);
3056 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3057 if (!OpTy || !Address)
3058 return Error("Invalid record");
3059 unsigned NumDests = Record.size()-2;
3060 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3061 InstructionList.push_back(IBI);
3062 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3063 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3064 IBI->addDestination(DestBB);
3067 return Error("Invalid record");
3074 case bitc::FUNC_CODE_INST_INVOKE: {
3075 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3076 if (Record.size() < 4)
3077 return Error("Invalid record");
3078 AttributeSet PAL = getAttributes(Record[0]);
3079 unsigned CCInfo = Record[1];
3080 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3081 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3085 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3086 return Error("Invalid record");
3088 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3089 FunctionType *FTy = !CalleeTy ? nullptr :
3090 dyn_cast<FunctionType>(CalleeTy->getElementType());
3092 // Check that the right number of fixed parameters are here.
3093 if (!FTy || !NormalBB || !UnwindBB ||
3094 Record.size() < OpNum+FTy->getNumParams())
3095 return Error("Invalid record");
3097 SmallVector<Value*, 16> Ops;
3098 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3099 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3100 FTy->getParamType(i)));
3102 return Error("Invalid record");
3105 if (!FTy->isVarArg()) {
3106 if (Record.size() != OpNum)
3107 return Error("Invalid record");
3109 // Read type/value pairs for varargs params.
3110 while (OpNum != Record.size()) {
3112 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3113 return Error("Invalid record");
3118 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3119 InstructionList.push_back(I);
3120 cast<InvokeInst>(I)->setCallingConv(
3121 static_cast<CallingConv::ID>(CCInfo));
3122 cast<InvokeInst>(I)->setAttributes(PAL);
3125 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3127 Value *Val = nullptr;
3128 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3129 return Error("Invalid record");
3130 I = ResumeInst::Create(Val);
3131 InstructionList.push_back(I);
3134 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3135 I = new UnreachableInst(Context);
3136 InstructionList.push_back(I);
3138 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3139 if (Record.size() < 1 || ((Record.size()-1)&1))
3140 return Error("Invalid record");
3141 Type *Ty = getTypeByID(Record[0]);
3143 return Error("Invalid record");
3145 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3146 InstructionList.push_back(PN);
3148 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3150 // With the new function encoding, it is possible that operands have
3151 // negative IDs (for forward references). Use a signed VBR
3152 // representation to keep the encoding small.
3154 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3156 V = getValue(Record, 1+i, NextValueNo, Ty);
3157 BasicBlock *BB = getBasicBlock(Record[2+i]);
3159 return Error("Invalid record");
3160 PN->addIncoming(V, BB);
3166 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3167 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3169 if (Record.size() < 4)
3170 return Error("Invalid record");
3171 Type *Ty = getTypeByID(Record[Idx++]);
3173 return Error("Invalid record");
3174 Value *PersFn = nullptr;
3175 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3176 return Error("Invalid record");
3178 bool IsCleanup = !!Record[Idx++];
3179 unsigned NumClauses = Record[Idx++];
3180 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3181 LP->setCleanup(IsCleanup);
3182 for (unsigned J = 0; J != NumClauses; ++J) {
3183 LandingPadInst::ClauseType CT =
3184 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3187 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3189 return Error("Invalid record");
3192 assert((CT != LandingPadInst::Catch ||
3193 !isa<ArrayType>(Val->getType())) &&
3194 "Catch clause has a invalid type!");
3195 assert((CT != LandingPadInst::Filter ||
3196 isa<ArrayType>(Val->getType())) &&
3197 "Filter clause has invalid type!");
3198 LP->addClause(cast<Constant>(Val));
3202 InstructionList.push_back(I);
3206 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3207 if (Record.size() != 4)
3208 return Error("Invalid record");
3210 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3211 Type *OpTy = getTypeByID(Record[1]);
3212 Value *Size = getFnValueByID(Record[2], OpTy);
3213 unsigned AlignRecord = Record[3];
3214 bool InAlloca = AlignRecord & (1 << 5);
3215 unsigned Align = AlignRecord & ((1 << 5) - 1);
3217 return Error("Invalid record");
3218 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3219 AI->setUsedWithInAlloca(InAlloca);
3221 InstructionList.push_back(I);
3224 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3227 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3228 OpNum+2 != Record.size())
3229 return Error("Invalid record");
3231 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3232 InstructionList.push_back(I);
3235 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3236 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3239 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3240 OpNum+4 != Record.size())
3241 return Error("Invalid record");
3243 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3244 if (Ordering == NotAtomic || Ordering == Release ||
3245 Ordering == AcquireRelease)
3246 return Error("Invalid record");
3247 if (Ordering != NotAtomic && Record[OpNum] == 0)
3248 return Error("Invalid record");
3249 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3251 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3252 Ordering, SynchScope);
3253 InstructionList.push_back(I);
3256 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3259 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3260 popValue(Record, OpNum, NextValueNo,
3261 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3262 OpNum+2 != Record.size())
3263 return Error("Invalid record");
3265 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3266 InstructionList.push_back(I);
3269 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3270 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3273 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3274 popValue(Record, OpNum, NextValueNo,
3275 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3276 OpNum+4 != Record.size())
3277 return Error("Invalid record");
3279 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3280 if (Ordering == NotAtomic || Ordering == Acquire ||
3281 Ordering == AcquireRelease)
3282 return Error("Invalid record");
3283 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3284 if (Ordering != NotAtomic && Record[OpNum] == 0)
3285 return Error("Invalid record");
3287 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3288 Ordering, SynchScope);
3289 InstructionList.push_back(I);
3292 case bitc::FUNC_CODE_INST_CMPXCHG: {
3293 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3294 // failureordering?, isweak?]
3296 Value *Ptr, *Cmp, *New;
3297 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3298 popValue(Record, OpNum, NextValueNo,
3299 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3300 popValue(Record, OpNum, NextValueNo,
3301 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3302 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3303 return Error("Invalid record");
3304 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3305 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3306 return Error("Invalid record");
3307 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3309 AtomicOrdering FailureOrdering;
3310 if (Record.size() < 7)
3312 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3314 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3316 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3318 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3320 if (Record.size() < 8) {
3321 // Before weak cmpxchgs existed, the instruction simply returned the
3322 // value loaded from memory, so bitcode files from that era will be
3323 // expecting the first component of a modern cmpxchg.
3324 CurBB->getInstList().push_back(I);
3325 I = ExtractValueInst::Create(I, 0);
3327 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3330 InstructionList.push_back(I);
3333 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3334 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3337 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3338 popValue(Record, OpNum, NextValueNo,
3339 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3340 OpNum+4 != Record.size())
3341 return Error("Invalid record");
3342 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3343 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3344 Operation > AtomicRMWInst::LAST_BINOP)
3345 return Error("Invalid record");
3346 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3347 if (Ordering == NotAtomic || Ordering == Unordered)
3348 return Error("Invalid record");
3349 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3350 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3351 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3352 InstructionList.push_back(I);
3355 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3356 if (2 != Record.size())
3357 return Error("Invalid record");
3358 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3359 if (Ordering == NotAtomic || Ordering == Unordered ||
3360 Ordering == Monotonic)
3361 return Error("Invalid record");
3362 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3363 I = new FenceInst(Context, Ordering, SynchScope);
3364 InstructionList.push_back(I);
3367 case bitc::FUNC_CODE_INST_CALL: {
3368 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3369 if (Record.size() < 3)
3370 return Error("Invalid record");
3372 AttributeSet PAL = getAttributes(Record[0]);
3373 unsigned CCInfo = Record[1];
3377 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3378 return Error("Invalid record");
3380 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3381 FunctionType *FTy = nullptr;
3382 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3383 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3384 return Error("Invalid record");
3386 SmallVector<Value*, 16> Args;
3387 // Read the fixed params.
3388 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3389 if (FTy->getParamType(i)->isLabelTy())
3390 Args.push_back(getBasicBlock(Record[OpNum]));
3392 Args.push_back(getValue(Record, OpNum, NextValueNo,
3393 FTy->getParamType(i)));
3395 return Error("Invalid record");
3398 // Read type/value pairs for varargs params.
3399 if (!FTy->isVarArg()) {
3400 if (OpNum != Record.size())
3401 return Error("Invalid record");
3403 while (OpNum != Record.size()) {
3405 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3406 return Error("Invalid record");
3411 I = CallInst::Create(Callee, Args);
3412 InstructionList.push_back(I);
3413 cast<CallInst>(I)->setCallingConv(
3414 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3415 CallInst::TailCallKind TCK = CallInst::TCK_None;
3417 TCK = CallInst::TCK_Tail;
3418 if (CCInfo & (1 << 14))
3419 TCK = CallInst::TCK_MustTail;
3420 cast<CallInst>(I)->setTailCallKind(TCK);
3421 cast<CallInst>(I)->setAttributes(PAL);
3424 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3425 if (Record.size() < 3)
3426 return Error("Invalid record");
3427 Type *OpTy = getTypeByID(Record[0]);
3428 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3429 Type *ResTy = getTypeByID(Record[2]);
3430 if (!OpTy || !Op || !ResTy)
3431 return Error("Invalid record");
3432 I = new VAArgInst(Op, ResTy);
3433 InstructionList.push_back(I);
3438 // Add instruction to end of current BB. If there is no current BB, reject
3442 return Error("Invalid instruction with no BB");
3444 CurBB->getInstList().push_back(I);
3446 // If this was a terminator instruction, move to the next block.
3447 if (isa<TerminatorInst>(I)) {
3449 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3452 // Non-void values get registered in the value table for future use.
3453 if (I && !I->getType()->isVoidTy())
3454 ValueList.AssignValue(I, NextValueNo++);
3459 // Check the function list for unresolved values.
3460 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3461 if (!A->getParent()) {
3462 // We found at least one unresolved value. Nuke them all to avoid leaks.
3463 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3464 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3465 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3469 return Error("Never resolved value found in function");
3473 // FIXME: Check for unresolved forward-declared metadata references
3474 // and clean up leaks.
3476 // Trim the value list down to the size it was before we parsed this function.
3477 ValueList.shrinkTo(ModuleValueListSize);
3478 MDValueList.shrinkTo(ModuleMDValueListSize);
3479 std::vector<BasicBlock*>().swap(FunctionBBs);
3480 return std::error_code();
3483 /// Find the function body in the bitcode stream
3484 std::error_code BitcodeReader::FindFunctionInStream(
3486 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3487 while (DeferredFunctionInfoIterator->second == 0) {
3488 if (Stream.AtEndOfStream())
3489 return Error("Could not find function in stream");
3490 // ParseModule will parse the next body in the stream and set its
3491 // position in the DeferredFunctionInfo map.
3492 if (std::error_code EC = ParseModule(true))
3495 return std::error_code();
3498 //===----------------------------------------------------------------------===//
3499 // GVMaterializer implementation
3500 //===----------------------------------------------------------------------===//
3502 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3504 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3505 Function *F = dyn_cast<Function>(GV);
3506 // If it's not a function or is already material, ignore the request.
3507 if (!F || !F->isMaterializable())
3508 return std::error_code();
3510 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3511 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3512 // If its position is recorded as 0, its body is somewhere in the stream
3513 // but we haven't seen it yet.
3514 if (DFII->second == 0 && LazyStreamer)
3515 if (std::error_code EC = FindFunctionInStream(F, DFII))
3518 // Move the bit stream to the saved position of the deferred function body.
3519 Stream.JumpToBit(DFII->second);
3521 if (std::error_code EC = ParseFunctionBody(F))
3523 F->setIsMaterializable(false);
3525 // Upgrade any old intrinsic calls in the function.
3526 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3527 E = UpgradedIntrinsics.end(); I != E; ++I) {
3528 if (I->first != I->second) {
3529 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3531 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3532 UpgradeIntrinsicCall(CI, I->second);
3537 // Bring in any functions that this function forward-referenced via
3539 return materializeForwardReferencedFunctions();
3542 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3543 const Function *F = dyn_cast<Function>(GV);
3544 if (!F || F->isDeclaration())
3547 // Dematerializing F would leave dangling references that wouldn't be
3548 // reconnected on re-materialization.
3549 if (BlockAddressesTaken.count(F))
3552 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3555 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3556 Function *F = dyn_cast<Function>(GV);
3557 // If this function isn't dematerializable, this is a noop.
3558 if (!F || !isDematerializable(F))
3561 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3563 // Just forget the function body, we can remat it later.
3564 F->dropAllReferences();
3565 F->setIsMaterializable(true);
3568 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3569 assert(M == TheModule &&
3570 "Can only Materialize the Module this BitcodeReader is attached to.");
3572 // Promise to materialize all forward references.
3573 WillMaterializeAllForwardRefs = true;
3575 // Iterate over the module, deserializing any functions that are still on
3577 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3579 if (std::error_code EC = materialize(F))
3582 // At this point, if there are any function bodies, the current bit is
3583 // pointing to the END_BLOCK record after them. Now make sure the rest
3584 // of the bits in the module have been read.
3588 // Check that all block address forward references got resolved (as we
3590 if (!BasicBlockFwdRefs.empty())
3591 return Error("Never resolved function from blockaddress");
3593 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3594 // delete the old functions to clean up. We can't do this unless the entire
3595 // module is materialized because there could always be another function body
3596 // with calls to the old function.
3597 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3598 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3599 if (I->first != I->second) {
3600 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3602 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3603 UpgradeIntrinsicCall(CI, I->second);
3605 if (!I->first->use_empty())
3606 I->first->replaceAllUsesWith(I->second);
3607 I->first->eraseFromParent();
3610 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3612 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3613 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3615 UpgradeDebugInfo(*M);
3616 return std::error_code();
3619 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3620 return IdentifiedStructTypes;
3623 std::error_code BitcodeReader::InitStream() {
3625 return InitLazyStream();
3626 return InitStreamFromBuffer();
3629 std::error_code BitcodeReader::InitStreamFromBuffer() {
3630 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3631 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3633 if (Buffer->getBufferSize() & 3)
3634 return Error("Invalid bitcode signature");
3636 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3637 // The magic number is 0x0B17C0DE stored in little endian.
3638 if (isBitcodeWrapper(BufPtr, BufEnd))
3639 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3640 return Error("Invalid bitcode wrapper header");
3642 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3643 Stream.init(&*StreamFile);
3645 return std::error_code();
3648 std::error_code BitcodeReader::InitLazyStream() {
3649 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3651 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3652 StreamingMemoryObject &Bytes = *OwnedBytes;
3653 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3654 Stream.init(&*StreamFile);
3656 unsigned char buf[16];
3657 if (Bytes.readBytes(buf, 16, 0) != 16)
3658 return Error("Invalid bitcode signature");
3660 if (!isBitcode(buf, buf + 16))
3661 return Error("Invalid bitcode signature");
3663 if (isBitcodeWrapper(buf, buf + 4)) {
3664 const unsigned char *bitcodeStart = buf;
3665 const unsigned char *bitcodeEnd = buf + 16;
3666 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3667 Bytes.dropLeadingBytes(bitcodeStart - buf);
3668 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3670 return std::error_code();
3674 class BitcodeErrorCategoryType : public std::error_category {
3675 const char *name() const LLVM_NOEXCEPT override {
3676 return "llvm.bitcode";
3678 std::string message(int IE) const override {
3679 BitcodeError E = static_cast<BitcodeError>(IE);
3681 case BitcodeError::InvalidBitcodeSignature:
3682 return "Invalid bitcode signature";
3683 case BitcodeError::CorruptedBitcode:
3684 return "Corrupted bitcode";
3686 llvm_unreachable("Unknown error type!");
3691 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3693 const std::error_category &llvm::BitcodeErrorCategory() {
3694 return *ErrorCategory;
3697 //===----------------------------------------------------------------------===//
3698 // External interface
3699 //===----------------------------------------------------------------------===//
3701 /// \brief Get a lazy one-at-time loading module from bitcode.
3703 /// This isn't always used in a lazy context. In particular, it's also used by
3704 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3705 /// in forward-referenced functions from block address references.
3707 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3708 /// materialize everything -- in particular, if this isn't truly lazy.
3709 static ErrorOr<Module *>
3710 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3711 LLVMContext &Context, bool WillMaterializeAll,
3712 DiagnosticHandlerFunction DiagnosticHandler) {
3713 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3715 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3716 M->setMaterializer(R);
3718 auto cleanupOnError = [&](std::error_code EC) {
3719 R->releaseBuffer(); // Never take ownership on error.
3720 delete M; // Also deletes R.
3724 if (std::error_code EC = R->ParseBitcodeInto(M))
3725 return cleanupOnError(EC);
3727 if (!WillMaterializeAll)
3728 // Resolve forward references from blockaddresses.
3729 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3730 return cleanupOnError(EC);
3732 Buffer.release(); // The BitcodeReader owns it now.
3737 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3738 LLVMContext &Context,
3739 DiagnosticHandlerFunction DiagnosticHandler) {
3740 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3744 ErrorOr<std::unique_ptr<Module>>
3745 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3746 LLVMContext &Context,
3747 DiagnosticHandlerFunction DiagnosticHandler) {
3748 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3749 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
3750 M->setMaterializer(R);
3751 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3753 return std::move(M);
3757 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3758 DiagnosticHandlerFunction DiagnosticHandler) {
3759 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3760 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3761 std::move(Buf), Context, true, DiagnosticHandler);
3764 Module *M = ModuleOrErr.get();
3765 // Read in the entire module, and destroy the BitcodeReader.
3766 if (std::error_code EC = M->materializeAllPermanently()) {
3771 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3772 // written. We must defer until the Module has been fully materialized.
3778 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3779 DiagnosticHandlerFunction DiagnosticHandler) {
3780 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3781 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3783 ErrorOr<std::string> Triple = R->parseTriple();
3784 if (Triple.getError())
3786 return Triple.get();