1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/Bitcode/LLVMBitCodes.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/ManagedStatic.h"
33 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
36 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
37 if (WillMaterializeAllForwardRefs)
38 return std::error_code();
41 WillMaterializeAllForwardRefs = true;
43 while (!BasicBlockFwdRefQueue.empty()) {
44 Function *F = BasicBlockFwdRefQueue.front();
45 BasicBlockFwdRefQueue.pop_front();
46 assert(F && "Expected valid function");
47 if (!BasicBlockFwdRefs.count(F))
48 // Already materialized.
51 // Check for a function that isn't materializable to prevent an infinite
52 // loop. When parsing a blockaddress stored in a global variable, there
53 // isn't a trivial way to check if a function will have a body without a
54 // linear search through FunctionsWithBodies, so just check it here.
55 if (!F->isMaterializable())
56 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
58 // Try to materialize F.
59 if (std::error_code EC = materialize(F))
62 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
65 WillMaterializeAllForwardRefs = false;
66 return std::error_code();
69 void BitcodeReader::FreeState() {
71 std::vector<Type*>().swap(TypeList);
74 std::vector<Comdat *>().swap(ComdatList);
76 std::vector<AttributeSet>().swap(MAttributes);
77 std::vector<BasicBlock*>().swap(FunctionBBs);
78 std::vector<Function*>().swap(FunctionsWithBodies);
79 DeferredFunctionInfo.clear();
82 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
83 BasicBlockFwdRefQueue.clear();
86 //===----------------------------------------------------------------------===//
87 // Helper functions to implement forward reference resolution, etc.
88 //===----------------------------------------------------------------------===//
90 /// ConvertToString - Convert a string from a record into an std::string, return
92 template<typename StrTy>
93 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
95 if (Idx > Record.size())
98 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
99 Result += (char)Record[i];
103 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
105 default: // Map unknown/new linkages to external
106 case 0: return GlobalValue::ExternalLinkage;
107 case 1: return GlobalValue::WeakAnyLinkage;
108 case 2: return GlobalValue::AppendingLinkage;
109 case 3: return GlobalValue::InternalLinkage;
110 case 4: return GlobalValue::LinkOnceAnyLinkage;
111 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
112 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
113 case 7: return GlobalValue::ExternalWeakLinkage;
114 case 8: return GlobalValue::CommonLinkage;
115 case 9: return GlobalValue::PrivateLinkage;
116 case 10: return GlobalValue::WeakODRLinkage;
117 case 11: return GlobalValue::LinkOnceODRLinkage;
118 case 12: return GlobalValue::AvailableExternallyLinkage;
120 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
122 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
126 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
128 default: // Map unknown visibilities to default.
129 case 0: return GlobalValue::DefaultVisibility;
130 case 1: return GlobalValue::HiddenVisibility;
131 case 2: return GlobalValue::ProtectedVisibility;
135 static GlobalValue::DLLStorageClassTypes
136 GetDecodedDLLStorageClass(unsigned Val) {
138 default: // Map unknown values to default.
139 case 0: return GlobalValue::DefaultStorageClass;
140 case 1: return GlobalValue::DLLImportStorageClass;
141 case 2: return GlobalValue::DLLExportStorageClass;
145 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
147 case 0: return GlobalVariable::NotThreadLocal;
148 default: // Map unknown non-zero value to general dynamic.
149 case 1: return GlobalVariable::GeneralDynamicTLSModel;
150 case 2: return GlobalVariable::LocalDynamicTLSModel;
151 case 3: return GlobalVariable::InitialExecTLSModel;
152 case 4: return GlobalVariable::LocalExecTLSModel;
156 static int GetDecodedCastOpcode(unsigned Val) {
159 case bitc::CAST_TRUNC : return Instruction::Trunc;
160 case bitc::CAST_ZEXT : return Instruction::ZExt;
161 case bitc::CAST_SEXT : return Instruction::SExt;
162 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
163 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
164 case bitc::CAST_UITOFP : return Instruction::UIToFP;
165 case bitc::CAST_SITOFP : return Instruction::SIToFP;
166 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
167 case bitc::CAST_FPEXT : return Instruction::FPExt;
168 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
169 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
170 case bitc::CAST_BITCAST : return Instruction::BitCast;
171 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
174 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
177 case bitc::BINOP_ADD:
178 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
179 case bitc::BINOP_SUB:
180 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
181 case bitc::BINOP_MUL:
182 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
183 case bitc::BINOP_UDIV: return Instruction::UDiv;
184 case bitc::BINOP_SDIV:
185 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
186 case bitc::BINOP_UREM: return Instruction::URem;
187 case bitc::BINOP_SREM:
188 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
189 case bitc::BINOP_SHL: return Instruction::Shl;
190 case bitc::BINOP_LSHR: return Instruction::LShr;
191 case bitc::BINOP_ASHR: return Instruction::AShr;
192 case bitc::BINOP_AND: return Instruction::And;
193 case bitc::BINOP_OR: return Instruction::Or;
194 case bitc::BINOP_XOR: return Instruction::Xor;
198 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
200 default: return AtomicRMWInst::BAD_BINOP;
201 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
202 case bitc::RMW_ADD: return AtomicRMWInst::Add;
203 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
204 case bitc::RMW_AND: return AtomicRMWInst::And;
205 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
206 case bitc::RMW_OR: return AtomicRMWInst::Or;
207 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
208 case bitc::RMW_MAX: return AtomicRMWInst::Max;
209 case bitc::RMW_MIN: return AtomicRMWInst::Min;
210 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
211 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
215 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
217 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
218 case bitc::ORDERING_UNORDERED: return Unordered;
219 case bitc::ORDERING_MONOTONIC: return Monotonic;
220 case bitc::ORDERING_ACQUIRE: return Acquire;
221 case bitc::ORDERING_RELEASE: return Release;
222 case bitc::ORDERING_ACQREL: return AcquireRelease;
223 default: // Map unknown orderings to sequentially-consistent.
224 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
228 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
230 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
231 default: // Map unknown scopes to cross-thread.
232 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
236 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
238 default: // Map unknown selection kinds to any.
239 case bitc::COMDAT_SELECTION_KIND_ANY:
241 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
242 return Comdat::ExactMatch;
243 case bitc::COMDAT_SELECTION_KIND_LARGEST:
244 return Comdat::Largest;
245 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
246 return Comdat::NoDuplicates;
247 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
248 return Comdat::SameSize;
252 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
254 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
255 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
261 /// @brief A class for maintaining the slot number definition
262 /// as a placeholder for the actual definition for forward constants defs.
263 class ConstantPlaceHolder : public ConstantExpr {
264 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
266 // allocate space for exactly one operand
267 void *operator new(size_t s) {
268 return User::operator new(s, 1);
270 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
271 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
272 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
275 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
276 static bool classof(const Value *V) {
277 return isa<ConstantExpr>(V) &&
278 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
282 /// Provide fast operand accessors
283 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
287 // FIXME: can we inherit this from ConstantExpr?
289 struct OperandTraits<ConstantPlaceHolder> :
290 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
292 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
296 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
305 WeakVH &OldV = ValuePtrs[Idx];
311 // Handle constants and non-constants (e.g. instrs) differently for
313 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
314 ResolveConstants.push_back(std::make_pair(PHC, Idx));
317 // If there was a forward reference to this value, replace it.
318 Value *PrevVal = OldV;
319 OldV->replaceAllUsesWith(V);
325 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
330 if (Value *V = ValuePtrs[Idx]) {
331 assert(Ty == V->getType() && "Type mismatch in constant table!");
332 return cast<Constant>(V);
335 // Create and return a placeholder, which will later be RAUW'd.
336 Constant *C = new ConstantPlaceHolder(Ty, Context);
341 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
345 if (Value *V = ValuePtrs[Idx]) {
346 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
350 // No type specified, must be invalid reference.
351 if (!Ty) return nullptr;
353 // Create and return a placeholder, which will later be RAUW'd.
354 Value *V = new Argument(Ty);
359 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
360 /// resolves any forward references. The idea behind this is that we sometimes
361 /// get constants (such as large arrays) which reference *many* forward ref
362 /// constants. Replacing each of these causes a lot of thrashing when
363 /// building/reuniquing the constant. Instead of doing this, we look at all the
364 /// uses and rewrite all the place holders at once for any constant that uses
366 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
367 // Sort the values by-pointer so that they are efficient to look up with a
369 std::sort(ResolveConstants.begin(), ResolveConstants.end());
371 SmallVector<Constant*, 64> NewOps;
373 while (!ResolveConstants.empty()) {
374 Value *RealVal = operator[](ResolveConstants.back().second);
375 Constant *Placeholder = ResolveConstants.back().first;
376 ResolveConstants.pop_back();
378 // Loop over all users of the placeholder, updating them to reference the
379 // new value. If they reference more than one placeholder, update them all
381 while (!Placeholder->use_empty()) {
382 auto UI = Placeholder->user_begin();
385 // If the using object isn't uniqued, just update the operands. This
386 // handles instructions and initializers for global variables.
387 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
388 UI.getUse().set(RealVal);
392 // Otherwise, we have a constant that uses the placeholder. Replace that
393 // constant with a new constant that has *all* placeholder uses updated.
394 Constant *UserC = cast<Constant>(U);
395 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
398 if (!isa<ConstantPlaceHolder>(*I)) {
399 // Not a placeholder reference.
401 } else if (*I == Placeholder) {
402 // Common case is that it just references this one placeholder.
405 // Otherwise, look up the placeholder in ResolveConstants.
406 ResolveConstantsTy::iterator It =
407 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
408 std::pair<Constant*, unsigned>(cast<Constant>(*I),
410 assert(It != ResolveConstants.end() && It->first == *I);
411 NewOp = operator[](It->second);
414 NewOps.push_back(cast<Constant>(NewOp));
417 // Make the new constant.
419 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
420 NewC = ConstantArray::get(UserCA->getType(), NewOps);
421 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
422 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
423 } else if (isa<ConstantVector>(UserC)) {
424 NewC = ConstantVector::get(NewOps);
426 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
427 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
430 UserC->replaceAllUsesWith(NewC);
431 UserC->destroyConstant();
435 // Update all ValueHandles, they should be the only users at this point.
436 Placeholder->replaceAllUsesWith(RealVal);
441 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
450 WeakVH &OldV = MDValuePtrs[Idx];
456 // If there was a forward reference to this value, replace it.
457 MDNode *PrevVal = cast<MDNode>(OldV);
458 OldV->replaceAllUsesWith(V);
459 MDNode::deleteTemporary(PrevVal);
460 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
462 MDValuePtrs[Idx] = V;
465 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
469 if (Value *V = MDValuePtrs[Idx]) {
470 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
474 // Create and return a placeholder, which will later be RAUW'd.
475 Value *V = MDNode::getTemporary(Context, None);
476 MDValuePtrs[Idx] = V;
480 Type *BitcodeReader::getTypeByID(unsigned ID) {
481 // The type table size is always specified correctly.
482 if (ID >= TypeList.size())
485 if (Type *Ty = TypeList[ID])
488 // If we have a forward reference, the only possible case is when it is to a
489 // named struct. Just create a placeholder for now.
490 return TypeList[ID] = StructType::create(Context);
494 //===----------------------------------------------------------------------===//
495 // Functions for parsing blocks from the bitcode file
496 //===----------------------------------------------------------------------===//
499 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
500 /// been decoded from the given integer. This function must stay in sync with
501 /// 'encodeLLVMAttributesForBitcode'.
502 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
503 uint64_t EncodedAttrs) {
504 // FIXME: Remove in 4.0.
506 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
507 // the bits above 31 down by 11 bits.
508 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
509 assert((!Alignment || isPowerOf2_32(Alignment)) &&
510 "Alignment must be a power of two.");
513 B.addAlignmentAttr(Alignment);
514 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
515 (EncodedAttrs & 0xffff));
518 std::error_code BitcodeReader::ParseAttributeBlock() {
519 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
520 return Error(BitcodeError::InvalidRecord);
522 if (!MAttributes.empty())
523 return Error(BitcodeError::InvalidMultipleBlocks);
525 SmallVector<uint64_t, 64> Record;
527 SmallVector<AttributeSet, 8> Attrs;
529 // Read all the records.
531 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
533 switch (Entry.Kind) {
534 case BitstreamEntry::SubBlock: // Handled for us already.
535 case BitstreamEntry::Error:
536 return Error(BitcodeError::MalformedBlock);
537 case BitstreamEntry::EndBlock:
538 return std::error_code();
539 case BitstreamEntry::Record:
540 // The interesting case.
546 switch (Stream.readRecord(Entry.ID, Record)) {
547 default: // Default behavior: ignore.
549 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
550 // FIXME: Remove in 4.0.
551 if (Record.size() & 1)
552 return Error(BitcodeError::InvalidRecord);
554 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
556 decodeLLVMAttributesForBitcode(B, Record[i+1]);
557 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
560 MAttributes.push_back(AttributeSet::get(Context, Attrs));
564 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
565 for (unsigned i = 0, e = Record.size(); i != e; ++i)
566 Attrs.push_back(MAttributeGroups[Record[i]]);
568 MAttributes.push_back(AttributeSet::get(Context, Attrs));
576 // Returns Attribute::None on unrecognized codes.
577 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
580 return Attribute::None;
581 case bitc::ATTR_KIND_ALIGNMENT:
582 return Attribute::Alignment;
583 case bitc::ATTR_KIND_ALWAYS_INLINE:
584 return Attribute::AlwaysInline;
585 case bitc::ATTR_KIND_BUILTIN:
586 return Attribute::Builtin;
587 case bitc::ATTR_KIND_BY_VAL:
588 return Attribute::ByVal;
589 case bitc::ATTR_KIND_IN_ALLOCA:
590 return Attribute::InAlloca;
591 case bitc::ATTR_KIND_COLD:
592 return Attribute::Cold;
593 case bitc::ATTR_KIND_INLINE_HINT:
594 return Attribute::InlineHint;
595 case bitc::ATTR_KIND_IN_REG:
596 return Attribute::InReg;
597 case bitc::ATTR_KIND_JUMP_TABLE:
598 return Attribute::JumpTable;
599 case bitc::ATTR_KIND_MIN_SIZE:
600 return Attribute::MinSize;
601 case bitc::ATTR_KIND_NAKED:
602 return Attribute::Naked;
603 case bitc::ATTR_KIND_NEST:
604 return Attribute::Nest;
605 case bitc::ATTR_KIND_NO_ALIAS:
606 return Attribute::NoAlias;
607 case bitc::ATTR_KIND_NO_BUILTIN:
608 return Attribute::NoBuiltin;
609 case bitc::ATTR_KIND_NO_CAPTURE:
610 return Attribute::NoCapture;
611 case bitc::ATTR_KIND_NO_DUPLICATE:
612 return Attribute::NoDuplicate;
613 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
614 return Attribute::NoImplicitFloat;
615 case bitc::ATTR_KIND_NO_INLINE:
616 return Attribute::NoInline;
617 case bitc::ATTR_KIND_NON_LAZY_BIND:
618 return Attribute::NonLazyBind;
619 case bitc::ATTR_KIND_NON_NULL:
620 return Attribute::NonNull;
621 case bitc::ATTR_KIND_DEREFERENCEABLE:
622 return Attribute::Dereferenceable;
623 case bitc::ATTR_KIND_NO_RED_ZONE:
624 return Attribute::NoRedZone;
625 case bitc::ATTR_KIND_NO_RETURN:
626 return Attribute::NoReturn;
627 case bitc::ATTR_KIND_NO_UNWIND:
628 return Attribute::NoUnwind;
629 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
630 return Attribute::OptimizeForSize;
631 case bitc::ATTR_KIND_OPTIMIZE_NONE:
632 return Attribute::OptimizeNone;
633 case bitc::ATTR_KIND_READ_NONE:
634 return Attribute::ReadNone;
635 case bitc::ATTR_KIND_READ_ONLY:
636 return Attribute::ReadOnly;
637 case bitc::ATTR_KIND_RETURNED:
638 return Attribute::Returned;
639 case bitc::ATTR_KIND_RETURNS_TWICE:
640 return Attribute::ReturnsTwice;
641 case bitc::ATTR_KIND_S_EXT:
642 return Attribute::SExt;
643 case bitc::ATTR_KIND_STACK_ALIGNMENT:
644 return Attribute::StackAlignment;
645 case bitc::ATTR_KIND_STACK_PROTECT:
646 return Attribute::StackProtect;
647 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
648 return Attribute::StackProtectReq;
649 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
650 return Attribute::StackProtectStrong;
651 case bitc::ATTR_KIND_STRUCT_RET:
652 return Attribute::StructRet;
653 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
654 return Attribute::SanitizeAddress;
655 case bitc::ATTR_KIND_SANITIZE_THREAD:
656 return Attribute::SanitizeThread;
657 case bitc::ATTR_KIND_SANITIZE_MEMORY:
658 return Attribute::SanitizeMemory;
659 case bitc::ATTR_KIND_UW_TABLE:
660 return Attribute::UWTable;
661 case bitc::ATTR_KIND_Z_EXT:
662 return Attribute::ZExt;
666 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
667 Attribute::AttrKind *Kind) {
668 *Kind = GetAttrFromCode(Code);
669 if (*Kind == Attribute::None)
670 return Error(BitcodeError::InvalidValue);
671 return std::error_code();
674 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
675 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
676 return Error(BitcodeError::InvalidRecord);
678 if (!MAttributeGroups.empty())
679 return Error(BitcodeError::InvalidMultipleBlocks);
681 SmallVector<uint64_t, 64> Record;
683 // Read all the records.
685 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
687 switch (Entry.Kind) {
688 case BitstreamEntry::SubBlock: // Handled for us already.
689 case BitstreamEntry::Error:
690 return Error(BitcodeError::MalformedBlock);
691 case BitstreamEntry::EndBlock:
692 return std::error_code();
693 case BitstreamEntry::Record:
694 // The interesting case.
700 switch (Stream.readRecord(Entry.ID, Record)) {
701 default: // Default behavior: ignore.
703 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
704 if (Record.size() < 3)
705 return Error(BitcodeError::InvalidRecord);
707 uint64_t GrpID = Record[0];
708 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
711 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
712 if (Record[i] == 0) { // Enum attribute
713 Attribute::AttrKind Kind;
714 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
717 B.addAttribute(Kind);
718 } else if (Record[i] == 1) { // Integer attribute
719 Attribute::AttrKind Kind;
720 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
722 if (Kind == Attribute::Alignment)
723 B.addAlignmentAttr(Record[++i]);
724 else if (Kind == Attribute::StackAlignment)
725 B.addStackAlignmentAttr(Record[++i]);
726 else if (Kind == Attribute::Dereferenceable)
727 B.addDereferenceableAttr(Record[++i]);
728 } else { // String attribute
729 assert((Record[i] == 3 || Record[i] == 4) &&
730 "Invalid attribute group entry");
731 bool HasValue = (Record[i++] == 4);
732 SmallString<64> KindStr;
733 SmallString<64> ValStr;
735 while (Record[i] != 0 && i != e)
736 KindStr += Record[i++];
737 assert(Record[i] == 0 && "Kind string not null terminated");
740 // Has a value associated with it.
741 ++i; // Skip the '0' that terminates the "kind" string.
742 while (Record[i] != 0 && i != e)
743 ValStr += Record[i++];
744 assert(Record[i] == 0 && "Value string not null terminated");
747 B.addAttribute(KindStr.str(), ValStr.str());
751 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
758 std::error_code BitcodeReader::ParseTypeTable() {
759 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
760 return Error(BitcodeError::InvalidRecord);
762 return ParseTypeTableBody();
765 std::error_code BitcodeReader::ParseTypeTableBody() {
766 if (!TypeList.empty())
767 return Error(BitcodeError::InvalidMultipleBlocks);
769 SmallVector<uint64_t, 64> Record;
770 unsigned NumRecords = 0;
772 SmallString<64> TypeName;
774 // Read all the records for this type table.
776 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
778 switch (Entry.Kind) {
779 case BitstreamEntry::SubBlock: // Handled for us already.
780 case BitstreamEntry::Error:
781 return Error(BitcodeError::MalformedBlock);
782 case BitstreamEntry::EndBlock:
783 if (NumRecords != TypeList.size())
784 return Error(BitcodeError::MalformedBlock);
785 return std::error_code();
786 case BitstreamEntry::Record:
787 // The interesting case.
793 Type *ResultTy = nullptr;
794 switch (Stream.readRecord(Entry.ID, Record)) {
796 return Error(BitcodeError::InvalidValue);
797 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
798 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
799 // type list. This allows us to reserve space.
800 if (Record.size() < 1)
801 return Error(BitcodeError::InvalidRecord);
802 TypeList.resize(Record[0]);
804 case bitc::TYPE_CODE_VOID: // VOID
805 ResultTy = Type::getVoidTy(Context);
807 case bitc::TYPE_CODE_HALF: // HALF
808 ResultTy = Type::getHalfTy(Context);
810 case bitc::TYPE_CODE_FLOAT: // FLOAT
811 ResultTy = Type::getFloatTy(Context);
813 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
814 ResultTy = Type::getDoubleTy(Context);
816 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
817 ResultTy = Type::getX86_FP80Ty(Context);
819 case bitc::TYPE_CODE_FP128: // FP128
820 ResultTy = Type::getFP128Ty(Context);
822 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
823 ResultTy = Type::getPPC_FP128Ty(Context);
825 case bitc::TYPE_CODE_LABEL: // LABEL
826 ResultTy = Type::getLabelTy(Context);
828 case bitc::TYPE_CODE_METADATA: // METADATA
829 ResultTy = Type::getMetadataTy(Context);
831 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
832 ResultTy = Type::getX86_MMXTy(Context);
834 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
835 if (Record.size() < 1)
836 return Error(BitcodeError::InvalidRecord);
838 ResultTy = IntegerType::get(Context, Record[0]);
840 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
841 // [pointee type, address space]
842 if (Record.size() < 1)
843 return Error(BitcodeError::InvalidRecord);
844 unsigned AddressSpace = 0;
845 if (Record.size() == 2)
846 AddressSpace = Record[1];
847 ResultTy = getTypeByID(Record[0]);
849 return Error(BitcodeError::InvalidType);
850 ResultTy = PointerType::get(ResultTy, AddressSpace);
853 case bitc::TYPE_CODE_FUNCTION_OLD: {
854 // FIXME: attrid is dead, remove it in LLVM 4.0
855 // FUNCTION: [vararg, attrid, retty, paramty x N]
856 if (Record.size() < 3)
857 return Error(BitcodeError::InvalidRecord);
858 SmallVector<Type*, 8> ArgTys;
859 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
860 if (Type *T = getTypeByID(Record[i]))
866 ResultTy = getTypeByID(Record[2]);
867 if (!ResultTy || ArgTys.size() < Record.size()-3)
868 return Error(BitcodeError::InvalidType);
870 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
873 case bitc::TYPE_CODE_FUNCTION: {
874 // FUNCTION: [vararg, retty, paramty x N]
875 if (Record.size() < 2)
876 return Error(BitcodeError::InvalidRecord);
877 SmallVector<Type*, 8> ArgTys;
878 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
879 if (Type *T = getTypeByID(Record[i]))
885 ResultTy = getTypeByID(Record[1]);
886 if (!ResultTy || ArgTys.size() < Record.size()-2)
887 return Error(BitcodeError::InvalidType);
889 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
892 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
893 if (Record.size() < 1)
894 return Error(BitcodeError::InvalidRecord);
895 SmallVector<Type*, 8> EltTys;
896 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
897 if (Type *T = getTypeByID(Record[i]))
902 if (EltTys.size() != Record.size()-1)
903 return Error(BitcodeError::InvalidType);
904 ResultTy = StructType::get(Context, EltTys, Record[0]);
907 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
908 if (ConvertToString(Record, 0, TypeName))
909 return Error(BitcodeError::InvalidRecord);
912 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
913 if (Record.size() < 1)
914 return Error(BitcodeError::InvalidRecord);
916 if (NumRecords >= TypeList.size())
917 return Error(BitcodeError::InvalidTYPETable);
919 // Check to see if this was forward referenced, if so fill in the temp.
920 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
922 Res->setName(TypeName);
923 TypeList[NumRecords] = nullptr;
924 } else // Otherwise, create a new struct.
925 Res = StructType::create(Context, TypeName);
928 SmallVector<Type*, 8> EltTys;
929 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
930 if (Type *T = getTypeByID(Record[i]))
935 if (EltTys.size() != Record.size()-1)
936 return Error(BitcodeError::InvalidRecord);
937 Res->setBody(EltTys, Record[0]);
941 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
942 if (Record.size() != 1)
943 return Error(BitcodeError::InvalidRecord);
945 if (NumRecords >= TypeList.size())
946 return Error(BitcodeError::InvalidTYPETable);
948 // Check to see if this was forward referenced, if so fill in the temp.
949 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
951 Res->setName(TypeName);
952 TypeList[NumRecords] = nullptr;
953 } else // Otherwise, create a new struct with no body.
954 Res = StructType::create(Context, TypeName);
959 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
960 if (Record.size() < 2)
961 return Error(BitcodeError::InvalidRecord);
962 if ((ResultTy = getTypeByID(Record[1])))
963 ResultTy = ArrayType::get(ResultTy, Record[0]);
965 return Error(BitcodeError::InvalidType);
967 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
968 if (Record.size() < 2)
969 return Error(BitcodeError::InvalidRecord);
970 if ((ResultTy = getTypeByID(Record[1])))
971 ResultTy = VectorType::get(ResultTy, Record[0]);
973 return Error(BitcodeError::InvalidType);
977 if (NumRecords >= TypeList.size())
978 return Error(BitcodeError::InvalidTYPETable);
979 assert(ResultTy && "Didn't read a type?");
980 assert(!TypeList[NumRecords] && "Already read type?");
981 TypeList[NumRecords++] = ResultTy;
985 std::error_code BitcodeReader::ParseValueSymbolTable() {
986 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
987 return Error(BitcodeError::InvalidRecord);
989 SmallVector<uint64_t, 64> Record;
991 // Read all the records for this value table.
992 SmallString<128> ValueName;
994 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
996 switch (Entry.Kind) {
997 case BitstreamEntry::SubBlock: // Handled for us already.
998 case BitstreamEntry::Error:
999 return Error(BitcodeError::MalformedBlock);
1000 case BitstreamEntry::EndBlock:
1001 return std::error_code();
1002 case BitstreamEntry::Record:
1003 // The interesting case.
1009 switch (Stream.readRecord(Entry.ID, Record)) {
1010 default: // Default behavior: unknown type.
1012 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1013 if (ConvertToString(Record, 1, ValueName))
1014 return Error(BitcodeError::InvalidRecord);
1015 unsigned ValueID = Record[0];
1016 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1017 return Error(BitcodeError::InvalidRecord);
1018 Value *V = ValueList[ValueID];
1020 V->setName(StringRef(ValueName.data(), ValueName.size()));
1024 case bitc::VST_CODE_BBENTRY: {
1025 if (ConvertToString(Record, 1, ValueName))
1026 return Error(BitcodeError::InvalidRecord);
1027 BasicBlock *BB = getBasicBlock(Record[0]);
1029 return Error(BitcodeError::InvalidRecord);
1031 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1039 std::error_code BitcodeReader::ParseMetadata() {
1040 unsigned NextMDValueNo = MDValueList.size();
1042 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1043 return Error(BitcodeError::InvalidRecord);
1045 SmallVector<uint64_t, 64> Record;
1047 // Read all the records.
1049 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1051 switch (Entry.Kind) {
1052 case BitstreamEntry::SubBlock: // Handled for us already.
1053 case BitstreamEntry::Error:
1054 return Error(BitcodeError::MalformedBlock);
1055 case BitstreamEntry::EndBlock:
1056 return std::error_code();
1057 case BitstreamEntry::Record:
1058 // The interesting case.
1062 bool IsFunctionLocal = false;
1065 unsigned Code = Stream.readRecord(Entry.ID, Record);
1067 default: // Default behavior: ignore.
1069 case bitc::METADATA_NAME: {
1070 // Read name of the named metadata.
1071 SmallString<8> Name(Record.begin(), Record.end());
1073 Code = Stream.ReadCode();
1075 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1076 unsigned NextBitCode = Stream.readRecord(Code, Record);
1077 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1079 // Read named metadata elements.
1080 unsigned Size = Record.size();
1081 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1082 for (unsigned i = 0; i != Size; ++i) {
1083 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1085 return Error(BitcodeError::InvalidRecord);
1086 NMD->addOperand(MD);
1090 case bitc::METADATA_FN_NODE:
1091 IsFunctionLocal = true;
1093 case bitc::METADATA_NODE: {
1094 if (Record.size() % 2 == 1)
1095 return Error(BitcodeError::InvalidRecord);
1097 unsigned Size = Record.size();
1098 SmallVector<Value*, 8> Elts;
1099 for (unsigned i = 0; i != Size; i += 2) {
1100 Type *Ty = getTypeByID(Record[i]);
1102 return Error(BitcodeError::InvalidRecord);
1103 if (Ty->isMetadataTy())
1104 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1105 else if (!Ty->isVoidTy())
1106 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1108 Elts.push_back(nullptr);
1110 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1111 IsFunctionLocal = false;
1112 MDValueList.AssignValue(V, NextMDValueNo++);
1115 case bitc::METADATA_STRING: {
1116 std::string String(Record.begin(), Record.end());
1117 llvm::UpgradeMDStringConstant(String);
1118 Value *V = MDString::get(Context, String);
1119 MDValueList.AssignValue(V, NextMDValueNo++);
1122 case bitc::METADATA_KIND: {
1123 if (Record.size() < 2)
1124 return Error(BitcodeError::InvalidRecord);
1126 unsigned Kind = Record[0];
1127 SmallString<8> Name(Record.begin()+1, Record.end());
1129 unsigned NewKind = TheModule->getMDKindID(Name.str());
1130 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1131 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1138 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1139 /// the LSB for dense VBR encoding.
1140 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1145 // There is no such thing as -0 with integers. "-0" really means MININT.
1149 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1150 /// values and aliases that we can.
1151 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1152 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1153 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1154 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1155 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1157 GlobalInitWorklist.swap(GlobalInits);
1158 AliasInitWorklist.swap(AliasInits);
1159 FunctionPrefixWorklist.swap(FunctionPrefixes);
1160 FunctionPrologueWorklist.swap(FunctionPrologues);
1162 while (!GlobalInitWorklist.empty()) {
1163 unsigned ValID = GlobalInitWorklist.back().second;
1164 if (ValID >= ValueList.size()) {
1165 // Not ready to resolve this yet, it requires something later in the file.
1166 GlobalInits.push_back(GlobalInitWorklist.back());
1168 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1169 GlobalInitWorklist.back().first->setInitializer(C);
1171 return Error(BitcodeError::ExpectedConstant);
1173 GlobalInitWorklist.pop_back();
1176 while (!AliasInitWorklist.empty()) {
1177 unsigned ValID = AliasInitWorklist.back().second;
1178 if (ValID >= ValueList.size()) {
1179 AliasInits.push_back(AliasInitWorklist.back());
1181 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1182 AliasInitWorklist.back().first->setAliasee(C);
1184 return Error(BitcodeError::ExpectedConstant);
1186 AliasInitWorklist.pop_back();
1189 while (!FunctionPrefixWorklist.empty()) {
1190 unsigned ValID = FunctionPrefixWorklist.back().second;
1191 if (ValID >= ValueList.size()) {
1192 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1194 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1195 FunctionPrefixWorklist.back().first->setPrefixData(C);
1197 return Error(BitcodeError::ExpectedConstant);
1199 FunctionPrefixWorklist.pop_back();
1202 while (!FunctionPrologueWorklist.empty()) {
1203 unsigned ValID = FunctionPrologueWorklist.back().second;
1204 if (ValID >= ValueList.size()) {
1205 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1207 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1208 FunctionPrologueWorklist.back().first->setPrologueData(C);
1210 return Error(BitcodeError::ExpectedConstant);
1212 FunctionPrologueWorklist.pop_back();
1215 return std::error_code();
1218 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1219 SmallVector<uint64_t, 8> Words(Vals.size());
1220 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1221 BitcodeReader::decodeSignRotatedValue);
1223 return APInt(TypeBits, Words);
1226 std::error_code BitcodeReader::ParseConstants() {
1227 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1228 return Error(BitcodeError::InvalidRecord);
1230 SmallVector<uint64_t, 64> Record;
1232 // Read all the records for this value table.
1233 Type *CurTy = Type::getInt32Ty(Context);
1234 unsigned NextCstNo = ValueList.size();
1236 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1238 switch (Entry.Kind) {
1239 case BitstreamEntry::SubBlock: // Handled for us already.
1240 case BitstreamEntry::Error:
1241 return Error(BitcodeError::MalformedBlock);
1242 case BitstreamEntry::EndBlock:
1243 if (NextCstNo != ValueList.size())
1244 return Error(BitcodeError::InvalidConstantReference);
1246 // Once all the constants have been read, go through and resolve forward
1248 ValueList.ResolveConstantForwardRefs();
1249 return std::error_code();
1250 case BitstreamEntry::Record:
1251 // The interesting case.
1258 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1260 default: // Default behavior: unknown constant
1261 case bitc::CST_CODE_UNDEF: // UNDEF
1262 V = UndefValue::get(CurTy);
1264 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1266 return Error(BitcodeError::InvalidRecord);
1267 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1268 return Error(BitcodeError::InvalidRecord);
1269 CurTy = TypeList[Record[0]];
1270 continue; // Skip the ValueList manipulation.
1271 case bitc::CST_CODE_NULL: // NULL
1272 V = Constant::getNullValue(CurTy);
1274 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1275 if (!CurTy->isIntegerTy() || Record.empty())
1276 return Error(BitcodeError::InvalidRecord);
1277 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1279 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1280 if (!CurTy->isIntegerTy() || Record.empty())
1281 return Error(BitcodeError::InvalidRecord);
1283 APInt VInt = ReadWideAPInt(Record,
1284 cast<IntegerType>(CurTy)->getBitWidth());
1285 V = ConstantInt::get(Context, VInt);
1289 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1291 return Error(BitcodeError::InvalidRecord);
1292 if (CurTy->isHalfTy())
1293 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1294 APInt(16, (uint16_t)Record[0])));
1295 else if (CurTy->isFloatTy())
1296 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1297 APInt(32, (uint32_t)Record[0])));
1298 else if (CurTy->isDoubleTy())
1299 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1300 APInt(64, Record[0])));
1301 else if (CurTy->isX86_FP80Ty()) {
1302 // Bits are not stored the same way as a normal i80 APInt, compensate.
1303 uint64_t Rearrange[2];
1304 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1305 Rearrange[1] = Record[0] >> 48;
1306 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1307 APInt(80, Rearrange)));
1308 } else if (CurTy->isFP128Ty())
1309 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1310 APInt(128, Record)));
1311 else if (CurTy->isPPC_FP128Ty())
1312 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1313 APInt(128, Record)));
1315 V = UndefValue::get(CurTy);
1319 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1321 return Error(BitcodeError::InvalidRecord);
1323 unsigned Size = Record.size();
1324 SmallVector<Constant*, 16> Elts;
1326 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1327 for (unsigned i = 0; i != Size; ++i)
1328 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1329 STy->getElementType(i)));
1330 V = ConstantStruct::get(STy, Elts);
1331 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1332 Type *EltTy = ATy->getElementType();
1333 for (unsigned i = 0; i != Size; ++i)
1334 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1335 V = ConstantArray::get(ATy, Elts);
1336 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1337 Type *EltTy = VTy->getElementType();
1338 for (unsigned i = 0; i != Size; ++i)
1339 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1340 V = ConstantVector::get(Elts);
1342 V = UndefValue::get(CurTy);
1346 case bitc::CST_CODE_STRING: // STRING: [values]
1347 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1349 return Error(BitcodeError::InvalidRecord);
1351 SmallString<16> Elts(Record.begin(), Record.end());
1352 V = ConstantDataArray::getString(Context, Elts,
1353 BitCode == bitc::CST_CODE_CSTRING);
1356 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1358 return Error(BitcodeError::InvalidRecord);
1360 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1361 unsigned Size = Record.size();
1363 if (EltTy->isIntegerTy(8)) {
1364 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1365 if (isa<VectorType>(CurTy))
1366 V = ConstantDataVector::get(Context, Elts);
1368 V = ConstantDataArray::get(Context, Elts);
1369 } else if (EltTy->isIntegerTy(16)) {
1370 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1371 if (isa<VectorType>(CurTy))
1372 V = ConstantDataVector::get(Context, Elts);
1374 V = ConstantDataArray::get(Context, Elts);
1375 } else if (EltTy->isIntegerTy(32)) {
1376 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1377 if (isa<VectorType>(CurTy))
1378 V = ConstantDataVector::get(Context, Elts);
1380 V = ConstantDataArray::get(Context, Elts);
1381 } else if (EltTy->isIntegerTy(64)) {
1382 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1383 if (isa<VectorType>(CurTy))
1384 V = ConstantDataVector::get(Context, Elts);
1386 V = ConstantDataArray::get(Context, Elts);
1387 } else if (EltTy->isFloatTy()) {
1388 SmallVector<float, 16> Elts(Size);
1389 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1390 if (isa<VectorType>(CurTy))
1391 V = ConstantDataVector::get(Context, Elts);
1393 V = ConstantDataArray::get(Context, Elts);
1394 } else if (EltTy->isDoubleTy()) {
1395 SmallVector<double, 16> Elts(Size);
1396 std::transform(Record.begin(), Record.end(), Elts.begin(),
1398 if (isa<VectorType>(CurTy))
1399 V = ConstantDataVector::get(Context, Elts);
1401 V = ConstantDataArray::get(Context, Elts);
1403 return Error(BitcodeError::InvalidTypeForValue);
1408 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1409 if (Record.size() < 3)
1410 return Error(BitcodeError::InvalidRecord);
1411 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1413 V = UndefValue::get(CurTy); // Unknown binop.
1415 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1416 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1418 if (Record.size() >= 4) {
1419 if (Opc == Instruction::Add ||
1420 Opc == Instruction::Sub ||
1421 Opc == Instruction::Mul ||
1422 Opc == Instruction::Shl) {
1423 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1424 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1425 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1426 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1427 } else if (Opc == Instruction::SDiv ||
1428 Opc == Instruction::UDiv ||
1429 Opc == Instruction::LShr ||
1430 Opc == Instruction::AShr) {
1431 if (Record[3] & (1 << bitc::PEO_EXACT))
1432 Flags |= SDivOperator::IsExact;
1435 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1439 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1440 if (Record.size() < 3)
1441 return Error(BitcodeError::InvalidRecord);
1442 int Opc = GetDecodedCastOpcode(Record[0]);
1444 V = UndefValue::get(CurTy); // Unknown cast.
1446 Type *OpTy = getTypeByID(Record[1]);
1448 return Error(BitcodeError::InvalidRecord);
1449 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1450 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1451 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1455 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1456 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1457 if (Record.size() & 1)
1458 return Error(BitcodeError::InvalidRecord);
1459 SmallVector<Constant*, 16> Elts;
1460 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1461 Type *ElTy = getTypeByID(Record[i]);
1463 return Error(BitcodeError::InvalidRecord);
1464 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1466 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1467 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1469 bitc::CST_CODE_CE_INBOUNDS_GEP);
1472 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1473 if (Record.size() < 3)
1474 return Error(BitcodeError::InvalidRecord);
1476 Type *SelectorTy = Type::getInt1Ty(Context);
1478 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1479 // vector. Otherwise, it must be a single bit.
1480 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1481 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1482 VTy->getNumElements());
1484 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1486 ValueList.getConstantFwdRef(Record[1],CurTy),
1487 ValueList.getConstantFwdRef(Record[2],CurTy));
1490 case bitc::CST_CODE_CE_EXTRACTELT
1491 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1492 if (Record.size() < 3)
1493 return Error(BitcodeError::InvalidRecord);
1495 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1497 return Error(BitcodeError::InvalidRecord);
1498 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1499 Constant *Op1 = nullptr;
1500 if (Record.size() == 4) {
1501 Type *IdxTy = getTypeByID(Record[2]);
1503 return Error(BitcodeError::InvalidRecord);
1504 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1505 } else // TODO: Remove with llvm 4.0
1506 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1508 return Error(BitcodeError::InvalidRecord);
1509 V = ConstantExpr::getExtractElement(Op0, Op1);
1512 case bitc::CST_CODE_CE_INSERTELT
1513 : { // CE_INSERTELT: [opval, opval, opty, opval]
1514 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1515 if (Record.size() < 3 || !OpTy)
1516 return Error(BitcodeError::InvalidRecord);
1517 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1518 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1519 OpTy->getElementType());
1520 Constant *Op2 = nullptr;
1521 if (Record.size() == 4) {
1522 Type *IdxTy = getTypeByID(Record[2]);
1524 return Error(BitcodeError::InvalidRecord);
1525 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1526 } else // TODO: Remove with llvm 4.0
1527 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1529 return Error(BitcodeError::InvalidRecord);
1530 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1533 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1534 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1535 if (Record.size() < 3 || !OpTy)
1536 return Error(BitcodeError::InvalidRecord);
1537 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1538 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1539 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1540 OpTy->getNumElements());
1541 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1542 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1545 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1546 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1548 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1549 if (Record.size() < 4 || !RTy || !OpTy)
1550 return Error(BitcodeError::InvalidRecord);
1551 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1552 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1553 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1554 RTy->getNumElements());
1555 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1556 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1559 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1560 if (Record.size() < 4)
1561 return Error(BitcodeError::InvalidRecord);
1562 Type *OpTy = getTypeByID(Record[0]);
1564 return Error(BitcodeError::InvalidRecord);
1565 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1566 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1568 if (OpTy->isFPOrFPVectorTy())
1569 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1571 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1574 // This maintains backward compatibility, pre-asm dialect keywords.
1575 // FIXME: Remove with the 4.0 release.
1576 case bitc::CST_CODE_INLINEASM_OLD: {
1577 if (Record.size() < 2)
1578 return Error(BitcodeError::InvalidRecord);
1579 std::string AsmStr, ConstrStr;
1580 bool HasSideEffects = Record[0] & 1;
1581 bool IsAlignStack = Record[0] >> 1;
1582 unsigned AsmStrSize = Record[1];
1583 if (2+AsmStrSize >= Record.size())
1584 return Error(BitcodeError::InvalidRecord);
1585 unsigned ConstStrSize = Record[2+AsmStrSize];
1586 if (3+AsmStrSize+ConstStrSize > Record.size())
1587 return Error(BitcodeError::InvalidRecord);
1589 for (unsigned i = 0; i != AsmStrSize; ++i)
1590 AsmStr += (char)Record[2+i];
1591 for (unsigned i = 0; i != ConstStrSize; ++i)
1592 ConstrStr += (char)Record[3+AsmStrSize+i];
1593 PointerType *PTy = cast<PointerType>(CurTy);
1594 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1595 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1598 // This version adds support for the asm dialect keywords (e.g.,
1600 case bitc::CST_CODE_INLINEASM: {
1601 if (Record.size() < 2)
1602 return Error(BitcodeError::InvalidRecord);
1603 std::string AsmStr, ConstrStr;
1604 bool HasSideEffects = Record[0] & 1;
1605 bool IsAlignStack = (Record[0] >> 1) & 1;
1606 unsigned AsmDialect = Record[0] >> 2;
1607 unsigned AsmStrSize = Record[1];
1608 if (2+AsmStrSize >= Record.size())
1609 return Error(BitcodeError::InvalidRecord);
1610 unsigned ConstStrSize = Record[2+AsmStrSize];
1611 if (3+AsmStrSize+ConstStrSize > Record.size())
1612 return Error(BitcodeError::InvalidRecord);
1614 for (unsigned i = 0; i != AsmStrSize; ++i)
1615 AsmStr += (char)Record[2+i];
1616 for (unsigned i = 0; i != ConstStrSize; ++i)
1617 ConstrStr += (char)Record[3+AsmStrSize+i];
1618 PointerType *PTy = cast<PointerType>(CurTy);
1619 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1620 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1621 InlineAsm::AsmDialect(AsmDialect));
1624 case bitc::CST_CODE_BLOCKADDRESS:{
1625 if (Record.size() < 3)
1626 return Error(BitcodeError::InvalidRecord);
1627 Type *FnTy = getTypeByID(Record[0]);
1629 return Error(BitcodeError::InvalidRecord);
1631 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1633 return Error(BitcodeError::InvalidRecord);
1635 // Don't let Fn get dematerialized.
1636 BlockAddressesTaken.insert(Fn);
1638 // If the function is already parsed we can insert the block address right
1641 unsigned BBID = Record[2];
1643 // Invalid reference to entry block.
1644 return Error(BitcodeError::InvalidID);
1646 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1647 for (size_t I = 0, E = BBID; I != E; ++I) {
1649 return Error(BitcodeError::InvalidID);
1654 // Otherwise insert a placeholder and remember it so it can be inserted
1655 // when the function is parsed.
1656 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1658 BasicBlockFwdRefQueue.push_back(Fn);
1659 if (FwdBBs.size() < BBID + 1)
1660 FwdBBs.resize(BBID + 1);
1662 FwdBBs[BBID] = BasicBlock::Create(Context);
1665 V = BlockAddress::get(Fn, BB);
1670 ValueList.AssignValue(V, NextCstNo);
1675 std::error_code BitcodeReader::ParseUseLists() {
1676 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1677 return Error(BitcodeError::InvalidRecord);
1679 // Read all the records.
1680 SmallVector<uint64_t, 64> Record;
1682 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1684 switch (Entry.Kind) {
1685 case BitstreamEntry::SubBlock: // Handled for us already.
1686 case BitstreamEntry::Error:
1687 return Error(BitcodeError::MalformedBlock);
1688 case BitstreamEntry::EndBlock:
1689 return std::error_code();
1690 case BitstreamEntry::Record:
1691 // The interesting case.
1695 // Read a use list record.
1698 switch (Stream.readRecord(Entry.ID, Record)) {
1699 default: // Default behavior: unknown type.
1701 case bitc::USELIST_CODE_BB:
1704 case bitc::USELIST_CODE_DEFAULT: {
1705 unsigned RecordLength = Record.size();
1706 if (RecordLength < 3)
1707 // Records should have at least an ID and two indexes.
1708 return Error(BitcodeError::InvalidRecord);
1709 unsigned ID = Record.back();
1714 assert(ID < FunctionBBs.size() && "Basic block not found");
1715 V = FunctionBBs[ID];
1718 unsigned NumUses = 0;
1719 SmallDenseMap<const Use *, unsigned, 16> Order;
1720 for (const Use &U : V->uses()) {
1721 if (++NumUses > Record.size())
1723 Order[&U] = Record[NumUses - 1];
1725 if (Order.size() != Record.size() || NumUses > Record.size())
1726 // Mismatches can happen if the functions are being materialized lazily
1727 // (out-of-order), or a value has been upgraded.
1730 V->sortUseList([&](const Use &L, const Use &R) {
1731 return Order.lookup(&L) < Order.lookup(&R);
1739 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1740 /// remember where it is and then skip it. This lets us lazily deserialize the
1742 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1743 // Get the function we are talking about.
1744 if (FunctionsWithBodies.empty())
1745 return Error(BitcodeError::InsufficientFunctionProtos);
1747 Function *Fn = FunctionsWithBodies.back();
1748 FunctionsWithBodies.pop_back();
1750 // Save the current stream state.
1751 uint64_t CurBit = Stream.GetCurrentBitNo();
1752 DeferredFunctionInfo[Fn] = CurBit;
1754 // Skip over the function block for now.
1755 if (Stream.SkipBlock())
1756 return Error(BitcodeError::InvalidRecord);
1757 return std::error_code();
1760 std::error_code BitcodeReader::GlobalCleanup() {
1761 // Patch the initializers for globals and aliases up.
1762 ResolveGlobalAndAliasInits();
1763 if (!GlobalInits.empty() || !AliasInits.empty())
1764 return Error(BitcodeError::MalformedGlobalInitializerSet);
1766 // Look for intrinsic functions which need to be upgraded at some point
1767 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1770 if (UpgradeIntrinsicFunction(FI, NewFn))
1771 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1774 // Look for global variables which need to be renamed.
1775 for (Module::global_iterator
1776 GI = TheModule->global_begin(), GE = TheModule->global_end();
1778 GlobalVariable *GV = GI++;
1779 UpgradeGlobalVariable(GV);
1782 // Force deallocation of memory for these vectors to favor the client that
1783 // want lazy deserialization.
1784 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1785 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1786 return std::error_code();
1789 std::error_code BitcodeReader::ParseModule(bool Resume) {
1791 Stream.JumpToBit(NextUnreadBit);
1792 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1793 return Error(BitcodeError::InvalidRecord);
1795 SmallVector<uint64_t, 64> Record;
1796 std::vector<std::string> SectionTable;
1797 std::vector<std::string> GCTable;
1799 // Read all the records for this module.
1801 BitstreamEntry Entry = Stream.advance();
1803 switch (Entry.Kind) {
1804 case BitstreamEntry::Error:
1805 return Error(BitcodeError::MalformedBlock);
1806 case BitstreamEntry::EndBlock:
1807 return GlobalCleanup();
1809 case BitstreamEntry::SubBlock:
1811 default: // Skip unknown content.
1812 if (Stream.SkipBlock())
1813 return Error(BitcodeError::InvalidRecord);
1815 case bitc::BLOCKINFO_BLOCK_ID:
1816 if (Stream.ReadBlockInfoBlock())
1817 return Error(BitcodeError::MalformedBlock);
1819 case bitc::PARAMATTR_BLOCK_ID:
1820 if (std::error_code EC = ParseAttributeBlock())
1823 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1824 if (std::error_code EC = ParseAttributeGroupBlock())
1827 case bitc::TYPE_BLOCK_ID_NEW:
1828 if (std::error_code EC = ParseTypeTable())
1831 case bitc::VALUE_SYMTAB_BLOCK_ID:
1832 if (std::error_code EC = ParseValueSymbolTable())
1834 SeenValueSymbolTable = true;
1836 case bitc::CONSTANTS_BLOCK_ID:
1837 if (std::error_code EC = ParseConstants())
1839 if (std::error_code EC = ResolveGlobalAndAliasInits())
1842 case bitc::METADATA_BLOCK_ID:
1843 if (std::error_code EC = ParseMetadata())
1846 case bitc::FUNCTION_BLOCK_ID:
1847 // If this is the first function body we've seen, reverse the
1848 // FunctionsWithBodies list.
1849 if (!SeenFirstFunctionBody) {
1850 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1851 if (std::error_code EC = GlobalCleanup())
1853 SeenFirstFunctionBody = true;
1856 if (std::error_code EC = RememberAndSkipFunctionBody())
1858 // For streaming bitcode, suspend parsing when we reach the function
1859 // bodies. Subsequent materialization calls will resume it when
1860 // necessary. For streaming, the function bodies must be at the end of
1861 // the bitcode. If the bitcode file is old, the symbol table will be
1862 // at the end instead and will not have been seen yet. In this case,
1863 // just finish the parse now.
1864 if (LazyStreamer && SeenValueSymbolTable) {
1865 NextUnreadBit = Stream.GetCurrentBitNo();
1866 return std::error_code();
1869 case bitc::USELIST_BLOCK_ID:
1870 if (std::error_code EC = ParseUseLists())
1876 case BitstreamEntry::Record:
1877 // The interesting case.
1883 switch (Stream.readRecord(Entry.ID, Record)) {
1884 default: break; // Default behavior, ignore unknown content.
1885 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1886 if (Record.size() < 1)
1887 return Error(BitcodeError::InvalidRecord);
1888 // Only version #0 and #1 are supported so far.
1889 unsigned module_version = Record[0];
1890 switch (module_version) {
1892 return Error(BitcodeError::InvalidValue);
1894 UseRelativeIDs = false;
1897 UseRelativeIDs = true;
1902 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1904 if (ConvertToString(Record, 0, S))
1905 return Error(BitcodeError::InvalidRecord);
1906 TheModule->setTargetTriple(S);
1909 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1911 if (ConvertToString(Record, 0, S))
1912 return Error(BitcodeError::InvalidRecord);
1913 TheModule->setDataLayout(S);
1916 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1918 if (ConvertToString(Record, 0, S))
1919 return Error(BitcodeError::InvalidRecord);
1920 TheModule->setModuleInlineAsm(S);
1923 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1924 // FIXME: Remove in 4.0.
1926 if (ConvertToString(Record, 0, S))
1927 return Error(BitcodeError::InvalidRecord);
1931 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1933 if (ConvertToString(Record, 0, S))
1934 return Error(BitcodeError::InvalidRecord);
1935 SectionTable.push_back(S);
1938 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1940 if (ConvertToString(Record, 0, S))
1941 return Error(BitcodeError::InvalidRecord);
1942 GCTable.push_back(S);
1945 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1946 if (Record.size() < 2)
1947 return Error(BitcodeError::InvalidRecord);
1948 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1949 unsigned ComdatNameSize = Record[1];
1950 std::string ComdatName;
1951 ComdatName.reserve(ComdatNameSize);
1952 for (unsigned i = 0; i != ComdatNameSize; ++i)
1953 ComdatName += (char)Record[2 + i];
1954 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1955 C->setSelectionKind(SK);
1956 ComdatList.push_back(C);
1959 // GLOBALVAR: [pointer type, isconst, initid,
1960 // linkage, alignment, section, visibility, threadlocal,
1961 // unnamed_addr, dllstorageclass]
1962 case bitc::MODULE_CODE_GLOBALVAR: {
1963 if (Record.size() < 6)
1964 return Error(BitcodeError::InvalidRecord);
1965 Type *Ty = getTypeByID(Record[0]);
1967 return Error(BitcodeError::InvalidRecord);
1968 if (!Ty->isPointerTy())
1969 return Error(BitcodeError::InvalidTypeForValue);
1970 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1971 Ty = cast<PointerType>(Ty)->getElementType();
1973 bool isConstant = Record[1];
1974 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1975 unsigned Alignment = (1 << Record[4]) >> 1;
1976 std::string Section;
1978 if (Record[5]-1 >= SectionTable.size())
1979 return Error(BitcodeError::InvalidID);
1980 Section = SectionTable[Record[5]-1];
1982 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1983 // Local linkage must have default visibility.
1984 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1985 // FIXME: Change to an error if non-default in 4.0.
1986 Visibility = GetDecodedVisibility(Record[6]);
1988 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1989 if (Record.size() > 7)
1990 TLM = GetDecodedThreadLocalMode(Record[7]);
1992 bool UnnamedAddr = false;
1993 if (Record.size() > 8)
1994 UnnamedAddr = Record[8];
1996 bool ExternallyInitialized = false;
1997 if (Record.size() > 9)
1998 ExternallyInitialized = Record[9];
2000 GlobalVariable *NewGV =
2001 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2002 TLM, AddressSpace, ExternallyInitialized);
2003 NewGV->setAlignment(Alignment);
2004 if (!Section.empty())
2005 NewGV->setSection(Section);
2006 NewGV->setVisibility(Visibility);
2007 NewGV->setUnnamedAddr(UnnamedAddr);
2009 if (Record.size() > 10)
2010 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2012 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2014 ValueList.push_back(NewGV);
2016 // Remember which value to use for the global initializer.
2017 if (unsigned InitID = Record[2])
2018 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2020 if (Record.size() > 11)
2021 if (unsigned ComdatID = Record[11]) {
2022 assert(ComdatID <= ComdatList.size());
2023 NewGV->setComdat(ComdatList[ComdatID - 1]);
2027 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2028 // alignment, section, visibility, gc, unnamed_addr,
2029 // prologuedata, dllstorageclass, comdat, prefixdata]
2030 case bitc::MODULE_CODE_FUNCTION: {
2031 if (Record.size() < 8)
2032 return Error(BitcodeError::InvalidRecord);
2033 Type *Ty = getTypeByID(Record[0]);
2035 return Error(BitcodeError::InvalidRecord);
2036 if (!Ty->isPointerTy())
2037 return Error(BitcodeError::InvalidTypeForValue);
2039 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2041 return Error(BitcodeError::InvalidTypeForValue);
2043 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2046 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2047 bool isProto = Record[2];
2048 Func->setLinkage(GetDecodedLinkage(Record[3]));
2049 Func->setAttributes(getAttributes(Record[4]));
2051 Func->setAlignment((1 << Record[5]) >> 1);
2053 if (Record[6]-1 >= SectionTable.size())
2054 return Error(BitcodeError::InvalidID);
2055 Func->setSection(SectionTable[Record[6]-1]);
2057 // Local linkage must have default visibility.
2058 if (!Func->hasLocalLinkage())
2059 // FIXME: Change to an error if non-default in 4.0.
2060 Func->setVisibility(GetDecodedVisibility(Record[7]));
2061 if (Record.size() > 8 && Record[8]) {
2062 if (Record[8]-1 > GCTable.size())
2063 return Error(BitcodeError::InvalidID);
2064 Func->setGC(GCTable[Record[8]-1].c_str());
2066 bool UnnamedAddr = false;
2067 if (Record.size() > 9)
2068 UnnamedAddr = Record[9];
2069 Func->setUnnamedAddr(UnnamedAddr);
2070 if (Record.size() > 10 && Record[10] != 0)
2071 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2073 if (Record.size() > 11)
2074 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2076 UpgradeDLLImportExportLinkage(Func, Record[3]);
2078 if (Record.size() > 12)
2079 if (unsigned ComdatID = Record[12]) {
2080 assert(ComdatID <= ComdatList.size());
2081 Func->setComdat(ComdatList[ComdatID - 1]);
2084 if (Record.size() > 13 && Record[13] != 0)
2085 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2087 ValueList.push_back(Func);
2089 // If this is a function with a body, remember the prototype we are
2090 // creating now, so that we can match up the body with them later.
2092 Func->setIsMaterializable(true);
2093 FunctionsWithBodies.push_back(Func);
2095 DeferredFunctionInfo[Func] = 0;
2099 // ALIAS: [alias type, aliasee val#, linkage]
2100 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2101 case bitc::MODULE_CODE_ALIAS: {
2102 if (Record.size() < 3)
2103 return Error(BitcodeError::InvalidRecord);
2104 Type *Ty = getTypeByID(Record[0]);
2106 return Error(BitcodeError::InvalidRecord);
2107 auto *PTy = dyn_cast<PointerType>(Ty);
2109 return Error(BitcodeError::InvalidTypeForValue);
2112 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2113 GetDecodedLinkage(Record[2]), "", TheModule);
2114 // Old bitcode files didn't have visibility field.
2115 // Local linkage must have default visibility.
2116 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2117 // FIXME: Change to an error if non-default in 4.0.
2118 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2119 if (Record.size() > 4)
2120 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2122 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2123 if (Record.size() > 5)
2124 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2125 if (Record.size() > 6)
2126 NewGA->setUnnamedAddr(Record[6]);
2127 ValueList.push_back(NewGA);
2128 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2131 /// MODULE_CODE_PURGEVALS: [numvals]
2132 case bitc::MODULE_CODE_PURGEVALS:
2133 // Trim down the value list to the specified size.
2134 if (Record.size() < 1 || Record[0] > ValueList.size())
2135 return Error(BitcodeError::InvalidRecord);
2136 ValueList.shrinkTo(Record[0]);
2143 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2144 TheModule = nullptr;
2146 if (std::error_code EC = InitStream())
2149 // Sniff for the signature.
2150 if (Stream.Read(8) != 'B' ||
2151 Stream.Read(8) != 'C' ||
2152 Stream.Read(4) != 0x0 ||
2153 Stream.Read(4) != 0xC ||
2154 Stream.Read(4) != 0xE ||
2155 Stream.Read(4) != 0xD)
2156 return Error(BitcodeError::InvalidBitcodeSignature);
2158 // We expect a number of well-defined blocks, though we don't necessarily
2159 // need to understand them all.
2161 if (Stream.AtEndOfStream())
2162 return std::error_code();
2164 BitstreamEntry Entry =
2165 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2167 switch (Entry.Kind) {
2168 case BitstreamEntry::Error:
2169 return Error(BitcodeError::MalformedBlock);
2170 case BitstreamEntry::EndBlock:
2171 return std::error_code();
2173 case BitstreamEntry::SubBlock:
2175 case bitc::BLOCKINFO_BLOCK_ID:
2176 if (Stream.ReadBlockInfoBlock())
2177 return Error(BitcodeError::MalformedBlock);
2179 case bitc::MODULE_BLOCK_ID:
2180 // Reject multiple MODULE_BLOCK's in a single bitstream.
2182 return Error(BitcodeError::InvalidMultipleBlocks);
2184 if (std::error_code EC = ParseModule(false))
2187 return std::error_code();
2190 if (Stream.SkipBlock())
2191 return Error(BitcodeError::InvalidRecord);
2195 case BitstreamEntry::Record:
2196 // There should be no records in the top-level of blocks.
2198 // The ranlib in Xcode 4 will align archive members by appending newlines
2199 // to the end of them. If this file size is a multiple of 4 but not 8, we
2200 // have to read and ignore these final 4 bytes :-(
2201 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2202 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2203 Stream.AtEndOfStream())
2204 return std::error_code();
2206 return Error(BitcodeError::InvalidRecord);
2211 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2212 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2213 return Error(BitcodeError::InvalidRecord);
2215 SmallVector<uint64_t, 64> Record;
2218 // Read all the records for this module.
2220 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2222 switch (Entry.Kind) {
2223 case BitstreamEntry::SubBlock: // Handled for us already.
2224 case BitstreamEntry::Error:
2225 return Error(BitcodeError::MalformedBlock);
2226 case BitstreamEntry::EndBlock:
2228 case BitstreamEntry::Record:
2229 // The interesting case.
2234 switch (Stream.readRecord(Entry.ID, Record)) {
2235 default: break; // Default behavior, ignore unknown content.
2236 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2238 if (ConvertToString(Record, 0, S))
2239 return Error(BitcodeError::InvalidRecord);
2246 llvm_unreachable("Exit infinite loop");
2249 ErrorOr<std::string> BitcodeReader::parseTriple() {
2250 if (std::error_code EC = InitStream())
2253 // Sniff for the signature.
2254 if (Stream.Read(8) != 'B' ||
2255 Stream.Read(8) != 'C' ||
2256 Stream.Read(4) != 0x0 ||
2257 Stream.Read(4) != 0xC ||
2258 Stream.Read(4) != 0xE ||
2259 Stream.Read(4) != 0xD)
2260 return Error(BitcodeError::InvalidBitcodeSignature);
2262 // We expect a number of well-defined blocks, though we don't necessarily
2263 // need to understand them all.
2265 BitstreamEntry Entry = Stream.advance();
2267 switch (Entry.Kind) {
2268 case BitstreamEntry::Error:
2269 return Error(BitcodeError::MalformedBlock);
2270 case BitstreamEntry::EndBlock:
2271 return std::error_code();
2273 case BitstreamEntry::SubBlock:
2274 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2275 return parseModuleTriple();
2277 // Ignore other sub-blocks.
2278 if (Stream.SkipBlock())
2279 return Error(BitcodeError::MalformedBlock);
2282 case BitstreamEntry::Record:
2283 Stream.skipRecord(Entry.ID);
2289 /// ParseMetadataAttachment - Parse metadata attachments.
2290 std::error_code BitcodeReader::ParseMetadataAttachment() {
2291 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2292 return Error(BitcodeError::InvalidRecord);
2294 SmallVector<uint64_t, 64> Record;
2296 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2298 switch (Entry.Kind) {
2299 case BitstreamEntry::SubBlock: // Handled for us already.
2300 case BitstreamEntry::Error:
2301 return Error(BitcodeError::MalformedBlock);
2302 case BitstreamEntry::EndBlock:
2303 return std::error_code();
2304 case BitstreamEntry::Record:
2305 // The interesting case.
2309 // Read a metadata attachment record.
2311 switch (Stream.readRecord(Entry.ID, Record)) {
2312 default: // Default behavior: ignore.
2314 case bitc::METADATA_ATTACHMENT: {
2315 unsigned RecordLength = Record.size();
2316 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2317 return Error(BitcodeError::InvalidRecord);
2318 Instruction *Inst = InstructionList[Record[0]];
2319 for (unsigned i = 1; i != RecordLength; i = i+2) {
2320 unsigned Kind = Record[i];
2321 DenseMap<unsigned, unsigned>::iterator I =
2322 MDKindMap.find(Kind);
2323 if (I == MDKindMap.end())
2324 return Error(BitcodeError::InvalidID);
2325 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2326 Inst->setMetadata(I->second, cast<MDNode>(Node));
2327 if (I->second == LLVMContext::MD_tbaa)
2328 InstsWithTBAATag.push_back(Inst);
2336 /// ParseFunctionBody - Lazily parse the specified function body block.
2337 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2338 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2339 return Error(BitcodeError::InvalidRecord);
2341 InstructionList.clear();
2342 unsigned ModuleValueListSize = ValueList.size();
2343 unsigned ModuleMDValueListSize = MDValueList.size();
2345 // Add all the function arguments to the value table.
2346 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2347 ValueList.push_back(I);
2349 unsigned NextValueNo = ValueList.size();
2350 BasicBlock *CurBB = nullptr;
2351 unsigned CurBBNo = 0;
2355 // Read all the records.
2356 SmallVector<uint64_t, 64> Record;
2358 BitstreamEntry Entry = Stream.advance();
2360 switch (Entry.Kind) {
2361 case BitstreamEntry::Error:
2362 return Error(BitcodeError::MalformedBlock);
2363 case BitstreamEntry::EndBlock:
2364 goto OutOfRecordLoop;
2366 case BitstreamEntry::SubBlock:
2368 default: // Skip unknown content.
2369 if (Stream.SkipBlock())
2370 return Error(BitcodeError::InvalidRecord);
2372 case bitc::CONSTANTS_BLOCK_ID:
2373 if (std::error_code EC = ParseConstants())
2375 NextValueNo = ValueList.size();
2377 case bitc::VALUE_SYMTAB_BLOCK_ID:
2378 if (std::error_code EC = ParseValueSymbolTable())
2381 case bitc::METADATA_ATTACHMENT_ID:
2382 if (std::error_code EC = ParseMetadataAttachment())
2385 case bitc::METADATA_BLOCK_ID:
2386 if (std::error_code EC = ParseMetadata())
2389 case bitc::USELIST_BLOCK_ID:
2390 if (std::error_code EC = ParseUseLists())
2396 case BitstreamEntry::Record:
2397 // The interesting case.
2403 Instruction *I = nullptr;
2404 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2406 default: // Default behavior: reject
2407 return Error(BitcodeError::InvalidValue);
2408 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2409 if (Record.size() < 1 || Record[0] == 0)
2410 return Error(BitcodeError::InvalidRecord);
2411 // Create all the basic blocks for the function.
2412 FunctionBBs.resize(Record[0]);
2414 // See if anything took the address of blocks in this function.
2415 auto BBFRI = BasicBlockFwdRefs.find(F);
2416 if (BBFRI == BasicBlockFwdRefs.end()) {
2417 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2418 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2420 auto &BBRefs = BBFRI->second;
2421 // Check for invalid basic block references.
2422 if (BBRefs.size() > FunctionBBs.size())
2423 return Error(BitcodeError::InvalidID);
2424 assert(!BBRefs.empty() && "Unexpected empty array");
2425 assert(!BBRefs.front() && "Invalid reference to entry block");
2426 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2428 if (I < RE && BBRefs[I]) {
2429 BBRefs[I]->insertInto(F);
2430 FunctionBBs[I] = BBRefs[I];
2432 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2435 // Erase from the table.
2436 BasicBlockFwdRefs.erase(BBFRI);
2439 CurBB = FunctionBBs[0];
2443 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2444 // This record indicates that the last instruction is at the same
2445 // location as the previous instruction with a location.
2448 // Get the last instruction emitted.
2449 if (CurBB && !CurBB->empty())
2451 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2452 !FunctionBBs[CurBBNo-1]->empty())
2453 I = &FunctionBBs[CurBBNo-1]->back();
2456 return Error(BitcodeError::InvalidRecord);
2457 I->setDebugLoc(LastLoc);
2461 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2462 I = nullptr; // Get the last instruction emitted.
2463 if (CurBB && !CurBB->empty())
2465 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2466 !FunctionBBs[CurBBNo-1]->empty())
2467 I = &FunctionBBs[CurBBNo-1]->back();
2468 if (!I || Record.size() < 4)
2469 return Error(BitcodeError::InvalidRecord);
2471 unsigned Line = Record[0], Col = Record[1];
2472 unsigned ScopeID = Record[2], IAID = Record[3];
2474 MDNode *Scope = nullptr, *IA = nullptr;
2475 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2476 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2477 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2478 I->setDebugLoc(LastLoc);
2483 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2486 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2487 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2488 OpNum+1 > Record.size())
2489 return Error(BitcodeError::InvalidRecord);
2491 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2493 return Error(BitcodeError::InvalidRecord);
2494 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2495 InstructionList.push_back(I);
2496 if (OpNum < Record.size()) {
2497 if (Opc == Instruction::Add ||
2498 Opc == Instruction::Sub ||
2499 Opc == Instruction::Mul ||
2500 Opc == Instruction::Shl) {
2501 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2502 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2503 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2504 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2505 } else if (Opc == Instruction::SDiv ||
2506 Opc == Instruction::UDiv ||
2507 Opc == Instruction::LShr ||
2508 Opc == Instruction::AShr) {
2509 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2510 cast<BinaryOperator>(I)->setIsExact(true);
2511 } else if (isa<FPMathOperator>(I)) {
2513 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2514 FMF.setUnsafeAlgebra();
2515 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2517 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2519 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2520 FMF.setNoSignedZeros();
2521 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2522 FMF.setAllowReciprocal();
2524 I->setFastMathFlags(FMF);
2530 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2533 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2534 OpNum+2 != Record.size())
2535 return Error(BitcodeError::InvalidRecord);
2537 Type *ResTy = getTypeByID(Record[OpNum]);
2538 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2539 if (Opc == -1 || !ResTy)
2540 return Error(BitcodeError::InvalidRecord);
2541 Instruction *Temp = nullptr;
2542 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2544 InstructionList.push_back(Temp);
2545 CurBB->getInstList().push_back(Temp);
2548 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2550 InstructionList.push_back(I);
2553 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2554 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2557 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2558 return Error(BitcodeError::InvalidRecord);
2560 SmallVector<Value*, 16> GEPIdx;
2561 while (OpNum != Record.size()) {
2563 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2564 return Error(BitcodeError::InvalidRecord);
2565 GEPIdx.push_back(Op);
2568 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2569 InstructionList.push_back(I);
2570 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2571 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2575 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2576 // EXTRACTVAL: [opty, opval, n x indices]
2579 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2580 return Error(BitcodeError::InvalidRecord);
2582 SmallVector<unsigned, 4> EXTRACTVALIdx;
2583 for (unsigned RecSize = Record.size();
2584 OpNum != RecSize; ++OpNum) {
2585 uint64_t Index = Record[OpNum];
2586 if ((unsigned)Index != Index)
2587 return Error(BitcodeError::InvalidValue);
2588 EXTRACTVALIdx.push_back((unsigned)Index);
2591 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2592 InstructionList.push_back(I);
2596 case bitc::FUNC_CODE_INST_INSERTVAL: {
2597 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2600 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2601 return Error(BitcodeError::InvalidRecord);
2603 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2604 return Error(BitcodeError::InvalidRecord);
2606 SmallVector<unsigned, 4> INSERTVALIdx;
2607 for (unsigned RecSize = Record.size();
2608 OpNum != RecSize; ++OpNum) {
2609 uint64_t Index = Record[OpNum];
2610 if ((unsigned)Index != Index)
2611 return Error(BitcodeError::InvalidValue);
2612 INSERTVALIdx.push_back((unsigned)Index);
2615 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2616 InstructionList.push_back(I);
2620 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2621 // obsolete form of select
2622 // handles select i1 ... in old bitcode
2624 Value *TrueVal, *FalseVal, *Cond;
2625 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2626 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2627 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2628 return Error(BitcodeError::InvalidRecord);
2630 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2631 InstructionList.push_back(I);
2635 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2636 // new form of select
2637 // handles select i1 or select [N x i1]
2639 Value *TrueVal, *FalseVal, *Cond;
2640 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2641 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2642 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2643 return Error(BitcodeError::InvalidRecord);
2645 // select condition can be either i1 or [N x i1]
2646 if (VectorType* vector_type =
2647 dyn_cast<VectorType>(Cond->getType())) {
2649 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2650 return Error(BitcodeError::InvalidTypeForValue);
2653 if (Cond->getType() != Type::getInt1Ty(Context))
2654 return Error(BitcodeError::InvalidTypeForValue);
2657 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2658 InstructionList.push_back(I);
2662 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2665 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2666 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2667 return Error(BitcodeError::InvalidRecord);
2668 I = ExtractElementInst::Create(Vec, Idx);
2669 InstructionList.push_back(I);
2673 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2675 Value *Vec, *Elt, *Idx;
2676 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2677 popValue(Record, OpNum, NextValueNo,
2678 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2679 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2680 return Error(BitcodeError::InvalidRecord);
2681 I = InsertElementInst::Create(Vec, Elt, Idx);
2682 InstructionList.push_back(I);
2686 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2688 Value *Vec1, *Vec2, *Mask;
2689 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2690 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2691 return Error(BitcodeError::InvalidRecord);
2693 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2694 return Error(BitcodeError::InvalidRecord);
2695 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2696 InstructionList.push_back(I);
2700 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2701 // Old form of ICmp/FCmp returning bool
2702 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2703 // both legal on vectors but had different behaviour.
2704 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2705 // FCmp/ICmp returning bool or vector of bool
2709 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2710 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2711 OpNum+1 != Record.size())
2712 return Error(BitcodeError::InvalidRecord);
2714 if (LHS->getType()->isFPOrFPVectorTy())
2715 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2717 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2718 InstructionList.push_back(I);
2722 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2724 unsigned Size = Record.size();
2726 I = ReturnInst::Create(Context);
2727 InstructionList.push_back(I);
2732 Value *Op = nullptr;
2733 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2734 return Error(BitcodeError::InvalidRecord);
2735 if (OpNum != Record.size())
2736 return Error(BitcodeError::InvalidRecord);
2738 I = ReturnInst::Create(Context, Op);
2739 InstructionList.push_back(I);
2742 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2743 if (Record.size() != 1 && Record.size() != 3)
2744 return Error(BitcodeError::InvalidRecord);
2745 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2747 return Error(BitcodeError::InvalidRecord);
2749 if (Record.size() == 1) {
2750 I = BranchInst::Create(TrueDest);
2751 InstructionList.push_back(I);
2754 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2755 Value *Cond = getValue(Record, 2, NextValueNo,
2756 Type::getInt1Ty(Context));
2757 if (!FalseDest || !Cond)
2758 return Error(BitcodeError::InvalidRecord);
2759 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2760 InstructionList.push_back(I);
2764 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2766 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2767 // "New" SwitchInst format with case ranges. The changes to write this
2768 // format were reverted but we still recognize bitcode that uses it.
2769 // Hopefully someday we will have support for case ranges and can use
2770 // this format again.
2772 Type *OpTy = getTypeByID(Record[1]);
2773 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2775 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2776 BasicBlock *Default = getBasicBlock(Record[3]);
2777 if (!OpTy || !Cond || !Default)
2778 return Error(BitcodeError::InvalidRecord);
2780 unsigned NumCases = Record[4];
2782 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2783 InstructionList.push_back(SI);
2785 unsigned CurIdx = 5;
2786 for (unsigned i = 0; i != NumCases; ++i) {
2787 SmallVector<ConstantInt*, 1> CaseVals;
2788 unsigned NumItems = Record[CurIdx++];
2789 for (unsigned ci = 0; ci != NumItems; ++ci) {
2790 bool isSingleNumber = Record[CurIdx++];
2793 unsigned ActiveWords = 1;
2794 if (ValueBitWidth > 64)
2795 ActiveWords = Record[CurIdx++];
2796 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2798 CurIdx += ActiveWords;
2800 if (!isSingleNumber) {
2802 if (ValueBitWidth > 64)
2803 ActiveWords = Record[CurIdx++];
2805 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2807 CurIdx += ActiveWords;
2809 // FIXME: It is not clear whether values in the range should be
2810 // compared as signed or unsigned values. The partially
2811 // implemented changes that used this format in the past used
2812 // unsigned comparisons.
2813 for ( ; Low.ule(High); ++Low)
2814 CaseVals.push_back(ConstantInt::get(Context, Low));
2816 CaseVals.push_back(ConstantInt::get(Context, Low));
2818 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2819 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2820 cve = CaseVals.end(); cvi != cve; ++cvi)
2821 SI->addCase(*cvi, DestBB);
2827 // Old SwitchInst format without case ranges.
2829 if (Record.size() < 3 || (Record.size() & 1) == 0)
2830 return Error(BitcodeError::InvalidRecord);
2831 Type *OpTy = getTypeByID(Record[0]);
2832 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2833 BasicBlock *Default = getBasicBlock(Record[2]);
2834 if (!OpTy || !Cond || !Default)
2835 return Error(BitcodeError::InvalidRecord);
2836 unsigned NumCases = (Record.size()-3)/2;
2837 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2838 InstructionList.push_back(SI);
2839 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2840 ConstantInt *CaseVal =
2841 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2842 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2843 if (!CaseVal || !DestBB) {
2845 return Error(BitcodeError::InvalidRecord);
2847 SI->addCase(CaseVal, DestBB);
2852 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2853 if (Record.size() < 2)
2854 return Error(BitcodeError::InvalidRecord);
2855 Type *OpTy = getTypeByID(Record[0]);
2856 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2857 if (!OpTy || !Address)
2858 return Error(BitcodeError::InvalidRecord);
2859 unsigned NumDests = Record.size()-2;
2860 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2861 InstructionList.push_back(IBI);
2862 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2863 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2864 IBI->addDestination(DestBB);
2867 return Error(BitcodeError::InvalidRecord);
2874 case bitc::FUNC_CODE_INST_INVOKE: {
2875 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2876 if (Record.size() < 4)
2877 return Error(BitcodeError::InvalidRecord);
2878 AttributeSet PAL = getAttributes(Record[0]);
2879 unsigned CCInfo = Record[1];
2880 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2881 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2885 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2886 return Error(BitcodeError::InvalidRecord);
2888 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2889 FunctionType *FTy = !CalleeTy ? nullptr :
2890 dyn_cast<FunctionType>(CalleeTy->getElementType());
2892 // Check that the right number of fixed parameters are here.
2893 if (!FTy || !NormalBB || !UnwindBB ||
2894 Record.size() < OpNum+FTy->getNumParams())
2895 return Error(BitcodeError::InvalidRecord);
2897 SmallVector<Value*, 16> Ops;
2898 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2899 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2900 FTy->getParamType(i)));
2902 return Error(BitcodeError::InvalidRecord);
2905 if (!FTy->isVarArg()) {
2906 if (Record.size() != OpNum)
2907 return Error(BitcodeError::InvalidRecord);
2909 // Read type/value pairs for varargs params.
2910 while (OpNum != Record.size()) {
2912 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2913 return Error(BitcodeError::InvalidRecord);
2918 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2919 InstructionList.push_back(I);
2920 cast<InvokeInst>(I)->setCallingConv(
2921 static_cast<CallingConv::ID>(CCInfo));
2922 cast<InvokeInst>(I)->setAttributes(PAL);
2925 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2927 Value *Val = nullptr;
2928 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2929 return Error(BitcodeError::InvalidRecord);
2930 I = ResumeInst::Create(Val);
2931 InstructionList.push_back(I);
2934 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2935 I = new UnreachableInst(Context);
2936 InstructionList.push_back(I);
2938 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2939 if (Record.size() < 1 || ((Record.size()-1)&1))
2940 return Error(BitcodeError::InvalidRecord);
2941 Type *Ty = getTypeByID(Record[0]);
2943 return Error(BitcodeError::InvalidRecord);
2945 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2946 InstructionList.push_back(PN);
2948 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2950 // With the new function encoding, it is possible that operands have
2951 // negative IDs (for forward references). Use a signed VBR
2952 // representation to keep the encoding small.
2954 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2956 V = getValue(Record, 1+i, NextValueNo, Ty);
2957 BasicBlock *BB = getBasicBlock(Record[2+i]);
2959 return Error(BitcodeError::InvalidRecord);
2960 PN->addIncoming(V, BB);
2966 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2967 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2969 if (Record.size() < 4)
2970 return Error(BitcodeError::InvalidRecord);
2971 Type *Ty = getTypeByID(Record[Idx++]);
2973 return Error(BitcodeError::InvalidRecord);
2974 Value *PersFn = nullptr;
2975 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2976 return Error(BitcodeError::InvalidRecord);
2978 bool IsCleanup = !!Record[Idx++];
2979 unsigned NumClauses = Record[Idx++];
2980 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2981 LP->setCleanup(IsCleanup);
2982 for (unsigned J = 0; J != NumClauses; ++J) {
2983 LandingPadInst::ClauseType CT =
2984 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2987 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2989 return Error(BitcodeError::InvalidRecord);
2992 assert((CT != LandingPadInst::Catch ||
2993 !isa<ArrayType>(Val->getType())) &&
2994 "Catch clause has a invalid type!");
2995 assert((CT != LandingPadInst::Filter ||
2996 isa<ArrayType>(Val->getType())) &&
2997 "Filter clause has invalid type!");
2998 LP->addClause(cast<Constant>(Val));
3002 InstructionList.push_back(I);
3006 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3007 if (Record.size() != 4)
3008 return Error(BitcodeError::InvalidRecord);
3010 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3011 Type *OpTy = getTypeByID(Record[1]);
3012 Value *Size = getFnValueByID(Record[2], OpTy);
3013 unsigned AlignRecord = Record[3];
3014 bool InAlloca = AlignRecord & (1 << 5);
3015 unsigned Align = AlignRecord & ((1 << 5) - 1);
3017 return Error(BitcodeError::InvalidRecord);
3018 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3019 AI->setUsedWithInAlloca(InAlloca);
3021 InstructionList.push_back(I);
3024 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3027 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3028 OpNum+2 != Record.size())
3029 return Error(BitcodeError::InvalidRecord);
3031 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3032 InstructionList.push_back(I);
3035 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3036 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3039 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3040 OpNum+4 != Record.size())
3041 return Error(BitcodeError::InvalidRecord);
3043 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3044 if (Ordering == NotAtomic || Ordering == Release ||
3045 Ordering == AcquireRelease)
3046 return Error(BitcodeError::InvalidRecord);
3047 if (Ordering != NotAtomic && Record[OpNum] == 0)
3048 return Error(BitcodeError::InvalidRecord);
3049 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3051 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3052 Ordering, SynchScope);
3053 InstructionList.push_back(I);
3056 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3059 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3060 popValue(Record, OpNum, NextValueNo,
3061 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3062 OpNum+2 != Record.size())
3063 return Error(BitcodeError::InvalidRecord);
3065 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3066 InstructionList.push_back(I);
3069 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3070 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3073 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3074 popValue(Record, OpNum, NextValueNo,
3075 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3076 OpNum+4 != Record.size())
3077 return Error(BitcodeError::InvalidRecord);
3079 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3080 if (Ordering == NotAtomic || Ordering == Acquire ||
3081 Ordering == AcquireRelease)
3082 return Error(BitcodeError::InvalidRecord);
3083 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3084 if (Ordering != NotAtomic && Record[OpNum] == 0)
3085 return Error(BitcodeError::InvalidRecord);
3087 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3088 Ordering, SynchScope);
3089 InstructionList.push_back(I);
3092 case bitc::FUNC_CODE_INST_CMPXCHG: {
3093 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3094 // failureordering?, isweak?]
3096 Value *Ptr, *Cmp, *New;
3097 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3098 popValue(Record, OpNum, NextValueNo,
3099 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3100 popValue(Record, OpNum, NextValueNo,
3101 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3102 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3103 return Error(BitcodeError::InvalidRecord);
3104 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3105 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3106 return Error(BitcodeError::InvalidRecord);
3107 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3109 AtomicOrdering FailureOrdering;
3110 if (Record.size() < 7)
3112 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3114 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3116 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3118 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3120 if (Record.size() < 8) {
3121 // Before weak cmpxchgs existed, the instruction simply returned the
3122 // value loaded from memory, so bitcode files from that era will be
3123 // expecting the first component of a modern cmpxchg.
3124 CurBB->getInstList().push_back(I);
3125 I = ExtractValueInst::Create(I, 0);
3127 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3130 InstructionList.push_back(I);
3133 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3134 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3137 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3138 popValue(Record, OpNum, NextValueNo,
3139 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3140 OpNum+4 != Record.size())
3141 return Error(BitcodeError::InvalidRecord);
3142 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3143 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3144 Operation > AtomicRMWInst::LAST_BINOP)
3145 return Error(BitcodeError::InvalidRecord);
3146 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3147 if (Ordering == NotAtomic || Ordering == Unordered)
3148 return Error(BitcodeError::InvalidRecord);
3149 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3150 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3151 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3152 InstructionList.push_back(I);
3155 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3156 if (2 != Record.size())
3157 return Error(BitcodeError::InvalidRecord);
3158 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3159 if (Ordering == NotAtomic || Ordering == Unordered ||
3160 Ordering == Monotonic)
3161 return Error(BitcodeError::InvalidRecord);
3162 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3163 I = new FenceInst(Context, Ordering, SynchScope);
3164 InstructionList.push_back(I);
3167 case bitc::FUNC_CODE_INST_CALL: {
3168 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3169 if (Record.size() < 3)
3170 return Error(BitcodeError::InvalidRecord);
3172 AttributeSet PAL = getAttributes(Record[0]);
3173 unsigned CCInfo = Record[1];
3177 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3178 return Error(BitcodeError::InvalidRecord);
3180 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3181 FunctionType *FTy = nullptr;
3182 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3183 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3184 return Error(BitcodeError::InvalidRecord);
3186 SmallVector<Value*, 16> Args;
3187 // Read the fixed params.
3188 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3189 if (FTy->getParamType(i)->isLabelTy())
3190 Args.push_back(getBasicBlock(Record[OpNum]));
3192 Args.push_back(getValue(Record, OpNum, NextValueNo,
3193 FTy->getParamType(i)));
3195 return Error(BitcodeError::InvalidRecord);
3198 // Read type/value pairs for varargs params.
3199 if (!FTy->isVarArg()) {
3200 if (OpNum != Record.size())
3201 return Error(BitcodeError::InvalidRecord);
3203 while (OpNum != Record.size()) {
3205 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3206 return Error(BitcodeError::InvalidRecord);
3211 I = CallInst::Create(Callee, Args);
3212 InstructionList.push_back(I);
3213 cast<CallInst>(I)->setCallingConv(
3214 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3215 CallInst::TailCallKind TCK = CallInst::TCK_None;
3217 TCK = CallInst::TCK_Tail;
3218 if (CCInfo & (1 << 14))
3219 TCK = CallInst::TCK_MustTail;
3220 cast<CallInst>(I)->setTailCallKind(TCK);
3221 cast<CallInst>(I)->setAttributes(PAL);
3224 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3225 if (Record.size() < 3)
3226 return Error(BitcodeError::InvalidRecord);
3227 Type *OpTy = getTypeByID(Record[0]);
3228 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3229 Type *ResTy = getTypeByID(Record[2]);
3230 if (!OpTy || !Op || !ResTy)
3231 return Error(BitcodeError::InvalidRecord);
3232 I = new VAArgInst(Op, ResTy);
3233 InstructionList.push_back(I);
3238 // Add instruction to end of current BB. If there is no current BB, reject
3242 return Error(BitcodeError::InvalidInstructionWithNoBB);
3244 CurBB->getInstList().push_back(I);
3246 // If this was a terminator instruction, move to the next block.
3247 if (isa<TerminatorInst>(I)) {
3249 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3252 // Non-void values get registered in the value table for future use.
3253 if (I && !I->getType()->isVoidTy())
3254 ValueList.AssignValue(I, NextValueNo++);
3259 // Check the function list for unresolved values.
3260 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3261 if (!A->getParent()) {
3262 // We found at least one unresolved value. Nuke them all to avoid leaks.
3263 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3264 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3265 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3269 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3273 // FIXME: Check for unresolved forward-declared metadata references
3274 // and clean up leaks.
3276 // Trim the value list down to the size it was before we parsed this function.
3277 ValueList.shrinkTo(ModuleValueListSize);
3278 MDValueList.shrinkTo(ModuleMDValueListSize);
3279 std::vector<BasicBlock*>().swap(FunctionBBs);
3280 return std::error_code();
3283 /// Find the function body in the bitcode stream
3284 std::error_code BitcodeReader::FindFunctionInStream(
3286 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3287 while (DeferredFunctionInfoIterator->second == 0) {
3288 if (Stream.AtEndOfStream())
3289 return Error(BitcodeError::CouldNotFindFunctionInStream);
3290 // ParseModule will parse the next body in the stream and set its
3291 // position in the DeferredFunctionInfo map.
3292 if (std::error_code EC = ParseModule(true))
3295 return std::error_code();
3298 //===----------------------------------------------------------------------===//
3299 // GVMaterializer implementation
3300 //===----------------------------------------------------------------------===//
3302 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3304 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3305 Function *F = dyn_cast<Function>(GV);
3306 // If it's not a function or is already material, ignore the request.
3307 if (!F || !F->isMaterializable())
3308 return std::error_code();
3310 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3311 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3312 // If its position is recorded as 0, its body is somewhere in the stream
3313 // but we haven't seen it yet.
3314 if (DFII->second == 0 && LazyStreamer)
3315 if (std::error_code EC = FindFunctionInStream(F, DFII))
3318 // Move the bit stream to the saved position of the deferred function body.
3319 Stream.JumpToBit(DFII->second);
3321 if (std::error_code EC = ParseFunctionBody(F))
3323 F->setIsMaterializable(false);
3325 // Upgrade any old intrinsic calls in the function.
3326 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3327 E = UpgradedIntrinsics.end(); I != E; ++I) {
3328 if (I->first != I->second) {
3329 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3331 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3332 UpgradeIntrinsicCall(CI, I->second);
3337 // Bring in any functions that this function forward-referenced via
3339 return materializeForwardReferencedFunctions();
3342 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3343 const Function *F = dyn_cast<Function>(GV);
3344 if (!F || F->isDeclaration())
3347 // Dematerializing F would leave dangling references that wouldn't be
3348 // reconnected on re-materialization.
3349 if (BlockAddressesTaken.count(F))
3352 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3355 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3356 Function *F = dyn_cast<Function>(GV);
3357 // If this function isn't dematerializable, this is a noop.
3358 if (!F || !isDematerializable(F))
3361 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3363 // Just forget the function body, we can remat it later.
3364 F->dropAllReferences();
3365 F->setIsMaterializable(true);
3368 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3369 assert(M == TheModule &&
3370 "Can only Materialize the Module this BitcodeReader is attached to.");
3372 // Promise to materialize all forward references.
3373 WillMaterializeAllForwardRefs = true;
3375 // Iterate over the module, deserializing any functions that are still on
3377 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3379 if (std::error_code EC = materialize(F))
3382 // At this point, if there are any function bodies, the current bit is
3383 // pointing to the END_BLOCK record after them. Now make sure the rest
3384 // of the bits in the module have been read.
3388 // Check that all block address forward references got resolved (as we
3390 if (!BasicBlockFwdRefs.empty())
3391 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3393 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3394 // delete the old functions to clean up. We can't do this unless the entire
3395 // module is materialized because there could always be another function body
3396 // with calls to the old function.
3397 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3398 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3399 if (I->first != I->second) {
3400 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3402 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3403 UpgradeIntrinsicCall(CI, I->second);
3405 if (!I->first->use_empty())
3406 I->first->replaceAllUsesWith(I->second);
3407 I->first->eraseFromParent();
3410 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3412 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3413 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3415 UpgradeDebugInfo(*M);
3416 return std::error_code();
3419 std::error_code BitcodeReader::InitStream() {
3421 return InitLazyStream();
3422 return InitStreamFromBuffer();
3425 std::error_code BitcodeReader::InitStreamFromBuffer() {
3426 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3427 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3429 if (Buffer->getBufferSize() & 3)
3430 return Error(BitcodeError::InvalidBitcodeSignature);
3432 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3433 // The magic number is 0x0B17C0DE stored in little endian.
3434 if (isBitcodeWrapper(BufPtr, BufEnd))
3435 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3436 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3438 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3439 Stream.init(&*StreamFile);
3441 return std::error_code();
3444 std::error_code BitcodeReader::InitLazyStream() {
3445 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3447 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3448 StreamFile.reset(new BitstreamReader(Bytes));
3449 Stream.init(&*StreamFile);
3451 unsigned char buf[16];
3452 if (Bytes->readBytes(buf, 16, 0) != 16)
3453 return Error(BitcodeError::InvalidBitcodeSignature);
3455 if (!isBitcode(buf, buf + 16))
3456 return Error(BitcodeError::InvalidBitcodeSignature);
3458 if (isBitcodeWrapper(buf, buf + 4)) {
3459 const unsigned char *bitcodeStart = buf;
3460 const unsigned char *bitcodeEnd = buf + 16;
3461 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3462 Bytes->dropLeadingBytes(bitcodeStart - buf);
3463 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3465 return std::error_code();
3469 class BitcodeErrorCategoryType : public std::error_category {
3470 const char *name() const LLVM_NOEXCEPT override {
3471 return "llvm.bitcode";
3473 std::string message(int IE) const override {
3474 BitcodeError E = static_cast<BitcodeError>(IE);
3476 case BitcodeError::ConflictingMETADATA_KINDRecords:
3477 return "Conflicting METADATA_KIND records";
3478 case BitcodeError::CouldNotFindFunctionInStream:
3479 return "Could not find function in stream";
3480 case BitcodeError::ExpectedConstant:
3481 return "Expected a constant";
3482 case BitcodeError::InsufficientFunctionProtos:
3483 return "Insufficient function protos";
3484 case BitcodeError::InvalidBitcodeSignature:
3485 return "Invalid bitcode signature";
3486 case BitcodeError::InvalidBitcodeWrapperHeader:
3487 return "Invalid bitcode wrapper header";
3488 case BitcodeError::InvalidConstantReference:
3489 return "Invalid ronstant reference";
3490 case BitcodeError::InvalidID:
3491 return "Invalid ID";
3492 case BitcodeError::InvalidInstructionWithNoBB:
3493 return "Invalid instruction with no BB";
3494 case BitcodeError::InvalidRecord:
3495 return "Invalid record";
3496 case BitcodeError::InvalidTypeForValue:
3497 return "Invalid type for value";
3498 case BitcodeError::InvalidTYPETable:
3499 return "Invalid TYPE table";
3500 case BitcodeError::InvalidType:
3501 return "Invalid type";
3502 case BitcodeError::MalformedBlock:
3503 return "Malformed block";
3504 case BitcodeError::MalformedGlobalInitializerSet:
3505 return "Malformed global initializer set";
3506 case BitcodeError::InvalidMultipleBlocks:
3507 return "Invalid multiple blocks";
3508 case BitcodeError::NeverResolvedValueFoundInFunction:
3509 return "Never resolved value found in function";
3510 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3511 return "Never resolved function from blockaddress";
3512 case BitcodeError::InvalidValue:
3513 return "Invalid value";
3515 llvm_unreachable("Unknown error type!");
3520 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3522 const std::error_category &llvm::BitcodeErrorCategory() {
3523 return *ErrorCategory;
3526 //===----------------------------------------------------------------------===//
3527 // External interface
3528 //===----------------------------------------------------------------------===//
3530 /// \brief Get a lazy one-at-time loading module from bitcode.
3532 /// This isn't always used in a lazy context. In particular, it's also used by
3533 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3534 /// in forward-referenced functions from block address references.
3536 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3537 /// materialize everything -- in particular, if this isn't truly lazy.
3538 static ErrorOr<Module *>
3539 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3540 LLVMContext &Context, bool WillMaterializeAll) {
3541 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3542 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3543 M->setMaterializer(R);
3545 auto cleanupOnError = [&](std::error_code EC) {
3546 R->releaseBuffer(); // Never take ownership on error.
3547 delete M; // Also deletes R.
3551 if (std::error_code EC = R->ParseBitcodeInto(M))
3552 return cleanupOnError(EC);
3554 if (!WillMaterializeAll)
3555 // Resolve forward references from blockaddresses.
3556 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3557 return cleanupOnError(EC);
3559 Buffer.release(); // The BitcodeReader owns it now.
3564 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3565 LLVMContext &Context) {
3566 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3569 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3570 DataStreamer *streamer,
3571 LLVMContext &Context,
3572 std::string *ErrMsg) {
3573 Module *M = new Module(name, Context);
3574 BitcodeReader *R = new BitcodeReader(streamer, Context);
3575 M->setMaterializer(R);
3576 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3578 *ErrMsg = EC.message();
3579 delete M; // Also deletes R.
3585 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3586 LLVMContext &Context) {
3587 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3588 ErrorOr<Module *> ModuleOrErr =
3589 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3592 Module *M = ModuleOrErr.get();
3593 // Read in the entire module, and destroy the BitcodeReader.
3594 if (std::error_code EC = M->materializeAllPermanently()) {
3599 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3600 // written. We must defer until the Module has been fully materialized.
3605 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3606 LLVMContext &Context) {
3607 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3608 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3609 ErrorOr<std::string> Triple = R->parseTriple();
3610 if (Triple.getError())
3612 return Triple.get();