1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DebugInfoMetadata.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/OperandTraits.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Support/DataStream.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
36 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
39 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
40 DiagnosticSeverity Severity,
42 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
44 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
46 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
47 std::error_code EC, const Twine &Message) {
48 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
49 DiagnosticHandler(DI);
53 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
55 return Error(DiagnosticHandler, EC, EC.message());
58 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
59 return ::Error(DiagnosticHandler, make_error_code(E), Message);
62 std::error_code BitcodeReader::Error(const Twine &Message) {
63 return ::Error(DiagnosticHandler,
64 make_error_code(BitcodeError::CorruptedBitcode), Message);
67 std::error_code BitcodeReader::Error(BitcodeError E) {
68 return ::Error(DiagnosticHandler, make_error_code(E));
71 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
75 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
78 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
79 DiagnosticHandlerFunction DiagnosticHandler)
80 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
81 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
82 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
83 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
84 WillMaterializeAllForwardRefs(false) {}
86 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
87 DiagnosticHandlerFunction DiagnosticHandler)
88 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
89 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
90 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
91 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
92 WillMaterializeAllForwardRefs(false) {}
94 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
95 if (WillMaterializeAllForwardRefs)
96 return std::error_code();
99 WillMaterializeAllForwardRefs = true;
101 while (!BasicBlockFwdRefQueue.empty()) {
102 Function *F = BasicBlockFwdRefQueue.front();
103 BasicBlockFwdRefQueue.pop_front();
104 assert(F && "Expected valid function");
105 if (!BasicBlockFwdRefs.count(F))
106 // Already materialized.
109 // Check for a function that isn't materializable to prevent an infinite
110 // loop. When parsing a blockaddress stored in a global variable, there
111 // isn't a trivial way to check if a function will have a body without a
112 // linear search through FunctionsWithBodies, so just check it here.
113 if (!F->isMaterializable())
114 return Error("Never resolved function from blockaddress");
116 // Try to materialize F.
117 if (std::error_code EC = materialize(F))
120 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
123 WillMaterializeAllForwardRefs = false;
124 return std::error_code();
127 void BitcodeReader::FreeState() {
129 std::vector<Type*>().swap(TypeList);
132 std::vector<Comdat *>().swap(ComdatList);
134 std::vector<AttributeSet>().swap(MAttributes);
135 std::vector<BasicBlock*>().swap(FunctionBBs);
136 std::vector<Function*>().swap(FunctionsWithBodies);
137 DeferredFunctionInfo.clear();
140 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
141 BasicBlockFwdRefQueue.clear();
144 //===----------------------------------------------------------------------===//
145 // Helper functions to implement forward reference resolution, etc.
146 //===----------------------------------------------------------------------===//
148 /// ConvertToString - Convert a string from a record into an std::string, return
150 template<typename StrTy>
151 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
153 if (Idx > Record.size())
156 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
157 Result += (char)Record[i];
161 static bool hasImplicitComdat(size_t Val) {
165 case 1: // Old WeakAnyLinkage
166 case 4: // Old LinkOnceAnyLinkage
167 case 10: // Old WeakODRLinkage
168 case 11: // Old LinkOnceODRLinkage
173 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
175 default: // Map unknown/new linkages to external
177 return GlobalValue::ExternalLinkage;
179 return GlobalValue::AppendingLinkage;
181 return GlobalValue::InternalLinkage;
183 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
185 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
187 return GlobalValue::ExternalWeakLinkage;
189 return GlobalValue::CommonLinkage;
191 return GlobalValue::PrivateLinkage;
193 return GlobalValue::AvailableExternallyLinkage;
195 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
197 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
199 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
200 case 1: // Old value with implicit comdat.
202 return GlobalValue::WeakAnyLinkage;
203 case 10: // Old value with implicit comdat.
205 return GlobalValue::WeakODRLinkage;
206 case 4: // Old value with implicit comdat.
208 return GlobalValue::LinkOnceAnyLinkage;
209 case 11: // Old value with implicit comdat.
211 return GlobalValue::LinkOnceODRLinkage;
215 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
217 default: // Map unknown visibilities to default.
218 case 0: return GlobalValue::DefaultVisibility;
219 case 1: return GlobalValue::HiddenVisibility;
220 case 2: return GlobalValue::ProtectedVisibility;
224 static GlobalValue::DLLStorageClassTypes
225 GetDecodedDLLStorageClass(unsigned Val) {
227 default: // Map unknown values to default.
228 case 0: return GlobalValue::DefaultStorageClass;
229 case 1: return GlobalValue::DLLImportStorageClass;
230 case 2: return GlobalValue::DLLExportStorageClass;
234 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
236 case 0: return GlobalVariable::NotThreadLocal;
237 default: // Map unknown non-zero value to general dynamic.
238 case 1: return GlobalVariable::GeneralDynamicTLSModel;
239 case 2: return GlobalVariable::LocalDynamicTLSModel;
240 case 3: return GlobalVariable::InitialExecTLSModel;
241 case 4: return GlobalVariable::LocalExecTLSModel;
245 static int GetDecodedCastOpcode(unsigned Val) {
248 case bitc::CAST_TRUNC : return Instruction::Trunc;
249 case bitc::CAST_ZEXT : return Instruction::ZExt;
250 case bitc::CAST_SEXT : return Instruction::SExt;
251 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
252 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
253 case bitc::CAST_UITOFP : return Instruction::UIToFP;
254 case bitc::CAST_SITOFP : return Instruction::SIToFP;
255 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
256 case bitc::CAST_FPEXT : return Instruction::FPExt;
257 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
258 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
259 case bitc::CAST_BITCAST : return Instruction::BitCast;
260 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
263 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
266 case bitc::BINOP_ADD:
267 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
268 case bitc::BINOP_SUB:
269 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
270 case bitc::BINOP_MUL:
271 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
272 case bitc::BINOP_UDIV: return Instruction::UDiv;
273 case bitc::BINOP_SDIV:
274 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
275 case bitc::BINOP_UREM: return Instruction::URem;
276 case bitc::BINOP_SREM:
277 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
278 case bitc::BINOP_SHL: return Instruction::Shl;
279 case bitc::BINOP_LSHR: return Instruction::LShr;
280 case bitc::BINOP_ASHR: return Instruction::AShr;
281 case bitc::BINOP_AND: return Instruction::And;
282 case bitc::BINOP_OR: return Instruction::Or;
283 case bitc::BINOP_XOR: return Instruction::Xor;
287 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
289 default: return AtomicRMWInst::BAD_BINOP;
290 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
291 case bitc::RMW_ADD: return AtomicRMWInst::Add;
292 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
293 case bitc::RMW_AND: return AtomicRMWInst::And;
294 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
295 case bitc::RMW_OR: return AtomicRMWInst::Or;
296 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
297 case bitc::RMW_MAX: return AtomicRMWInst::Max;
298 case bitc::RMW_MIN: return AtomicRMWInst::Min;
299 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
300 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
304 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
306 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
307 case bitc::ORDERING_UNORDERED: return Unordered;
308 case bitc::ORDERING_MONOTONIC: return Monotonic;
309 case bitc::ORDERING_ACQUIRE: return Acquire;
310 case bitc::ORDERING_RELEASE: return Release;
311 case bitc::ORDERING_ACQREL: return AcquireRelease;
312 default: // Map unknown orderings to sequentially-consistent.
313 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
317 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
319 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
320 default: // Map unknown scopes to cross-thread.
321 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
325 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
327 default: // Map unknown selection kinds to any.
328 case bitc::COMDAT_SELECTION_KIND_ANY:
330 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
331 return Comdat::ExactMatch;
332 case bitc::COMDAT_SELECTION_KIND_LARGEST:
333 return Comdat::Largest;
334 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
335 return Comdat::NoDuplicates;
336 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
337 return Comdat::SameSize;
341 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
343 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
344 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
350 /// @brief A class for maintaining the slot number definition
351 /// as a placeholder for the actual definition for forward constants defs.
352 class ConstantPlaceHolder : public ConstantExpr {
353 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
355 // allocate space for exactly one operand
356 void *operator new(size_t s) {
357 return User::operator new(s, 1);
359 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
360 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
361 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
364 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
365 static bool classof(const Value *V) {
366 return isa<ConstantExpr>(V) &&
367 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
371 /// Provide fast operand accessors
372 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
376 // FIXME: can we inherit this from ConstantExpr?
378 struct OperandTraits<ConstantPlaceHolder> :
379 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
381 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
385 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
394 WeakVH &OldV = ValuePtrs[Idx];
400 // Handle constants and non-constants (e.g. instrs) differently for
402 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
403 ResolveConstants.push_back(std::make_pair(PHC, Idx));
406 // If there was a forward reference to this value, replace it.
407 Value *PrevVal = OldV;
408 OldV->replaceAllUsesWith(V);
414 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
419 if (Value *V = ValuePtrs[Idx]) {
420 assert(Ty == V->getType() && "Type mismatch in constant table!");
421 return cast<Constant>(V);
424 // Create and return a placeholder, which will later be RAUW'd.
425 Constant *C = new ConstantPlaceHolder(Ty, Context);
430 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
434 if (Value *V = ValuePtrs[Idx]) {
435 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
439 // No type specified, must be invalid reference.
440 if (!Ty) return nullptr;
442 // Create and return a placeholder, which will later be RAUW'd.
443 Value *V = new Argument(Ty);
448 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
449 /// resolves any forward references. The idea behind this is that we sometimes
450 /// get constants (such as large arrays) which reference *many* forward ref
451 /// constants. Replacing each of these causes a lot of thrashing when
452 /// building/reuniquing the constant. Instead of doing this, we look at all the
453 /// uses and rewrite all the place holders at once for any constant that uses
455 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
456 // Sort the values by-pointer so that they are efficient to look up with a
458 std::sort(ResolveConstants.begin(), ResolveConstants.end());
460 SmallVector<Constant*, 64> NewOps;
462 while (!ResolveConstants.empty()) {
463 Value *RealVal = operator[](ResolveConstants.back().second);
464 Constant *Placeholder = ResolveConstants.back().first;
465 ResolveConstants.pop_back();
467 // Loop over all users of the placeholder, updating them to reference the
468 // new value. If they reference more than one placeholder, update them all
470 while (!Placeholder->use_empty()) {
471 auto UI = Placeholder->user_begin();
474 // If the using object isn't uniqued, just update the operands. This
475 // handles instructions and initializers for global variables.
476 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
477 UI.getUse().set(RealVal);
481 // Otherwise, we have a constant that uses the placeholder. Replace that
482 // constant with a new constant that has *all* placeholder uses updated.
483 Constant *UserC = cast<Constant>(U);
484 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
487 if (!isa<ConstantPlaceHolder>(*I)) {
488 // Not a placeholder reference.
490 } else if (*I == Placeholder) {
491 // Common case is that it just references this one placeholder.
494 // Otherwise, look up the placeholder in ResolveConstants.
495 ResolveConstantsTy::iterator It =
496 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
497 std::pair<Constant*, unsigned>(cast<Constant>(*I),
499 assert(It != ResolveConstants.end() && It->first == *I);
500 NewOp = operator[](It->second);
503 NewOps.push_back(cast<Constant>(NewOp));
506 // Make the new constant.
508 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
509 NewC = ConstantArray::get(UserCA->getType(), NewOps);
510 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
511 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
512 } else if (isa<ConstantVector>(UserC)) {
513 NewC = ConstantVector::get(NewOps);
515 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
516 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
519 UserC->replaceAllUsesWith(NewC);
520 UserC->destroyConstant();
524 // Update all ValueHandles, they should be the only users at this point.
525 Placeholder->replaceAllUsesWith(RealVal);
530 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
539 TrackingMDRef &OldMD = MDValuePtrs[Idx];
545 // If there was a forward reference to this value, replace it.
546 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
547 PrevMD->replaceAllUsesWith(MD);
551 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
555 if (Metadata *MD = MDValuePtrs[Idx])
558 // Create and return a placeholder, which will later be RAUW'd.
561 Metadata *MD = MDNode::getTemporary(Context, None).release();
562 MDValuePtrs[Idx].reset(MD);
566 void BitcodeReaderMDValueList::tryToResolveCycles() {
572 // Still forward references... can't resolve cycles.
575 // Resolve any cycles.
576 for (auto &MD : MDValuePtrs) {
577 auto *N = dyn_cast_or_null<MDNode>(MD);
581 assert(!N->isTemporary() && "Unexpected forward reference");
586 Type *BitcodeReader::getTypeByID(unsigned ID) {
587 // The type table size is always specified correctly.
588 if (ID >= TypeList.size())
591 if (Type *Ty = TypeList[ID])
594 // If we have a forward reference, the only possible case is when it is to a
595 // named struct. Just create a placeholder for now.
596 return TypeList[ID] = createIdentifiedStructType(Context);
599 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
601 auto *Ret = StructType::create(Context, Name);
602 IdentifiedStructTypes.push_back(Ret);
606 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
607 auto *Ret = StructType::create(Context);
608 IdentifiedStructTypes.push_back(Ret);
613 //===----------------------------------------------------------------------===//
614 // Functions for parsing blocks from the bitcode file
615 //===----------------------------------------------------------------------===//
618 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
619 /// been decoded from the given integer. This function must stay in sync with
620 /// 'encodeLLVMAttributesForBitcode'.
621 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
622 uint64_t EncodedAttrs) {
623 // FIXME: Remove in 4.0.
625 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
626 // the bits above 31 down by 11 bits.
627 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
628 assert((!Alignment || isPowerOf2_32(Alignment)) &&
629 "Alignment must be a power of two.");
632 B.addAlignmentAttr(Alignment);
633 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
634 (EncodedAttrs & 0xffff));
637 std::error_code BitcodeReader::ParseAttributeBlock() {
638 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
639 return Error("Invalid record");
641 if (!MAttributes.empty())
642 return Error("Invalid multiple blocks");
644 SmallVector<uint64_t, 64> Record;
646 SmallVector<AttributeSet, 8> Attrs;
648 // Read all the records.
650 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
652 switch (Entry.Kind) {
653 case BitstreamEntry::SubBlock: // Handled for us already.
654 case BitstreamEntry::Error:
655 return Error("Malformed block");
656 case BitstreamEntry::EndBlock:
657 return std::error_code();
658 case BitstreamEntry::Record:
659 // The interesting case.
665 switch (Stream.readRecord(Entry.ID, Record)) {
666 default: // Default behavior: ignore.
668 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
669 // FIXME: Remove in 4.0.
670 if (Record.size() & 1)
671 return Error("Invalid record");
673 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
675 decodeLLVMAttributesForBitcode(B, Record[i+1]);
676 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
679 MAttributes.push_back(AttributeSet::get(Context, Attrs));
683 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
684 for (unsigned i = 0, e = Record.size(); i != e; ++i)
685 Attrs.push_back(MAttributeGroups[Record[i]]);
687 MAttributes.push_back(AttributeSet::get(Context, Attrs));
695 // Returns Attribute::None on unrecognized codes.
696 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
699 return Attribute::None;
700 case bitc::ATTR_KIND_ALIGNMENT:
701 return Attribute::Alignment;
702 case bitc::ATTR_KIND_ALWAYS_INLINE:
703 return Attribute::AlwaysInline;
704 case bitc::ATTR_KIND_BUILTIN:
705 return Attribute::Builtin;
706 case bitc::ATTR_KIND_BY_VAL:
707 return Attribute::ByVal;
708 case bitc::ATTR_KIND_IN_ALLOCA:
709 return Attribute::InAlloca;
710 case bitc::ATTR_KIND_COLD:
711 return Attribute::Cold;
712 case bitc::ATTR_KIND_INLINE_HINT:
713 return Attribute::InlineHint;
714 case bitc::ATTR_KIND_IN_REG:
715 return Attribute::InReg;
716 case bitc::ATTR_KIND_JUMP_TABLE:
717 return Attribute::JumpTable;
718 case bitc::ATTR_KIND_MIN_SIZE:
719 return Attribute::MinSize;
720 case bitc::ATTR_KIND_NAKED:
721 return Attribute::Naked;
722 case bitc::ATTR_KIND_NEST:
723 return Attribute::Nest;
724 case bitc::ATTR_KIND_NO_ALIAS:
725 return Attribute::NoAlias;
726 case bitc::ATTR_KIND_NO_BUILTIN:
727 return Attribute::NoBuiltin;
728 case bitc::ATTR_KIND_NO_CAPTURE:
729 return Attribute::NoCapture;
730 case bitc::ATTR_KIND_NO_DUPLICATE:
731 return Attribute::NoDuplicate;
732 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
733 return Attribute::NoImplicitFloat;
734 case bitc::ATTR_KIND_NO_INLINE:
735 return Attribute::NoInline;
736 case bitc::ATTR_KIND_NON_LAZY_BIND:
737 return Attribute::NonLazyBind;
738 case bitc::ATTR_KIND_NON_NULL:
739 return Attribute::NonNull;
740 case bitc::ATTR_KIND_DEREFERENCEABLE:
741 return Attribute::Dereferenceable;
742 case bitc::ATTR_KIND_NO_RED_ZONE:
743 return Attribute::NoRedZone;
744 case bitc::ATTR_KIND_NO_RETURN:
745 return Attribute::NoReturn;
746 case bitc::ATTR_KIND_NO_UNWIND:
747 return Attribute::NoUnwind;
748 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
749 return Attribute::OptimizeForSize;
750 case bitc::ATTR_KIND_OPTIMIZE_NONE:
751 return Attribute::OptimizeNone;
752 case bitc::ATTR_KIND_READ_NONE:
753 return Attribute::ReadNone;
754 case bitc::ATTR_KIND_READ_ONLY:
755 return Attribute::ReadOnly;
756 case bitc::ATTR_KIND_RETURNED:
757 return Attribute::Returned;
758 case bitc::ATTR_KIND_RETURNS_TWICE:
759 return Attribute::ReturnsTwice;
760 case bitc::ATTR_KIND_S_EXT:
761 return Attribute::SExt;
762 case bitc::ATTR_KIND_STACK_ALIGNMENT:
763 return Attribute::StackAlignment;
764 case bitc::ATTR_KIND_STACK_PROTECT:
765 return Attribute::StackProtect;
766 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
767 return Attribute::StackProtectReq;
768 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
769 return Attribute::StackProtectStrong;
770 case bitc::ATTR_KIND_STRUCT_RET:
771 return Attribute::StructRet;
772 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
773 return Attribute::SanitizeAddress;
774 case bitc::ATTR_KIND_SANITIZE_THREAD:
775 return Attribute::SanitizeThread;
776 case bitc::ATTR_KIND_SANITIZE_MEMORY:
777 return Attribute::SanitizeMemory;
778 case bitc::ATTR_KIND_UW_TABLE:
779 return Attribute::UWTable;
780 case bitc::ATTR_KIND_Z_EXT:
781 return Attribute::ZExt;
785 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
786 Attribute::AttrKind *Kind) {
787 *Kind = GetAttrFromCode(Code);
788 if (*Kind == Attribute::None)
789 return Error(BitcodeError::CorruptedBitcode,
790 "Unknown attribute kind (" + Twine(Code) + ")");
791 return std::error_code();
794 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
795 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
796 return Error("Invalid record");
798 if (!MAttributeGroups.empty())
799 return Error("Invalid multiple blocks");
801 SmallVector<uint64_t, 64> Record;
803 // Read all the records.
805 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
807 switch (Entry.Kind) {
808 case BitstreamEntry::SubBlock: // Handled for us already.
809 case BitstreamEntry::Error:
810 return Error("Malformed block");
811 case BitstreamEntry::EndBlock:
812 return std::error_code();
813 case BitstreamEntry::Record:
814 // The interesting case.
820 switch (Stream.readRecord(Entry.ID, Record)) {
821 default: // Default behavior: ignore.
823 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
824 if (Record.size() < 3)
825 return Error("Invalid record");
827 uint64_t GrpID = Record[0];
828 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
831 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
832 if (Record[i] == 0) { // Enum attribute
833 Attribute::AttrKind Kind;
834 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
837 B.addAttribute(Kind);
838 } else if (Record[i] == 1) { // Integer attribute
839 Attribute::AttrKind Kind;
840 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
842 if (Kind == Attribute::Alignment)
843 B.addAlignmentAttr(Record[++i]);
844 else if (Kind == Attribute::StackAlignment)
845 B.addStackAlignmentAttr(Record[++i]);
846 else if (Kind == Attribute::Dereferenceable)
847 B.addDereferenceableAttr(Record[++i]);
848 } else { // String attribute
849 assert((Record[i] == 3 || Record[i] == 4) &&
850 "Invalid attribute group entry");
851 bool HasValue = (Record[i++] == 4);
852 SmallString<64> KindStr;
853 SmallString<64> ValStr;
855 while (Record[i] != 0 && i != e)
856 KindStr += Record[i++];
857 assert(Record[i] == 0 && "Kind string not null terminated");
860 // Has a value associated with it.
861 ++i; // Skip the '0' that terminates the "kind" string.
862 while (Record[i] != 0 && i != e)
863 ValStr += Record[i++];
864 assert(Record[i] == 0 && "Value string not null terminated");
867 B.addAttribute(KindStr.str(), ValStr.str());
871 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
878 std::error_code BitcodeReader::ParseTypeTable() {
879 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
880 return Error("Invalid record");
882 return ParseTypeTableBody();
885 std::error_code BitcodeReader::ParseTypeTableBody() {
886 if (!TypeList.empty())
887 return Error("Invalid multiple blocks");
889 SmallVector<uint64_t, 64> Record;
890 unsigned NumRecords = 0;
892 SmallString<64> TypeName;
894 // Read all the records for this type table.
896 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
898 switch (Entry.Kind) {
899 case BitstreamEntry::SubBlock: // Handled for us already.
900 case BitstreamEntry::Error:
901 return Error("Malformed block");
902 case BitstreamEntry::EndBlock:
903 if (NumRecords != TypeList.size())
904 return Error("Malformed block");
905 return std::error_code();
906 case BitstreamEntry::Record:
907 // The interesting case.
913 Type *ResultTy = nullptr;
914 switch (Stream.readRecord(Entry.ID, Record)) {
916 return Error("Invalid value");
917 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
918 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
919 // type list. This allows us to reserve space.
920 if (Record.size() < 1)
921 return Error("Invalid record");
922 TypeList.resize(Record[0]);
924 case bitc::TYPE_CODE_VOID: // VOID
925 ResultTy = Type::getVoidTy(Context);
927 case bitc::TYPE_CODE_HALF: // HALF
928 ResultTy = Type::getHalfTy(Context);
930 case bitc::TYPE_CODE_FLOAT: // FLOAT
931 ResultTy = Type::getFloatTy(Context);
933 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
934 ResultTy = Type::getDoubleTy(Context);
936 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
937 ResultTy = Type::getX86_FP80Ty(Context);
939 case bitc::TYPE_CODE_FP128: // FP128
940 ResultTy = Type::getFP128Ty(Context);
942 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
943 ResultTy = Type::getPPC_FP128Ty(Context);
945 case bitc::TYPE_CODE_LABEL: // LABEL
946 ResultTy = Type::getLabelTy(Context);
948 case bitc::TYPE_CODE_METADATA: // METADATA
949 ResultTy = Type::getMetadataTy(Context);
951 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
952 ResultTy = Type::getX86_MMXTy(Context);
954 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
955 if (Record.size() < 1)
956 return Error("Invalid record");
958 uint64_t NumBits = Record[0];
959 if (NumBits < IntegerType::MIN_INT_BITS ||
960 NumBits > IntegerType::MAX_INT_BITS)
961 return Error("Bitwidth for integer type out of range");
962 ResultTy = IntegerType::get(Context, NumBits);
965 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
966 // [pointee type, address space]
967 if (Record.size() < 1)
968 return Error("Invalid record");
969 unsigned AddressSpace = 0;
970 if (Record.size() == 2)
971 AddressSpace = Record[1];
972 ResultTy = getTypeByID(Record[0]);
974 return Error("Invalid type");
975 ResultTy = PointerType::get(ResultTy, AddressSpace);
978 case bitc::TYPE_CODE_FUNCTION_OLD: {
979 // FIXME: attrid is dead, remove it in LLVM 4.0
980 // FUNCTION: [vararg, attrid, retty, paramty x N]
981 if (Record.size() < 3)
982 return Error("Invalid record");
983 SmallVector<Type*, 8> ArgTys;
984 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
985 if (Type *T = getTypeByID(Record[i]))
991 ResultTy = getTypeByID(Record[2]);
992 if (!ResultTy || ArgTys.size() < Record.size()-3)
993 return Error("Invalid type");
995 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
998 case bitc::TYPE_CODE_FUNCTION: {
999 // FUNCTION: [vararg, retty, paramty x N]
1000 if (Record.size() < 2)
1001 return Error("Invalid record");
1002 SmallVector<Type*, 8> ArgTys;
1003 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1004 if (Type *T = getTypeByID(Record[i]))
1005 ArgTys.push_back(T);
1010 ResultTy = getTypeByID(Record[1]);
1011 if (!ResultTy || ArgTys.size() < Record.size()-2)
1012 return Error("Invalid type");
1014 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1017 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1018 if (Record.size() < 1)
1019 return Error("Invalid record");
1020 SmallVector<Type*, 8> EltTys;
1021 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1022 if (Type *T = getTypeByID(Record[i]))
1023 EltTys.push_back(T);
1027 if (EltTys.size() != Record.size()-1)
1028 return Error("Invalid type");
1029 ResultTy = StructType::get(Context, EltTys, Record[0]);
1032 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1033 if (ConvertToString(Record, 0, TypeName))
1034 return Error("Invalid record");
1037 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1038 if (Record.size() < 1)
1039 return Error("Invalid record");
1041 if (NumRecords >= TypeList.size())
1042 return Error("Invalid TYPE table");
1044 // Check to see if this was forward referenced, if so fill in the temp.
1045 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1047 Res->setName(TypeName);
1048 TypeList[NumRecords] = nullptr;
1049 } else // Otherwise, create a new struct.
1050 Res = createIdentifiedStructType(Context, TypeName);
1053 SmallVector<Type*, 8> EltTys;
1054 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1055 if (Type *T = getTypeByID(Record[i]))
1056 EltTys.push_back(T);
1060 if (EltTys.size() != Record.size()-1)
1061 return Error("Invalid record");
1062 Res->setBody(EltTys, Record[0]);
1066 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1067 if (Record.size() != 1)
1068 return Error("Invalid record");
1070 if (NumRecords >= TypeList.size())
1071 return Error("Invalid TYPE table");
1073 // Check to see if this was forward referenced, if so fill in the temp.
1074 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1076 Res->setName(TypeName);
1077 TypeList[NumRecords] = nullptr;
1078 } else // Otherwise, create a new struct with no body.
1079 Res = createIdentifiedStructType(Context, TypeName);
1084 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1085 if (Record.size() < 2)
1086 return Error("Invalid record");
1087 if ((ResultTy = getTypeByID(Record[1])))
1088 ResultTy = ArrayType::get(ResultTy, Record[0]);
1090 return Error("Invalid type");
1092 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1093 if (Record.size() < 2)
1094 return Error("Invalid record");
1095 if ((ResultTy = getTypeByID(Record[1])))
1096 ResultTy = VectorType::get(ResultTy, Record[0]);
1098 return Error("Invalid type");
1102 if (NumRecords >= TypeList.size())
1103 return Error("Invalid TYPE table");
1104 if (TypeList[NumRecords])
1106 "Invalid TYPE table: Only named structs can be forward referenced");
1107 assert(ResultTy && "Didn't read a type?");
1108 TypeList[NumRecords++] = ResultTy;
1112 std::error_code BitcodeReader::ParseValueSymbolTable() {
1113 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1114 return Error("Invalid record");
1116 SmallVector<uint64_t, 64> Record;
1118 Triple TT(TheModule->getTargetTriple());
1120 // Read all the records for this value table.
1121 SmallString<128> ValueName;
1123 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1125 switch (Entry.Kind) {
1126 case BitstreamEntry::SubBlock: // Handled for us already.
1127 case BitstreamEntry::Error:
1128 return Error("Malformed block");
1129 case BitstreamEntry::EndBlock:
1130 return std::error_code();
1131 case BitstreamEntry::Record:
1132 // The interesting case.
1138 switch (Stream.readRecord(Entry.ID, Record)) {
1139 default: // Default behavior: unknown type.
1141 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1142 if (ConvertToString(Record, 1, ValueName))
1143 return Error("Invalid record");
1144 unsigned ValueID = Record[0];
1145 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1146 return Error("Invalid record");
1147 Value *V = ValueList[ValueID];
1149 V->setName(StringRef(ValueName.data(), ValueName.size()));
1150 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1151 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1152 if (TT.isOSBinFormatMachO())
1153 GO->setComdat(nullptr);
1155 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1161 case bitc::VST_CODE_BBENTRY: {
1162 if (ConvertToString(Record, 1, ValueName))
1163 return Error("Invalid record");
1164 BasicBlock *BB = getBasicBlock(Record[0]);
1166 return Error("Invalid record");
1168 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1176 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1178 std::error_code BitcodeReader::ParseMetadata() {
1179 unsigned NextMDValueNo = MDValueList.size();
1181 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1182 return Error("Invalid record");
1184 SmallVector<uint64_t, 64> Record;
1186 auto getMDString = [&](unsigned ID) -> MDString *{
1187 // This requires that the ID is not really a forward reference. In
1188 // particular, the MDString must already have been resolved.
1190 return cast<MDString>(MDValueList.getValueFwdRef(ID - 1));
1194 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1195 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1197 // Read all the records.
1199 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1201 switch (Entry.Kind) {
1202 case BitstreamEntry::SubBlock: // Handled for us already.
1203 case BitstreamEntry::Error:
1204 return Error("Malformed block");
1205 case BitstreamEntry::EndBlock:
1206 MDValueList.tryToResolveCycles();
1207 return std::error_code();
1208 case BitstreamEntry::Record:
1209 // The interesting case.
1215 unsigned Code = Stream.readRecord(Entry.ID, Record);
1216 bool IsDistinct = false;
1218 default: // Default behavior: ignore.
1220 case bitc::METADATA_NAME: {
1221 // Read name of the named metadata.
1222 SmallString<8> Name(Record.begin(), Record.end());
1224 Code = Stream.ReadCode();
1226 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1227 unsigned NextBitCode = Stream.readRecord(Code, Record);
1228 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1230 // Read named metadata elements.
1231 unsigned Size = Record.size();
1232 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1233 for (unsigned i = 0; i != Size; ++i) {
1234 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1236 return Error("Invalid record");
1237 NMD->addOperand(MD);
1241 case bitc::METADATA_OLD_FN_NODE: {
1242 // FIXME: Remove in 4.0.
1243 // This is a LocalAsMetadata record, the only type of function-local
1245 if (Record.size() % 2 == 1)
1246 return Error("Invalid record");
1248 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1249 // to be legal, but there's no upgrade path.
1250 auto dropRecord = [&] {
1251 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1253 if (Record.size() != 2) {
1258 Type *Ty = getTypeByID(Record[0]);
1259 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1264 MDValueList.AssignValue(
1265 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1269 case bitc::METADATA_OLD_NODE: {
1270 // FIXME: Remove in 4.0.
1271 if (Record.size() % 2 == 1)
1272 return Error("Invalid record");
1274 unsigned Size = Record.size();
1275 SmallVector<Metadata *, 8> Elts;
1276 for (unsigned i = 0; i != Size; i += 2) {
1277 Type *Ty = getTypeByID(Record[i]);
1279 return Error("Invalid record");
1280 if (Ty->isMetadataTy())
1281 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1282 else if (!Ty->isVoidTy()) {
1284 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1285 assert(isa<ConstantAsMetadata>(MD) &&
1286 "Expected non-function-local metadata");
1289 Elts.push_back(nullptr);
1291 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1294 case bitc::METADATA_VALUE: {
1295 if (Record.size() != 2)
1296 return Error("Invalid record");
1298 Type *Ty = getTypeByID(Record[0]);
1299 if (Ty->isMetadataTy() || Ty->isVoidTy())
1300 return Error("Invalid record");
1302 MDValueList.AssignValue(
1303 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1307 case bitc::METADATA_DISTINCT_NODE:
1310 case bitc::METADATA_NODE: {
1311 SmallVector<Metadata *, 8> Elts;
1312 Elts.reserve(Record.size());
1313 for (unsigned ID : Record)
1314 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1315 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1316 : MDNode::get(Context, Elts),
1320 case bitc::METADATA_LOCATION: {
1321 if (Record.size() != 5)
1322 return Error("Invalid record");
1324 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1325 unsigned Line = Record[1];
1326 unsigned Column = Record[2];
1327 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1328 Metadata *InlinedAt =
1329 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1330 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1334 case bitc::METADATA_GENERIC_DEBUG: {
1335 if (Record.size() < 4)
1336 return Error("Invalid record");
1338 unsigned Tag = Record[1];
1339 unsigned Version = Record[2];
1341 if (Tag >= 1u << 16 || Version != 0)
1342 return Error("Invalid record");
1344 auto *Header = getMDString(Record[3]);
1345 SmallVector<Metadata *, 8> DwarfOps;
1346 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1347 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1349 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1350 (Context, Tag, Header, DwarfOps)),
1354 case bitc::METADATA_SUBRANGE: {
1355 if (Record.size() != 3)
1356 return Error("Invalid record");
1358 MDValueList.AssignValue(
1359 GET_OR_DISTINCT(MDSubrange, Record[0],
1360 (Context, Record[1], unrotateSign(Record[2]))),
1364 case bitc::METADATA_ENUMERATOR: {
1365 if (Record.size() != 3)
1366 return Error("Invalid record");
1368 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1369 (Context, unrotateSign(Record[1]),
1370 getMDString(Record[2]))),
1374 case bitc::METADATA_BASIC_TYPE: {
1375 if (Record.size() != 6)
1376 return Error("Invalid record");
1378 MDValueList.AssignValue(
1379 GET_OR_DISTINCT(MDBasicType, Record[0],
1380 (Context, Record[1], getMDString(Record[2]),
1381 Record[3], Record[4], Record[5])),
1385 case bitc::METADATA_STRING: {
1386 std::string String(Record.begin(), Record.end());
1387 llvm::UpgradeMDStringConstant(String);
1388 Metadata *MD = MDString::get(Context, String);
1389 MDValueList.AssignValue(MD, NextMDValueNo++);
1392 case bitc::METADATA_KIND: {
1393 if (Record.size() < 2)
1394 return Error("Invalid record");
1396 unsigned Kind = Record[0];
1397 SmallString<8> Name(Record.begin()+1, Record.end());
1399 unsigned NewKind = TheModule->getMDKindID(Name.str());
1400 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1401 return Error("Conflicting METADATA_KIND records");
1406 #undef GET_OR_DISTINCT
1409 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1410 /// the LSB for dense VBR encoding.
1411 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1416 // There is no such thing as -0 with integers. "-0" really means MININT.
1420 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1421 /// values and aliases that we can.
1422 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1423 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1424 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1425 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1426 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1428 GlobalInitWorklist.swap(GlobalInits);
1429 AliasInitWorklist.swap(AliasInits);
1430 FunctionPrefixWorklist.swap(FunctionPrefixes);
1431 FunctionPrologueWorklist.swap(FunctionPrologues);
1433 while (!GlobalInitWorklist.empty()) {
1434 unsigned ValID = GlobalInitWorklist.back().second;
1435 if (ValID >= ValueList.size()) {
1436 // Not ready to resolve this yet, it requires something later in the file.
1437 GlobalInits.push_back(GlobalInitWorklist.back());
1439 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1440 GlobalInitWorklist.back().first->setInitializer(C);
1442 return Error("Expected a constant");
1444 GlobalInitWorklist.pop_back();
1447 while (!AliasInitWorklist.empty()) {
1448 unsigned ValID = AliasInitWorklist.back().second;
1449 if (ValID >= ValueList.size()) {
1450 AliasInits.push_back(AliasInitWorklist.back());
1452 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1453 AliasInitWorklist.back().first->setAliasee(C);
1455 return Error("Expected a constant");
1457 AliasInitWorklist.pop_back();
1460 while (!FunctionPrefixWorklist.empty()) {
1461 unsigned ValID = FunctionPrefixWorklist.back().second;
1462 if (ValID >= ValueList.size()) {
1463 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1465 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1466 FunctionPrefixWorklist.back().first->setPrefixData(C);
1468 return Error("Expected a constant");
1470 FunctionPrefixWorklist.pop_back();
1473 while (!FunctionPrologueWorklist.empty()) {
1474 unsigned ValID = FunctionPrologueWorklist.back().second;
1475 if (ValID >= ValueList.size()) {
1476 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1478 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1479 FunctionPrologueWorklist.back().first->setPrologueData(C);
1481 return Error("Expected a constant");
1483 FunctionPrologueWorklist.pop_back();
1486 return std::error_code();
1489 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1490 SmallVector<uint64_t, 8> Words(Vals.size());
1491 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1492 BitcodeReader::decodeSignRotatedValue);
1494 return APInt(TypeBits, Words);
1497 std::error_code BitcodeReader::ParseConstants() {
1498 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1499 return Error("Invalid record");
1501 SmallVector<uint64_t, 64> Record;
1503 // Read all the records for this value table.
1504 Type *CurTy = Type::getInt32Ty(Context);
1505 unsigned NextCstNo = ValueList.size();
1507 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1509 switch (Entry.Kind) {
1510 case BitstreamEntry::SubBlock: // Handled for us already.
1511 case BitstreamEntry::Error:
1512 return Error("Malformed block");
1513 case BitstreamEntry::EndBlock:
1514 if (NextCstNo != ValueList.size())
1515 return Error("Invalid ronstant reference");
1517 // Once all the constants have been read, go through and resolve forward
1519 ValueList.ResolveConstantForwardRefs();
1520 return std::error_code();
1521 case BitstreamEntry::Record:
1522 // The interesting case.
1529 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1531 default: // Default behavior: unknown constant
1532 case bitc::CST_CODE_UNDEF: // UNDEF
1533 V = UndefValue::get(CurTy);
1535 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1537 return Error("Invalid record");
1538 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1539 return Error("Invalid record");
1540 CurTy = TypeList[Record[0]];
1541 continue; // Skip the ValueList manipulation.
1542 case bitc::CST_CODE_NULL: // NULL
1543 V = Constant::getNullValue(CurTy);
1545 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1546 if (!CurTy->isIntegerTy() || Record.empty())
1547 return Error("Invalid record");
1548 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1550 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1551 if (!CurTy->isIntegerTy() || Record.empty())
1552 return Error("Invalid record");
1554 APInt VInt = ReadWideAPInt(Record,
1555 cast<IntegerType>(CurTy)->getBitWidth());
1556 V = ConstantInt::get(Context, VInt);
1560 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1562 return Error("Invalid record");
1563 if (CurTy->isHalfTy())
1564 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1565 APInt(16, (uint16_t)Record[0])));
1566 else if (CurTy->isFloatTy())
1567 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1568 APInt(32, (uint32_t)Record[0])));
1569 else if (CurTy->isDoubleTy())
1570 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1571 APInt(64, Record[0])));
1572 else if (CurTy->isX86_FP80Ty()) {
1573 // Bits are not stored the same way as a normal i80 APInt, compensate.
1574 uint64_t Rearrange[2];
1575 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1576 Rearrange[1] = Record[0] >> 48;
1577 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1578 APInt(80, Rearrange)));
1579 } else if (CurTy->isFP128Ty())
1580 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1581 APInt(128, Record)));
1582 else if (CurTy->isPPC_FP128Ty())
1583 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1584 APInt(128, Record)));
1586 V = UndefValue::get(CurTy);
1590 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1592 return Error("Invalid record");
1594 unsigned Size = Record.size();
1595 SmallVector<Constant*, 16> Elts;
1597 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1598 for (unsigned i = 0; i != Size; ++i)
1599 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1600 STy->getElementType(i)));
1601 V = ConstantStruct::get(STy, Elts);
1602 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1603 Type *EltTy = ATy->getElementType();
1604 for (unsigned i = 0; i != Size; ++i)
1605 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1606 V = ConstantArray::get(ATy, Elts);
1607 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1608 Type *EltTy = VTy->getElementType();
1609 for (unsigned i = 0; i != Size; ++i)
1610 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1611 V = ConstantVector::get(Elts);
1613 V = UndefValue::get(CurTy);
1617 case bitc::CST_CODE_STRING: // STRING: [values]
1618 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1620 return Error("Invalid record");
1622 SmallString<16> Elts(Record.begin(), Record.end());
1623 V = ConstantDataArray::getString(Context, Elts,
1624 BitCode == bitc::CST_CODE_CSTRING);
1627 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1629 return Error("Invalid record");
1631 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1632 unsigned Size = Record.size();
1634 if (EltTy->isIntegerTy(8)) {
1635 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1636 if (isa<VectorType>(CurTy))
1637 V = ConstantDataVector::get(Context, Elts);
1639 V = ConstantDataArray::get(Context, Elts);
1640 } else if (EltTy->isIntegerTy(16)) {
1641 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1642 if (isa<VectorType>(CurTy))
1643 V = ConstantDataVector::get(Context, Elts);
1645 V = ConstantDataArray::get(Context, Elts);
1646 } else if (EltTy->isIntegerTy(32)) {
1647 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1648 if (isa<VectorType>(CurTy))
1649 V = ConstantDataVector::get(Context, Elts);
1651 V = ConstantDataArray::get(Context, Elts);
1652 } else if (EltTy->isIntegerTy(64)) {
1653 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1654 if (isa<VectorType>(CurTy))
1655 V = ConstantDataVector::get(Context, Elts);
1657 V = ConstantDataArray::get(Context, Elts);
1658 } else if (EltTy->isFloatTy()) {
1659 SmallVector<float, 16> Elts(Size);
1660 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1661 if (isa<VectorType>(CurTy))
1662 V = ConstantDataVector::get(Context, Elts);
1664 V = ConstantDataArray::get(Context, Elts);
1665 } else if (EltTy->isDoubleTy()) {
1666 SmallVector<double, 16> Elts(Size);
1667 std::transform(Record.begin(), Record.end(), Elts.begin(),
1669 if (isa<VectorType>(CurTy))
1670 V = ConstantDataVector::get(Context, Elts);
1672 V = ConstantDataArray::get(Context, Elts);
1674 return Error("Invalid type for value");
1679 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1680 if (Record.size() < 3)
1681 return Error("Invalid record");
1682 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1684 V = UndefValue::get(CurTy); // Unknown binop.
1686 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1687 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1689 if (Record.size() >= 4) {
1690 if (Opc == Instruction::Add ||
1691 Opc == Instruction::Sub ||
1692 Opc == Instruction::Mul ||
1693 Opc == Instruction::Shl) {
1694 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1695 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1696 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1697 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1698 } else if (Opc == Instruction::SDiv ||
1699 Opc == Instruction::UDiv ||
1700 Opc == Instruction::LShr ||
1701 Opc == Instruction::AShr) {
1702 if (Record[3] & (1 << bitc::PEO_EXACT))
1703 Flags |= SDivOperator::IsExact;
1706 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1710 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1711 if (Record.size() < 3)
1712 return Error("Invalid record");
1713 int Opc = GetDecodedCastOpcode(Record[0]);
1715 V = UndefValue::get(CurTy); // Unknown cast.
1717 Type *OpTy = getTypeByID(Record[1]);
1719 return Error("Invalid record");
1720 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1721 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1722 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1726 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1727 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1728 if (Record.size() & 1)
1729 return Error("Invalid record");
1730 SmallVector<Constant*, 16> Elts;
1731 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1732 Type *ElTy = getTypeByID(Record[i]);
1734 return Error("Invalid record");
1735 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1737 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1738 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1740 bitc::CST_CODE_CE_INBOUNDS_GEP);
1743 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1744 if (Record.size() < 3)
1745 return Error("Invalid record");
1747 Type *SelectorTy = Type::getInt1Ty(Context);
1749 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1750 // vector. Otherwise, it must be a single bit.
1751 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1752 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1753 VTy->getNumElements());
1755 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1757 ValueList.getConstantFwdRef(Record[1],CurTy),
1758 ValueList.getConstantFwdRef(Record[2],CurTy));
1761 case bitc::CST_CODE_CE_EXTRACTELT
1762 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1763 if (Record.size() < 3)
1764 return Error("Invalid record");
1766 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1768 return Error("Invalid record");
1769 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1770 Constant *Op1 = nullptr;
1771 if (Record.size() == 4) {
1772 Type *IdxTy = getTypeByID(Record[2]);
1774 return Error("Invalid record");
1775 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1776 } else // TODO: Remove with llvm 4.0
1777 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1779 return Error("Invalid record");
1780 V = ConstantExpr::getExtractElement(Op0, Op1);
1783 case bitc::CST_CODE_CE_INSERTELT
1784 : { // CE_INSERTELT: [opval, opval, opty, opval]
1785 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1786 if (Record.size() < 3 || !OpTy)
1787 return Error("Invalid record");
1788 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1789 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1790 OpTy->getElementType());
1791 Constant *Op2 = nullptr;
1792 if (Record.size() == 4) {
1793 Type *IdxTy = getTypeByID(Record[2]);
1795 return Error("Invalid record");
1796 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1797 } else // TODO: Remove with llvm 4.0
1798 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1800 return Error("Invalid record");
1801 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1804 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1805 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1806 if (Record.size() < 3 || !OpTy)
1807 return Error("Invalid record");
1808 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1809 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1810 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1811 OpTy->getNumElements());
1812 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1813 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1816 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1817 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1819 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1820 if (Record.size() < 4 || !RTy || !OpTy)
1821 return Error("Invalid record");
1822 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1823 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1824 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1825 RTy->getNumElements());
1826 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1827 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1830 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1831 if (Record.size() < 4)
1832 return Error("Invalid record");
1833 Type *OpTy = getTypeByID(Record[0]);
1835 return Error("Invalid record");
1836 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1837 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1839 if (OpTy->isFPOrFPVectorTy())
1840 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1842 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1845 // This maintains backward compatibility, pre-asm dialect keywords.
1846 // FIXME: Remove with the 4.0 release.
1847 case bitc::CST_CODE_INLINEASM_OLD: {
1848 if (Record.size() < 2)
1849 return Error("Invalid record");
1850 std::string AsmStr, ConstrStr;
1851 bool HasSideEffects = Record[0] & 1;
1852 bool IsAlignStack = Record[0] >> 1;
1853 unsigned AsmStrSize = Record[1];
1854 if (2+AsmStrSize >= Record.size())
1855 return Error("Invalid record");
1856 unsigned ConstStrSize = Record[2+AsmStrSize];
1857 if (3+AsmStrSize+ConstStrSize > Record.size())
1858 return Error("Invalid record");
1860 for (unsigned i = 0; i != AsmStrSize; ++i)
1861 AsmStr += (char)Record[2+i];
1862 for (unsigned i = 0; i != ConstStrSize; ++i)
1863 ConstrStr += (char)Record[3+AsmStrSize+i];
1864 PointerType *PTy = cast<PointerType>(CurTy);
1865 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1866 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1869 // This version adds support for the asm dialect keywords (e.g.,
1871 case bitc::CST_CODE_INLINEASM: {
1872 if (Record.size() < 2)
1873 return Error("Invalid record");
1874 std::string AsmStr, ConstrStr;
1875 bool HasSideEffects = Record[0] & 1;
1876 bool IsAlignStack = (Record[0] >> 1) & 1;
1877 unsigned AsmDialect = Record[0] >> 2;
1878 unsigned AsmStrSize = Record[1];
1879 if (2+AsmStrSize >= Record.size())
1880 return Error("Invalid record");
1881 unsigned ConstStrSize = Record[2+AsmStrSize];
1882 if (3+AsmStrSize+ConstStrSize > Record.size())
1883 return Error("Invalid record");
1885 for (unsigned i = 0; i != AsmStrSize; ++i)
1886 AsmStr += (char)Record[2+i];
1887 for (unsigned i = 0; i != ConstStrSize; ++i)
1888 ConstrStr += (char)Record[3+AsmStrSize+i];
1889 PointerType *PTy = cast<PointerType>(CurTy);
1890 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1891 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1892 InlineAsm::AsmDialect(AsmDialect));
1895 case bitc::CST_CODE_BLOCKADDRESS:{
1896 if (Record.size() < 3)
1897 return Error("Invalid record");
1898 Type *FnTy = getTypeByID(Record[0]);
1900 return Error("Invalid record");
1902 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1904 return Error("Invalid record");
1906 // Don't let Fn get dematerialized.
1907 BlockAddressesTaken.insert(Fn);
1909 // If the function is already parsed we can insert the block address right
1912 unsigned BBID = Record[2];
1914 // Invalid reference to entry block.
1915 return Error("Invalid ID");
1917 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1918 for (size_t I = 0, E = BBID; I != E; ++I) {
1920 return Error("Invalid ID");
1925 // Otherwise insert a placeholder and remember it so it can be inserted
1926 // when the function is parsed.
1927 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1929 BasicBlockFwdRefQueue.push_back(Fn);
1930 if (FwdBBs.size() < BBID + 1)
1931 FwdBBs.resize(BBID + 1);
1933 FwdBBs[BBID] = BasicBlock::Create(Context);
1936 V = BlockAddress::get(Fn, BB);
1941 ValueList.AssignValue(V, NextCstNo);
1946 std::error_code BitcodeReader::ParseUseLists() {
1947 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1948 return Error("Invalid record");
1950 // Read all the records.
1951 SmallVector<uint64_t, 64> Record;
1953 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1955 switch (Entry.Kind) {
1956 case BitstreamEntry::SubBlock: // Handled for us already.
1957 case BitstreamEntry::Error:
1958 return Error("Malformed block");
1959 case BitstreamEntry::EndBlock:
1960 return std::error_code();
1961 case BitstreamEntry::Record:
1962 // The interesting case.
1966 // Read a use list record.
1969 switch (Stream.readRecord(Entry.ID, Record)) {
1970 default: // Default behavior: unknown type.
1972 case bitc::USELIST_CODE_BB:
1975 case bitc::USELIST_CODE_DEFAULT: {
1976 unsigned RecordLength = Record.size();
1977 if (RecordLength < 3)
1978 // Records should have at least an ID and two indexes.
1979 return Error("Invalid record");
1980 unsigned ID = Record.back();
1985 assert(ID < FunctionBBs.size() && "Basic block not found");
1986 V = FunctionBBs[ID];
1989 unsigned NumUses = 0;
1990 SmallDenseMap<const Use *, unsigned, 16> Order;
1991 for (const Use &U : V->uses()) {
1992 if (++NumUses > Record.size())
1994 Order[&U] = Record[NumUses - 1];
1996 if (Order.size() != Record.size() || NumUses > Record.size())
1997 // Mismatches can happen if the functions are being materialized lazily
1998 // (out-of-order), or a value has been upgraded.
2001 V->sortUseList([&](const Use &L, const Use &R) {
2002 return Order.lookup(&L) < Order.lookup(&R);
2010 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2011 /// remember where it is and then skip it. This lets us lazily deserialize the
2013 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2014 // Get the function we are talking about.
2015 if (FunctionsWithBodies.empty())
2016 return Error("Insufficient function protos");
2018 Function *Fn = FunctionsWithBodies.back();
2019 FunctionsWithBodies.pop_back();
2021 // Save the current stream state.
2022 uint64_t CurBit = Stream.GetCurrentBitNo();
2023 DeferredFunctionInfo[Fn] = CurBit;
2025 // Skip over the function block for now.
2026 if (Stream.SkipBlock())
2027 return Error("Invalid record");
2028 return std::error_code();
2031 std::error_code BitcodeReader::GlobalCleanup() {
2032 // Patch the initializers for globals and aliases up.
2033 ResolveGlobalAndAliasInits();
2034 if (!GlobalInits.empty() || !AliasInits.empty())
2035 return Error("Malformed global initializer set");
2037 // Look for intrinsic functions which need to be upgraded at some point
2038 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2041 if (UpgradeIntrinsicFunction(FI, NewFn))
2042 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2045 // Look for global variables which need to be renamed.
2046 for (Module::global_iterator
2047 GI = TheModule->global_begin(), GE = TheModule->global_end();
2049 GlobalVariable *GV = GI++;
2050 UpgradeGlobalVariable(GV);
2053 // Force deallocation of memory for these vectors to favor the client that
2054 // want lazy deserialization.
2055 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2056 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2057 return std::error_code();
2060 std::error_code BitcodeReader::ParseModule(bool Resume) {
2062 Stream.JumpToBit(NextUnreadBit);
2063 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2064 return Error("Invalid record");
2066 SmallVector<uint64_t, 64> Record;
2067 std::vector<std::string> SectionTable;
2068 std::vector<std::string> GCTable;
2070 // Read all the records for this module.
2072 BitstreamEntry Entry = Stream.advance();
2074 switch (Entry.Kind) {
2075 case BitstreamEntry::Error:
2076 return Error("Malformed block");
2077 case BitstreamEntry::EndBlock:
2078 return GlobalCleanup();
2080 case BitstreamEntry::SubBlock:
2082 default: // Skip unknown content.
2083 if (Stream.SkipBlock())
2084 return Error("Invalid record");
2086 case bitc::BLOCKINFO_BLOCK_ID:
2087 if (Stream.ReadBlockInfoBlock())
2088 return Error("Malformed block");
2090 case bitc::PARAMATTR_BLOCK_ID:
2091 if (std::error_code EC = ParseAttributeBlock())
2094 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2095 if (std::error_code EC = ParseAttributeGroupBlock())
2098 case bitc::TYPE_BLOCK_ID_NEW:
2099 if (std::error_code EC = ParseTypeTable())
2102 case bitc::VALUE_SYMTAB_BLOCK_ID:
2103 if (std::error_code EC = ParseValueSymbolTable())
2105 SeenValueSymbolTable = true;
2107 case bitc::CONSTANTS_BLOCK_ID:
2108 if (std::error_code EC = ParseConstants())
2110 if (std::error_code EC = ResolveGlobalAndAliasInits())
2113 case bitc::METADATA_BLOCK_ID:
2114 if (std::error_code EC = ParseMetadata())
2117 case bitc::FUNCTION_BLOCK_ID:
2118 // If this is the first function body we've seen, reverse the
2119 // FunctionsWithBodies list.
2120 if (!SeenFirstFunctionBody) {
2121 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2122 if (std::error_code EC = GlobalCleanup())
2124 SeenFirstFunctionBody = true;
2127 if (std::error_code EC = RememberAndSkipFunctionBody())
2129 // For streaming bitcode, suspend parsing when we reach the function
2130 // bodies. Subsequent materialization calls will resume it when
2131 // necessary. For streaming, the function bodies must be at the end of
2132 // the bitcode. If the bitcode file is old, the symbol table will be
2133 // at the end instead and will not have been seen yet. In this case,
2134 // just finish the parse now.
2135 if (LazyStreamer && SeenValueSymbolTable) {
2136 NextUnreadBit = Stream.GetCurrentBitNo();
2137 return std::error_code();
2140 case bitc::USELIST_BLOCK_ID:
2141 if (std::error_code EC = ParseUseLists())
2147 case BitstreamEntry::Record:
2148 // The interesting case.
2154 switch (Stream.readRecord(Entry.ID, Record)) {
2155 default: break; // Default behavior, ignore unknown content.
2156 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2157 if (Record.size() < 1)
2158 return Error("Invalid record");
2159 // Only version #0 and #1 are supported so far.
2160 unsigned module_version = Record[0];
2161 switch (module_version) {
2163 return Error("Invalid value");
2165 UseRelativeIDs = false;
2168 UseRelativeIDs = true;
2173 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2175 if (ConvertToString(Record, 0, S))
2176 return Error("Invalid record");
2177 TheModule->setTargetTriple(S);
2180 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2182 if (ConvertToString(Record, 0, S))
2183 return Error("Invalid record");
2184 TheModule->setDataLayout(S);
2187 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2189 if (ConvertToString(Record, 0, S))
2190 return Error("Invalid record");
2191 TheModule->setModuleInlineAsm(S);
2194 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2195 // FIXME: Remove in 4.0.
2197 if (ConvertToString(Record, 0, S))
2198 return Error("Invalid record");
2202 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2204 if (ConvertToString(Record, 0, S))
2205 return Error("Invalid record");
2206 SectionTable.push_back(S);
2209 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2211 if (ConvertToString(Record, 0, S))
2212 return Error("Invalid record");
2213 GCTable.push_back(S);
2216 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2217 if (Record.size() < 2)
2218 return Error("Invalid record");
2219 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2220 unsigned ComdatNameSize = Record[1];
2221 std::string ComdatName;
2222 ComdatName.reserve(ComdatNameSize);
2223 for (unsigned i = 0; i != ComdatNameSize; ++i)
2224 ComdatName += (char)Record[2 + i];
2225 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2226 C->setSelectionKind(SK);
2227 ComdatList.push_back(C);
2230 // GLOBALVAR: [pointer type, isconst, initid,
2231 // linkage, alignment, section, visibility, threadlocal,
2232 // unnamed_addr, externally_initialized, dllstorageclass,
2234 case bitc::MODULE_CODE_GLOBALVAR: {
2235 if (Record.size() < 6)
2236 return Error("Invalid record");
2237 Type *Ty = getTypeByID(Record[0]);
2239 return Error("Invalid record");
2240 if (!Ty->isPointerTy())
2241 return Error("Invalid type for value");
2242 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2243 Ty = cast<PointerType>(Ty)->getElementType();
2245 bool isConstant = Record[1];
2246 uint64_t RawLinkage = Record[3];
2247 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2248 unsigned Alignment = (1 << Record[4]) >> 1;
2249 std::string Section;
2251 if (Record[5]-1 >= SectionTable.size())
2252 return Error("Invalid ID");
2253 Section = SectionTable[Record[5]-1];
2255 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2256 // Local linkage must have default visibility.
2257 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2258 // FIXME: Change to an error if non-default in 4.0.
2259 Visibility = GetDecodedVisibility(Record[6]);
2261 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2262 if (Record.size() > 7)
2263 TLM = GetDecodedThreadLocalMode(Record[7]);
2265 bool UnnamedAddr = false;
2266 if (Record.size() > 8)
2267 UnnamedAddr = Record[8];
2269 bool ExternallyInitialized = false;
2270 if (Record.size() > 9)
2271 ExternallyInitialized = Record[9];
2273 GlobalVariable *NewGV =
2274 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2275 TLM, AddressSpace, ExternallyInitialized);
2276 NewGV->setAlignment(Alignment);
2277 if (!Section.empty())
2278 NewGV->setSection(Section);
2279 NewGV->setVisibility(Visibility);
2280 NewGV->setUnnamedAddr(UnnamedAddr);
2282 if (Record.size() > 10)
2283 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2285 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2287 ValueList.push_back(NewGV);
2289 // Remember which value to use for the global initializer.
2290 if (unsigned InitID = Record[2])
2291 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2293 if (Record.size() > 11) {
2294 if (unsigned ComdatID = Record[11]) {
2295 assert(ComdatID <= ComdatList.size());
2296 NewGV->setComdat(ComdatList[ComdatID - 1]);
2298 } else if (hasImplicitComdat(RawLinkage)) {
2299 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2303 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2304 // alignment, section, visibility, gc, unnamed_addr,
2305 // prologuedata, dllstorageclass, comdat, prefixdata]
2306 case bitc::MODULE_CODE_FUNCTION: {
2307 if (Record.size() < 8)
2308 return Error("Invalid record");
2309 Type *Ty = getTypeByID(Record[0]);
2311 return Error("Invalid record");
2312 if (!Ty->isPointerTy())
2313 return Error("Invalid type for value");
2315 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2317 return Error("Invalid type for value");
2319 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2322 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2323 bool isProto = Record[2];
2324 uint64_t RawLinkage = Record[3];
2325 Func->setLinkage(getDecodedLinkage(RawLinkage));
2326 Func->setAttributes(getAttributes(Record[4]));
2328 Func->setAlignment((1 << Record[5]) >> 1);
2330 if (Record[6]-1 >= SectionTable.size())
2331 return Error("Invalid ID");
2332 Func->setSection(SectionTable[Record[6]-1]);
2334 // Local linkage must have default visibility.
2335 if (!Func->hasLocalLinkage())
2336 // FIXME: Change to an error if non-default in 4.0.
2337 Func->setVisibility(GetDecodedVisibility(Record[7]));
2338 if (Record.size() > 8 && Record[8]) {
2339 if (Record[8]-1 > GCTable.size())
2340 return Error("Invalid ID");
2341 Func->setGC(GCTable[Record[8]-1].c_str());
2343 bool UnnamedAddr = false;
2344 if (Record.size() > 9)
2345 UnnamedAddr = Record[9];
2346 Func->setUnnamedAddr(UnnamedAddr);
2347 if (Record.size() > 10 && Record[10] != 0)
2348 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2350 if (Record.size() > 11)
2351 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2353 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2355 if (Record.size() > 12) {
2356 if (unsigned ComdatID = Record[12]) {
2357 assert(ComdatID <= ComdatList.size());
2358 Func->setComdat(ComdatList[ComdatID - 1]);
2360 } else if (hasImplicitComdat(RawLinkage)) {
2361 Func->setComdat(reinterpret_cast<Comdat *>(1));
2364 if (Record.size() > 13 && Record[13] != 0)
2365 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2367 ValueList.push_back(Func);
2369 // If this is a function with a body, remember the prototype we are
2370 // creating now, so that we can match up the body with them later.
2372 Func->setIsMaterializable(true);
2373 FunctionsWithBodies.push_back(Func);
2375 DeferredFunctionInfo[Func] = 0;
2379 // ALIAS: [alias type, aliasee val#, linkage]
2380 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2381 case bitc::MODULE_CODE_ALIAS: {
2382 if (Record.size() < 3)
2383 return Error("Invalid record");
2384 Type *Ty = getTypeByID(Record[0]);
2386 return Error("Invalid record");
2387 auto *PTy = dyn_cast<PointerType>(Ty);
2389 return Error("Invalid type for value");
2392 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2393 getDecodedLinkage(Record[2]), "", TheModule);
2394 // Old bitcode files didn't have visibility field.
2395 // Local linkage must have default visibility.
2396 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2397 // FIXME: Change to an error if non-default in 4.0.
2398 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2399 if (Record.size() > 4)
2400 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2402 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2403 if (Record.size() > 5)
2404 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2405 if (Record.size() > 6)
2406 NewGA->setUnnamedAddr(Record[6]);
2407 ValueList.push_back(NewGA);
2408 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2411 /// MODULE_CODE_PURGEVALS: [numvals]
2412 case bitc::MODULE_CODE_PURGEVALS:
2413 // Trim down the value list to the specified size.
2414 if (Record.size() < 1 || Record[0] > ValueList.size())
2415 return Error("Invalid record");
2416 ValueList.shrinkTo(Record[0]);
2423 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2424 TheModule = nullptr;
2426 if (std::error_code EC = InitStream())
2429 // Sniff for the signature.
2430 if (Stream.Read(8) != 'B' ||
2431 Stream.Read(8) != 'C' ||
2432 Stream.Read(4) != 0x0 ||
2433 Stream.Read(4) != 0xC ||
2434 Stream.Read(4) != 0xE ||
2435 Stream.Read(4) != 0xD)
2436 return Error("Invalid bitcode signature");
2438 // We expect a number of well-defined blocks, though we don't necessarily
2439 // need to understand them all.
2441 if (Stream.AtEndOfStream())
2442 return std::error_code();
2444 BitstreamEntry Entry =
2445 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2447 switch (Entry.Kind) {
2448 case BitstreamEntry::Error:
2449 return Error("Malformed block");
2450 case BitstreamEntry::EndBlock:
2451 return std::error_code();
2453 case BitstreamEntry::SubBlock:
2455 case bitc::BLOCKINFO_BLOCK_ID:
2456 if (Stream.ReadBlockInfoBlock())
2457 return Error("Malformed block");
2459 case bitc::MODULE_BLOCK_ID:
2460 // Reject multiple MODULE_BLOCK's in a single bitstream.
2462 return Error("Invalid multiple blocks");
2464 if (std::error_code EC = ParseModule(false))
2467 return std::error_code();
2470 if (Stream.SkipBlock())
2471 return Error("Invalid record");
2475 case BitstreamEntry::Record:
2476 // There should be no records in the top-level of blocks.
2478 // The ranlib in Xcode 4 will align archive members by appending newlines
2479 // to the end of them. If this file size is a multiple of 4 but not 8, we
2480 // have to read and ignore these final 4 bytes :-(
2481 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2482 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2483 Stream.AtEndOfStream())
2484 return std::error_code();
2486 return Error("Invalid record");
2491 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2492 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2493 return Error("Invalid record");
2495 SmallVector<uint64_t, 64> Record;
2498 // Read all the records for this module.
2500 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2502 switch (Entry.Kind) {
2503 case BitstreamEntry::SubBlock: // Handled for us already.
2504 case BitstreamEntry::Error:
2505 return Error("Malformed block");
2506 case BitstreamEntry::EndBlock:
2508 case BitstreamEntry::Record:
2509 // The interesting case.
2514 switch (Stream.readRecord(Entry.ID, Record)) {
2515 default: break; // Default behavior, ignore unknown content.
2516 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2518 if (ConvertToString(Record, 0, S))
2519 return Error("Invalid record");
2526 llvm_unreachable("Exit infinite loop");
2529 ErrorOr<std::string> BitcodeReader::parseTriple() {
2530 if (std::error_code EC = InitStream())
2533 // Sniff for the signature.
2534 if (Stream.Read(8) != 'B' ||
2535 Stream.Read(8) != 'C' ||
2536 Stream.Read(4) != 0x0 ||
2537 Stream.Read(4) != 0xC ||
2538 Stream.Read(4) != 0xE ||
2539 Stream.Read(4) != 0xD)
2540 return Error("Invalid bitcode signature");
2542 // We expect a number of well-defined blocks, though we don't necessarily
2543 // need to understand them all.
2545 BitstreamEntry Entry = Stream.advance();
2547 switch (Entry.Kind) {
2548 case BitstreamEntry::Error:
2549 return Error("Malformed block");
2550 case BitstreamEntry::EndBlock:
2551 return std::error_code();
2553 case BitstreamEntry::SubBlock:
2554 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2555 return parseModuleTriple();
2557 // Ignore other sub-blocks.
2558 if (Stream.SkipBlock())
2559 return Error("Malformed block");
2562 case BitstreamEntry::Record:
2563 Stream.skipRecord(Entry.ID);
2569 /// ParseMetadataAttachment - Parse metadata attachments.
2570 std::error_code BitcodeReader::ParseMetadataAttachment() {
2571 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2572 return Error("Invalid record");
2574 SmallVector<uint64_t, 64> Record;
2576 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2578 switch (Entry.Kind) {
2579 case BitstreamEntry::SubBlock: // Handled for us already.
2580 case BitstreamEntry::Error:
2581 return Error("Malformed block");
2582 case BitstreamEntry::EndBlock:
2583 return std::error_code();
2584 case BitstreamEntry::Record:
2585 // The interesting case.
2589 // Read a metadata attachment record.
2591 switch (Stream.readRecord(Entry.ID, Record)) {
2592 default: // Default behavior: ignore.
2594 case bitc::METADATA_ATTACHMENT: {
2595 unsigned RecordLength = Record.size();
2596 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2597 return Error("Invalid record");
2598 Instruction *Inst = InstructionList[Record[0]];
2599 for (unsigned i = 1; i != RecordLength; i = i+2) {
2600 unsigned Kind = Record[i];
2601 DenseMap<unsigned, unsigned>::iterator I =
2602 MDKindMap.find(Kind);
2603 if (I == MDKindMap.end())
2604 return Error("Invalid ID");
2605 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2606 if (isa<LocalAsMetadata>(Node))
2607 // Drop the attachment. This used to be legal, but there's no
2610 Inst->setMetadata(I->second, cast<MDNode>(Node));
2611 if (I->second == LLVMContext::MD_tbaa)
2612 InstsWithTBAATag.push_back(Inst);
2620 /// ParseFunctionBody - Lazily parse the specified function body block.
2621 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2622 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2623 return Error("Invalid record");
2625 InstructionList.clear();
2626 unsigned ModuleValueListSize = ValueList.size();
2627 unsigned ModuleMDValueListSize = MDValueList.size();
2629 // Add all the function arguments to the value table.
2630 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2631 ValueList.push_back(I);
2633 unsigned NextValueNo = ValueList.size();
2634 BasicBlock *CurBB = nullptr;
2635 unsigned CurBBNo = 0;
2638 auto getLastInstruction = [&]() -> Instruction * {
2639 if (CurBB && !CurBB->empty())
2640 return &CurBB->back();
2641 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2642 !FunctionBBs[CurBBNo - 1]->empty())
2643 return &FunctionBBs[CurBBNo - 1]->back();
2647 // Read all the records.
2648 SmallVector<uint64_t, 64> Record;
2650 BitstreamEntry Entry = Stream.advance();
2652 switch (Entry.Kind) {
2653 case BitstreamEntry::Error:
2654 return Error("Malformed block");
2655 case BitstreamEntry::EndBlock:
2656 goto OutOfRecordLoop;
2658 case BitstreamEntry::SubBlock:
2660 default: // Skip unknown content.
2661 if (Stream.SkipBlock())
2662 return Error("Invalid record");
2664 case bitc::CONSTANTS_BLOCK_ID:
2665 if (std::error_code EC = ParseConstants())
2667 NextValueNo = ValueList.size();
2669 case bitc::VALUE_SYMTAB_BLOCK_ID:
2670 if (std::error_code EC = ParseValueSymbolTable())
2673 case bitc::METADATA_ATTACHMENT_ID:
2674 if (std::error_code EC = ParseMetadataAttachment())
2677 case bitc::METADATA_BLOCK_ID:
2678 if (std::error_code EC = ParseMetadata())
2681 case bitc::USELIST_BLOCK_ID:
2682 if (std::error_code EC = ParseUseLists())
2688 case BitstreamEntry::Record:
2689 // The interesting case.
2695 Instruction *I = nullptr;
2696 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2698 default: // Default behavior: reject
2699 return Error("Invalid value");
2700 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2701 if (Record.size() < 1 || Record[0] == 0)
2702 return Error("Invalid record");
2703 // Create all the basic blocks for the function.
2704 FunctionBBs.resize(Record[0]);
2706 // See if anything took the address of blocks in this function.
2707 auto BBFRI = BasicBlockFwdRefs.find(F);
2708 if (BBFRI == BasicBlockFwdRefs.end()) {
2709 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2710 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2712 auto &BBRefs = BBFRI->second;
2713 // Check for invalid basic block references.
2714 if (BBRefs.size() > FunctionBBs.size())
2715 return Error("Invalid ID");
2716 assert(!BBRefs.empty() && "Unexpected empty array");
2717 assert(!BBRefs.front() && "Invalid reference to entry block");
2718 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2720 if (I < RE && BBRefs[I]) {
2721 BBRefs[I]->insertInto(F);
2722 FunctionBBs[I] = BBRefs[I];
2724 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2727 // Erase from the table.
2728 BasicBlockFwdRefs.erase(BBFRI);
2731 CurBB = FunctionBBs[0];
2735 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2736 // This record indicates that the last instruction is at the same
2737 // location as the previous instruction with a location.
2738 I = getLastInstruction();
2741 return Error("Invalid record");
2742 I->setDebugLoc(LastLoc);
2746 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2747 I = getLastInstruction();
2748 if (!I || Record.size() < 4)
2749 return Error("Invalid record");
2751 unsigned Line = Record[0], Col = Record[1];
2752 unsigned ScopeID = Record[2], IAID = Record[3];
2754 MDNode *Scope = nullptr, *IA = nullptr;
2755 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2756 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2757 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2758 I->setDebugLoc(LastLoc);
2763 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2766 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2767 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2768 OpNum+1 > Record.size())
2769 return Error("Invalid record");
2771 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2773 return Error("Invalid record");
2774 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2775 InstructionList.push_back(I);
2776 if (OpNum < Record.size()) {
2777 if (Opc == Instruction::Add ||
2778 Opc == Instruction::Sub ||
2779 Opc == Instruction::Mul ||
2780 Opc == Instruction::Shl) {
2781 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2782 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2783 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2784 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2785 } else if (Opc == Instruction::SDiv ||
2786 Opc == Instruction::UDiv ||
2787 Opc == Instruction::LShr ||
2788 Opc == Instruction::AShr) {
2789 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2790 cast<BinaryOperator>(I)->setIsExact(true);
2791 } else if (isa<FPMathOperator>(I)) {
2793 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2794 FMF.setUnsafeAlgebra();
2795 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2797 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2799 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2800 FMF.setNoSignedZeros();
2801 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2802 FMF.setAllowReciprocal();
2804 I->setFastMathFlags(FMF);
2810 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2813 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2814 OpNum+2 != Record.size())
2815 return Error("Invalid record");
2817 Type *ResTy = getTypeByID(Record[OpNum]);
2818 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2819 if (Opc == -1 || !ResTy)
2820 return Error("Invalid record");
2821 Instruction *Temp = nullptr;
2822 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2824 InstructionList.push_back(Temp);
2825 CurBB->getInstList().push_back(Temp);
2828 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2830 InstructionList.push_back(I);
2833 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2834 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2837 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2838 return Error("Invalid record");
2840 SmallVector<Value*, 16> GEPIdx;
2841 while (OpNum != Record.size()) {
2843 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2844 return Error("Invalid record");
2845 GEPIdx.push_back(Op);
2848 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2849 InstructionList.push_back(I);
2850 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2851 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2855 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2856 // EXTRACTVAL: [opty, opval, n x indices]
2859 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2860 return Error("Invalid record");
2862 SmallVector<unsigned, 4> EXTRACTVALIdx;
2863 for (unsigned RecSize = Record.size();
2864 OpNum != RecSize; ++OpNum) {
2865 uint64_t Index = Record[OpNum];
2866 if ((unsigned)Index != Index)
2867 return Error("Invalid value");
2868 EXTRACTVALIdx.push_back((unsigned)Index);
2871 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2872 InstructionList.push_back(I);
2876 case bitc::FUNC_CODE_INST_INSERTVAL: {
2877 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2880 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2881 return Error("Invalid record");
2883 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2884 return Error("Invalid record");
2886 SmallVector<unsigned, 4> INSERTVALIdx;
2887 for (unsigned RecSize = Record.size();
2888 OpNum != RecSize; ++OpNum) {
2889 uint64_t Index = Record[OpNum];
2890 if ((unsigned)Index != Index)
2891 return Error("Invalid value");
2892 INSERTVALIdx.push_back((unsigned)Index);
2895 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2896 InstructionList.push_back(I);
2900 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2901 // obsolete form of select
2902 // handles select i1 ... in old bitcode
2904 Value *TrueVal, *FalseVal, *Cond;
2905 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2906 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2907 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2908 return Error("Invalid record");
2910 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2911 InstructionList.push_back(I);
2915 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2916 // new form of select
2917 // handles select i1 or select [N x i1]
2919 Value *TrueVal, *FalseVal, *Cond;
2920 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2921 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2922 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2923 return Error("Invalid record");
2925 // select condition can be either i1 or [N x i1]
2926 if (VectorType* vector_type =
2927 dyn_cast<VectorType>(Cond->getType())) {
2929 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2930 return Error("Invalid type for value");
2933 if (Cond->getType() != Type::getInt1Ty(Context))
2934 return Error("Invalid type for value");
2937 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2938 InstructionList.push_back(I);
2942 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2945 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2946 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2947 return Error("Invalid record");
2948 I = ExtractElementInst::Create(Vec, Idx);
2949 InstructionList.push_back(I);
2953 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2955 Value *Vec, *Elt, *Idx;
2956 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2957 popValue(Record, OpNum, NextValueNo,
2958 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2959 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2960 return Error("Invalid record");
2961 I = InsertElementInst::Create(Vec, Elt, Idx);
2962 InstructionList.push_back(I);
2966 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2968 Value *Vec1, *Vec2, *Mask;
2969 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2970 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2971 return Error("Invalid record");
2973 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2974 return Error("Invalid record");
2975 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2976 InstructionList.push_back(I);
2980 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2981 // Old form of ICmp/FCmp returning bool
2982 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2983 // both legal on vectors but had different behaviour.
2984 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2985 // FCmp/ICmp returning bool or vector of bool
2989 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2990 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2991 OpNum+1 != Record.size())
2992 return Error("Invalid record");
2994 if (LHS->getType()->isFPOrFPVectorTy())
2995 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2997 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2998 InstructionList.push_back(I);
3002 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3004 unsigned Size = Record.size();
3006 I = ReturnInst::Create(Context);
3007 InstructionList.push_back(I);
3012 Value *Op = nullptr;
3013 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3014 return Error("Invalid record");
3015 if (OpNum != Record.size())
3016 return Error("Invalid record");
3018 I = ReturnInst::Create(Context, Op);
3019 InstructionList.push_back(I);
3022 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3023 if (Record.size() != 1 && Record.size() != 3)
3024 return Error("Invalid record");
3025 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3027 return Error("Invalid record");
3029 if (Record.size() == 1) {
3030 I = BranchInst::Create(TrueDest);
3031 InstructionList.push_back(I);
3034 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3035 Value *Cond = getValue(Record, 2, NextValueNo,
3036 Type::getInt1Ty(Context));
3037 if (!FalseDest || !Cond)
3038 return Error("Invalid record");
3039 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3040 InstructionList.push_back(I);
3044 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3046 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3047 // "New" SwitchInst format with case ranges. The changes to write this
3048 // format were reverted but we still recognize bitcode that uses it.
3049 // Hopefully someday we will have support for case ranges and can use
3050 // this format again.
3052 Type *OpTy = getTypeByID(Record[1]);
3053 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3055 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3056 BasicBlock *Default = getBasicBlock(Record[3]);
3057 if (!OpTy || !Cond || !Default)
3058 return Error("Invalid record");
3060 unsigned NumCases = Record[4];
3062 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3063 InstructionList.push_back(SI);
3065 unsigned CurIdx = 5;
3066 for (unsigned i = 0; i != NumCases; ++i) {
3067 SmallVector<ConstantInt*, 1> CaseVals;
3068 unsigned NumItems = Record[CurIdx++];
3069 for (unsigned ci = 0; ci != NumItems; ++ci) {
3070 bool isSingleNumber = Record[CurIdx++];
3073 unsigned ActiveWords = 1;
3074 if (ValueBitWidth > 64)
3075 ActiveWords = Record[CurIdx++];
3076 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3078 CurIdx += ActiveWords;
3080 if (!isSingleNumber) {
3082 if (ValueBitWidth > 64)
3083 ActiveWords = Record[CurIdx++];
3085 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3087 CurIdx += ActiveWords;
3089 // FIXME: It is not clear whether values in the range should be
3090 // compared as signed or unsigned values. The partially
3091 // implemented changes that used this format in the past used
3092 // unsigned comparisons.
3093 for ( ; Low.ule(High); ++Low)
3094 CaseVals.push_back(ConstantInt::get(Context, Low));
3096 CaseVals.push_back(ConstantInt::get(Context, Low));
3098 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3099 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3100 cve = CaseVals.end(); cvi != cve; ++cvi)
3101 SI->addCase(*cvi, DestBB);
3107 // Old SwitchInst format without case ranges.
3109 if (Record.size() < 3 || (Record.size() & 1) == 0)
3110 return Error("Invalid record");
3111 Type *OpTy = getTypeByID(Record[0]);
3112 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3113 BasicBlock *Default = getBasicBlock(Record[2]);
3114 if (!OpTy || !Cond || !Default)
3115 return Error("Invalid record");
3116 unsigned NumCases = (Record.size()-3)/2;
3117 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3118 InstructionList.push_back(SI);
3119 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3120 ConstantInt *CaseVal =
3121 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3122 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3123 if (!CaseVal || !DestBB) {
3125 return Error("Invalid record");
3127 SI->addCase(CaseVal, DestBB);
3132 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3133 if (Record.size() < 2)
3134 return Error("Invalid record");
3135 Type *OpTy = getTypeByID(Record[0]);
3136 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3137 if (!OpTy || !Address)
3138 return Error("Invalid record");
3139 unsigned NumDests = Record.size()-2;
3140 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3141 InstructionList.push_back(IBI);
3142 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3143 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3144 IBI->addDestination(DestBB);
3147 return Error("Invalid record");
3154 case bitc::FUNC_CODE_INST_INVOKE: {
3155 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3156 if (Record.size() < 4)
3157 return Error("Invalid record");
3158 AttributeSet PAL = getAttributes(Record[0]);
3159 unsigned CCInfo = Record[1];
3160 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3161 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3165 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3166 return Error("Invalid record");
3168 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3169 FunctionType *FTy = !CalleeTy ? nullptr :
3170 dyn_cast<FunctionType>(CalleeTy->getElementType());
3172 // Check that the right number of fixed parameters are here.
3173 if (!FTy || !NormalBB || !UnwindBB ||
3174 Record.size() < OpNum+FTy->getNumParams())
3175 return Error("Invalid record");
3177 SmallVector<Value*, 16> Ops;
3178 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3179 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3180 FTy->getParamType(i)));
3182 return Error("Invalid record");
3185 if (!FTy->isVarArg()) {
3186 if (Record.size() != OpNum)
3187 return Error("Invalid record");
3189 // Read type/value pairs for varargs params.
3190 while (OpNum != Record.size()) {
3192 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3193 return Error("Invalid record");
3198 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3199 InstructionList.push_back(I);
3200 cast<InvokeInst>(I)->setCallingConv(
3201 static_cast<CallingConv::ID>(CCInfo));
3202 cast<InvokeInst>(I)->setAttributes(PAL);
3205 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3207 Value *Val = nullptr;
3208 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3209 return Error("Invalid record");
3210 I = ResumeInst::Create(Val);
3211 InstructionList.push_back(I);
3214 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3215 I = new UnreachableInst(Context);
3216 InstructionList.push_back(I);
3218 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3219 if (Record.size() < 1 || ((Record.size()-1)&1))
3220 return Error("Invalid record");
3221 Type *Ty = getTypeByID(Record[0]);
3223 return Error("Invalid record");
3225 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3226 InstructionList.push_back(PN);
3228 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3230 // With the new function encoding, it is possible that operands have
3231 // negative IDs (for forward references). Use a signed VBR
3232 // representation to keep the encoding small.
3234 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3236 V = getValue(Record, 1+i, NextValueNo, Ty);
3237 BasicBlock *BB = getBasicBlock(Record[2+i]);
3239 return Error("Invalid record");
3240 PN->addIncoming(V, BB);
3246 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3247 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3249 if (Record.size() < 4)
3250 return Error("Invalid record");
3251 Type *Ty = getTypeByID(Record[Idx++]);
3253 return Error("Invalid record");
3254 Value *PersFn = nullptr;
3255 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3256 return Error("Invalid record");
3258 bool IsCleanup = !!Record[Idx++];
3259 unsigned NumClauses = Record[Idx++];
3260 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3261 LP->setCleanup(IsCleanup);
3262 for (unsigned J = 0; J != NumClauses; ++J) {
3263 LandingPadInst::ClauseType CT =
3264 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3267 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3269 return Error("Invalid record");
3272 assert((CT != LandingPadInst::Catch ||
3273 !isa<ArrayType>(Val->getType())) &&
3274 "Catch clause has a invalid type!");
3275 assert((CT != LandingPadInst::Filter ||
3276 isa<ArrayType>(Val->getType())) &&
3277 "Filter clause has invalid type!");
3278 LP->addClause(cast<Constant>(Val));
3282 InstructionList.push_back(I);
3286 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3287 if (Record.size() != 4)
3288 return Error("Invalid record");
3290 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3291 Type *OpTy = getTypeByID(Record[1]);
3292 Value *Size = getFnValueByID(Record[2], OpTy);
3293 unsigned AlignRecord = Record[3];
3294 bool InAlloca = AlignRecord & (1 << 5);
3295 unsigned Align = AlignRecord & ((1 << 5) - 1);
3297 return Error("Invalid record");
3298 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3299 AI->setUsedWithInAlloca(InAlloca);
3301 InstructionList.push_back(I);
3304 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3307 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3308 OpNum+2 != Record.size())
3309 return Error("Invalid record");
3311 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3312 InstructionList.push_back(I);
3315 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3316 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3319 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3320 OpNum+4 != Record.size())
3321 return Error("Invalid record");
3323 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3324 if (Ordering == NotAtomic || Ordering == Release ||
3325 Ordering == AcquireRelease)
3326 return Error("Invalid record");
3327 if (Ordering != NotAtomic && Record[OpNum] == 0)
3328 return Error("Invalid record");
3329 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3331 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3332 Ordering, SynchScope);
3333 InstructionList.push_back(I);
3336 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3339 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3340 popValue(Record, OpNum, NextValueNo,
3341 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3342 OpNum+2 != Record.size())
3343 return Error("Invalid record");
3345 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3346 InstructionList.push_back(I);
3349 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3350 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3353 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3354 popValue(Record, OpNum, NextValueNo,
3355 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3356 OpNum+4 != Record.size())
3357 return Error("Invalid record");
3359 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3360 if (Ordering == NotAtomic || Ordering == Acquire ||
3361 Ordering == AcquireRelease)
3362 return Error("Invalid record");
3363 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3364 if (Ordering != NotAtomic && Record[OpNum] == 0)
3365 return Error("Invalid record");
3367 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3368 Ordering, SynchScope);
3369 InstructionList.push_back(I);
3372 case bitc::FUNC_CODE_INST_CMPXCHG: {
3373 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3374 // failureordering?, isweak?]
3376 Value *Ptr, *Cmp, *New;
3377 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3378 popValue(Record, OpNum, NextValueNo,
3379 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3380 popValue(Record, OpNum, NextValueNo,
3381 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3382 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3383 return Error("Invalid record");
3384 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3385 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3386 return Error("Invalid record");
3387 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3389 AtomicOrdering FailureOrdering;
3390 if (Record.size() < 7)
3392 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3394 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3396 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3398 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3400 if (Record.size() < 8) {
3401 // Before weak cmpxchgs existed, the instruction simply returned the
3402 // value loaded from memory, so bitcode files from that era will be
3403 // expecting the first component of a modern cmpxchg.
3404 CurBB->getInstList().push_back(I);
3405 I = ExtractValueInst::Create(I, 0);
3407 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3410 InstructionList.push_back(I);
3413 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3414 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3417 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3418 popValue(Record, OpNum, NextValueNo,
3419 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3420 OpNum+4 != Record.size())
3421 return Error("Invalid record");
3422 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3423 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3424 Operation > AtomicRMWInst::LAST_BINOP)
3425 return Error("Invalid record");
3426 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3427 if (Ordering == NotAtomic || Ordering == Unordered)
3428 return Error("Invalid record");
3429 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3430 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3431 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3432 InstructionList.push_back(I);
3435 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3436 if (2 != Record.size())
3437 return Error("Invalid record");
3438 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3439 if (Ordering == NotAtomic || Ordering == Unordered ||
3440 Ordering == Monotonic)
3441 return Error("Invalid record");
3442 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3443 I = new FenceInst(Context, Ordering, SynchScope);
3444 InstructionList.push_back(I);
3447 case bitc::FUNC_CODE_INST_CALL: {
3448 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3449 if (Record.size() < 3)
3450 return Error("Invalid record");
3452 AttributeSet PAL = getAttributes(Record[0]);
3453 unsigned CCInfo = Record[1];
3457 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3458 return Error("Invalid record");
3460 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3461 FunctionType *FTy = nullptr;
3462 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3463 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3464 return Error("Invalid record");
3466 SmallVector<Value*, 16> Args;
3467 // Read the fixed params.
3468 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3469 if (FTy->getParamType(i)->isLabelTy())
3470 Args.push_back(getBasicBlock(Record[OpNum]));
3472 Args.push_back(getValue(Record, OpNum, NextValueNo,
3473 FTy->getParamType(i)));
3475 return Error("Invalid record");
3478 // Read type/value pairs for varargs params.
3479 if (!FTy->isVarArg()) {
3480 if (OpNum != Record.size())
3481 return Error("Invalid record");
3483 while (OpNum != Record.size()) {
3485 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3486 return Error("Invalid record");
3491 I = CallInst::Create(Callee, Args);
3492 InstructionList.push_back(I);
3493 cast<CallInst>(I)->setCallingConv(
3494 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3495 CallInst::TailCallKind TCK = CallInst::TCK_None;
3497 TCK = CallInst::TCK_Tail;
3498 if (CCInfo & (1 << 14))
3499 TCK = CallInst::TCK_MustTail;
3500 cast<CallInst>(I)->setTailCallKind(TCK);
3501 cast<CallInst>(I)->setAttributes(PAL);
3504 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3505 if (Record.size() < 3)
3506 return Error("Invalid record");
3507 Type *OpTy = getTypeByID(Record[0]);
3508 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3509 Type *ResTy = getTypeByID(Record[2]);
3510 if (!OpTy || !Op || !ResTy)
3511 return Error("Invalid record");
3512 I = new VAArgInst(Op, ResTy);
3513 InstructionList.push_back(I);
3518 // Add instruction to end of current BB. If there is no current BB, reject
3522 return Error("Invalid instruction with no BB");
3524 CurBB->getInstList().push_back(I);
3526 // If this was a terminator instruction, move to the next block.
3527 if (isa<TerminatorInst>(I)) {
3529 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3532 // Non-void values get registered in the value table for future use.
3533 if (I && !I->getType()->isVoidTy())
3534 ValueList.AssignValue(I, NextValueNo++);
3539 // Check the function list for unresolved values.
3540 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3541 if (!A->getParent()) {
3542 // We found at least one unresolved value. Nuke them all to avoid leaks.
3543 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3544 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3545 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3549 return Error("Never resolved value found in function");
3553 // FIXME: Check for unresolved forward-declared metadata references
3554 // and clean up leaks.
3556 // Trim the value list down to the size it was before we parsed this function.
3557 ValueList.shrinkTo(ModuleValueListSize);
3558 MDValueList.shrinkTo(ModuleMDValueListSize);
3559 std::vector<BasicBlock*>().swap(FunctionBBs);
3560 return std::error_code();
3563 /// Find the function body in the bitcode stream
3564 std::error_code BitcodeReader::FindFunctionInStream(
3566 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3567 while (DeferredFunctionInfoIterator->second == 0) {
3568 if (Stream.AtEndOfStream())
3569 return Error("Could not find function in stream");
3570 // ParseModule will parse the next body in the stream and set its
3571 // position in the DeferredFunctionInfo map.
3572 if (std::error_code EC = ParseModule(true))
3575 return std::error_code();
3578 //===----------------------------------------------------------------------===//
3579 // GVMaterializer implementation
3580 //===----------------------------------------------------------------------===//
3582 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3584 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3585 Function *F = dyn_cast<Function>(GV);
3586 // If it's not a function or is already material, ignore the request.
3587 if (!F || !F->isMaterializable())
3588 return std::error_code();
3590 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3591 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3592 // If its position is recorded as 0, its body is somewhere in the stream
3593 // but we haven't seen it yet.
3594 if (DFII->second == 0 && LazyStreamer)
3595 if (std::error_code EC = FindFunctionInStream(F, DFII))
3598 // Move the bit stream to the saved position of the deferred function body.
3599 Stream.JumpToBit(DFII->second);
3601 if (std::error_code EC = ParseFunctionBody(F))
3603 F->setIsMaterializable(false);
3605 // Upgrade any old intrinsic calls in the function.
3606 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3607 E = UpgradedIntrinsics.end(); I != E; ++I) {
3608 if (I->first != I->second) {
3609 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3611 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3612 UpgradeIntrinsicCall(CI, I->second);
3617 // Bring in any functions that this function forward-referenced via
3619 return materializeForwardReferencedFunctions();
3622 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3623 const Function *F = dyn_cast<Function>(GV);
3624 if (!F || F->isDeclaration())
3627 // Dematerializing F would leave dangling references that wouldn't be
3628 // reconnected on re-materialization.
3629 if (BlockAddressesTaken.count(F))
3632 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3635 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3636 Function *F = dyn_cast<Function>(GV);
3637 // If this function isn't dematerializable, this is a noop.
3638 if (!F || !isDematerializable(F))
3641 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3643 // Just forget the function body, we can remat it later.
3644 F->dropAllReferences();
3645 F->setIsMaterializable(true);
3648 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3649 assert(M == TheModule &&
3650 "Can only Materialize the Module this BitcodeReader is attached to.");
3652 // Promise to materialize all forward references.
3653 WillMaterializeAllForwardRefs = true;
3655 // Iterate over the module, deserializing any functions that are still on
3657 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3659 if (std::error_code EC = materialize(F))
3662 // At this point, if there are any function bodies, the current bit is
3663 // pointing to the END_BLOCK record after them. Now make sure the rest
3664 // of the bits in the module have been read.
3668 // Check that all block address forward references got resolved (as we
3670 if (!BasicBlockFwdRefs.empty())
3671 return Error("Never resolved function from blockaddress");
3673 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3674 // delete the old functions to clean up. We can't do this unless the entire
3675 // module is materialized because there could always be another function body
3676 // with calls to the old function.
3677 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3678 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3679 if (I->first != I->second) {
3680 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3682 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3683 UpgradeIntrinsicCall(CI, I->second);
3685 if (!I->first->use_empty())
3686 I->first->replaceAllUsesWith(I->second);
3687 I->first->eraseFromParent();
3690 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3692 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3693 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3695 UpgradeDebugInfo(*M);
3696 return std::error_code();
3699 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3700 return IdentifiedStructTypes;
3703 std::error_code BitcodeReader::InitStream() {
3705 return InitLazyStream();
3706 return InitStreamFromBuffer();
3709 std::error_code BitcodeReader::InitStreamFromBuffer() {
3710 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3711 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3713 if (Buffer->getBufferSize() & 3)
3714 return Error("Invalid bitcode signature");
3716 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3717 // The magic number is 0x0B17C0DE stored in little endian.
3718 if (isBitcodeWrapper(BufPtr, BufEnd))
3719 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3720 return Error("Invalid bitcode wrapper header");
3722 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3723 Stream.init(&*StreamFile);
3725 return std::error_code();
3728 std::error_code BitcodeReader::InitLazyStream() {
3729 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3731 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3732 StreamingMemoryObject &Bytes = *OwnedBytes;
3733 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3734 Stream.init(&*StreamFile);
3736 unsigned char buf[16];
3737 if (Bytes.readBytes(buf, 16, 0) != 16)
3738 return Error("Invalid bitcode signature");
3740 if (!isBitcode(buf, buf + 16))
3741 return Error("Invalid bitcode signature");
3743 if (isBitcodeWrapper(buf, buf + 4)) {
3744 const unsigned char *bitcodeStart = buf;
3745 const unsigned char *bitcodeEnd = buf + 16;
3746 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3747 Bytes.dropLeadingBytes(bitcodeStart - buf);
3748 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3750 return std::error_code();
3754 class BitcodeErrorCategoryType : public std::error_category {
3755 const char *name() const LLVM_NOEXCEPT override {
3756 return "llvm.bitcode";
3758 std::string message(int IE) const override {
3759 BitcodeError E = static_cast<BitcodeError>(IE);
3761 case BitcodeError::InvalidBitcodeSignature:
3762 return "Invalid bitcode signature";
3763 case BitcodeError::CorruptedBitcode:
3764 return "Corrupted bitcode";
3766 llvm_unreachable("Unknown error type!");
3771 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3773 const std::error_category &llvm::BitcodeErrorCategory() {
3774 return *ErrorCategory;
3777 //===----------------------------------------------------------------------===//
3778 // External interface
3779 //===----------------------------------------------------------------------===//
3781 /// \brief Get a lazy one-at-time loading module from bitcode.
3783 /// This isn't always used in a lazy context. In particular, it's also used by
3784 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3785 /// in forward-referenced functions from block address references.
3787 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3788 /// materialize everything -- in particular, if this isn't truly lazy.
3789 static ErrorOr<Module *>
3790 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3791 LLVMContext &Context, bool WillMaterializeAll,
3792 DiagnosticHandlerFunction DiagnosticHandler) {
3793 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3795 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3796 M->setMaterializer(R);
3798 auto cleanupOnError = [&](std::error_code EC) {
3799 R->releaseBuffer(); // Never take ownership on error.
3800 delete M; // Also deletes R.
3804 if (std::error_code EC = R->ParseBitcodeInto(M))
3805 return cleanupOnError(EC);
3807 if (!WillMaterializeAll)
3808 // Resolve forward references from blockaddresses.
3809 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3810 return cleanupOnError(EC);
3812 Buffer.release(); // The BitcodeReader owns it now.
3817 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3818 LLVMContext &Context,
3819 DiagnosticHandlerFunction DiagnosticHandler) {
3820 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3824 ErrorOr<std::unique_ptr<Module>>
3825 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3826 LLVMContext &Context,
3827 DiagnosticHandlerFunction DiagnosticHandler) {
3828 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3829 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
3830 M->setMaterializer(R);
3831 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3833 return std::move(M);
3837 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3838 DiagnosticHandlerFunction DiagnosticHandler) {
3839 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3840 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3841 std::move(Buf), Context, true, DiagnosticHandler);
3844 Module *M = ModuleOrErr.get();
3845 // Read in the entire module, and destroy the BitcodeReader.
3846 if (std::error_code EC = M->materializeAllPermanently()) {
3851 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3852 // written. We must defer until the Module has been fully materialized.
3858 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3859 DiagnosticHandlerFunction DiagnosticHandler) {
3860 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3861 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3863 ErrorOr<std::string> Triple = R->parseTriple();
3864 if (Triple.getError())
3866 return Triple.get();