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"
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 void BitcodeReader::materializeForwardReferencedFunctions() {
35 while (!BlockAddrFwdRefs.empty()) {
36 Function *F = BlockAddrFwdRefs.begin()->first;
41 void BitcodeReader::FreeState() {
43 std::vector<Type*>().swap(TypeList);
46 std::vector<Comdat *>().swap(ComdatList);
48 std::vector<AttributeSet>().swap(MAttributes);
49 std::vector<BasicBlock*>().swap(FunctionBBs);
50 std::vector<Function*>().swap(FunctionsWithBodies);
51 DeferredFunctionInfo.clear();
54 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
57 //===----------------------------------------------------------------------===//
58 // Helper functions to implement forward reference resolution, etc.
59 //===----------------------------------------------------------------------===//
61 /// ConvertToString - Convert a string from a record into an std::string, return
63 template<typename StrTy>
64 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
66 if (Idx > Record.size())
69 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
70 Result += (char)Record[i];
74 ErrorOr<StringRef> BitcodeReader::convertToStringRef(ArrayRef<uint64_t> Record,
76 if (Idx > Record.size())
77 return Error(InvalidRecord);
79 return StringRef((char*)&Record[Idx], Record.size() - Idx);
83 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
85 default: // Map unknown/new linkages to external
86 case 0: return GlobalValue::ExternalLinkage;
87 case 1: return GlobalValue::WeakAnyLinkage;
88 case 2: return GlobalValue::AppendingLinkage;
89 case 3: return GlobalValue::InternalLinkage;
90 case 4: return GlobalValue::LinkOnceAnyLinkage;
91 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
92 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
93 case 7: return GlobalValue::ExternalWeakLinkage;
94 case 8: return GlobalValue::CommonLinkage;
95 case 9: return GlobalValue::PrivateLinkage;
96 case 10: return GlobalValue::WeakODRLinkage;
97 case 11: return GlobalValue::LinkOnceODRLinkage;
98 case 12: return GlobalValue::AvailableExternallyLinkage;
100 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
102 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
106 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
108 default: // Map unknown visibilities to default.
109 case 0: return GlobalValue::DefaultVisibility;
110 case 1: return GlobalValue::HiddenVisibility;
111 case 2: return GlobalValue::ProtectedVisibility;
115 static GlobalValue::DLLStorageClassTypes
116 GetDecodedDLLStorageClass(unsigned Val) {
118 default: // Map unknown values to default.
119 case 0: return GlobalValue::DefaultStorageClass;
120 case 1: return GlobalValue::DLLImportStorageClass;
121 case 2: return GlobalValue::DLLExportStorageClass;
125 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
127 case 0: return GlobalVariable::NotThreadLocal;
128 default: // Map unknown non-zero value to general dynamic.
129 case 1: return GlobalVariable::GeneralDynamicTLSModel;
130 case 2: return GlobalVariable::LocalDynamicTLSModel;
131 case 3: return GlobalVariable::InitialExecTLSModel;
132 case 4: return GlobalVariable::LocalExecTLSModel;
136 static int GetDecodedCastOpcode(unsigned Val) {
139 case bitc::CAST_TRUNC : return Instruction::Trunc;
140 case bitc::CAST_ZEXT : return Instruction::ZExt;
141 case bitc::CAST_SEXT : return Instruction::SExt;
142 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
143 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
144 case bitc::CAST_UITOFP : return Instruction::UIToFP;
145 case bitc::CAST_SITOFP : return Instruction::SIToFP;
146 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
147 case bitc::CAST_FPEXT : return Instruction::FPExt;
148 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
149 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
150 case bitc::CAST_BITCAST : return Instruction::BitCast;
151 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
154 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
157 case bitc::BINOP_ADD:
158 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
159 case bitc::BINOP_SUB:
160 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
161 case bitc::BINOP_MUL:
162 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
163 case bitc::BINOP_UDIV: return Instruction::UDiv;
164 case bitc::BINOP_SDIV:
165 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
166 case bitc::BINOP_UREM: return Instruction::URem;
167 case bitc::BINOP_SREM:
168 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
169 case bitc::BINOP_SHL: return Instruction::Shl;
170 case bitc::BINOP_LSHR: return Instruction::LShr;
171 case bitc::BINOP_ASHR: return Instruction::AShr;
172 case bitc::BINOP_AND: return Instruction::And;
173 case bitc::BINOP_OR: return Instruction::Or;
174 case bitc::BINOP_XOR: return Instruction::Xor;
178 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
180 default: return AtomicRMWInst::BAD_BINOP;
181 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
182 case bitc::RMW_ADD: return AtomicRMWInst::Add;
183 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
184 case bitc::RMW_AND: return AtomicRMWInst::And;
185 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
186 case bitc::RMW_OR: return AtomicRMWInst::Or;
187 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
188 case bitc::RMW_MAX: return AtomicRMWInst::Max;
189 case bitc::RMW_MIN: return AtomicRMWInst::Min;
190 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
191 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
195 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
197 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
198 case bitc::ORDERING_UNORDERED: return Unordered;
199 case bitc::ORDERING_MONOTONIC: return Monotonic;
200 case bitc::ORDERING_ACQUIRE: return Acquire;
201 case bitc::ORDERING_RELEASE: return Release;
202 case bitc::ORDERING_ACQREL: return AcquireRelease;
203 default: // Map unknown orderings to sequentially-consistent.
204 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
208 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
210 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
211 default: // Map unknown scopes to cross-thread.
212 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
216 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
218 default: // Map unknown selection kinds to any.
219 case bitc::COMDAT_SELECTION_KIND_ANY:
221 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
222 return Comdat::ExactMatch;
223 case bitc::COMDAT_SELECTION_KIND_LARGEST:
224 return Comdat::Largest;
225 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
226 return Comdat::NoDuplicates;
227 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
228 return Comdat::SameSize;
232 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
234 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
235 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
241 /// @brief A class for maintaining the slot number definition
242 /// as a placeholder for the actual definition for forward constants defs.
243 class ConstantPlaceHolder : public ConstantExpr {
244 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
246 // allocate space for exactly one operand
247 void *operator new(size_t s) {
248 return User::operator new(s, 1);
250 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
251 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
252 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
255 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
256 static bool classof(const Value *V) {
257 return isa<ConstantExpr>(V) &&
258 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
262 /// Provide fast operand accessors
263 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
267 // FIXME: can we inherit this from ConstantExpr?
269 struct OperandTraits<ConstantPlaceHolder> :
270 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
275 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
284 WeakVH &OldV = ValuePtrs[Idx];
290 // Handle constants and non-constants (e.g. instrs) differently for
292 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
293 ResolveConstants.push_back(std::make_pair(PHC, Idx));
296 // If there was a forward reference to this value, replace it.
297 Value *PrevVal = OldV;
298 OldV->replaceAllUsesWith(V);
304 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
309 if (Value *V = ValuePtrs[Idx]) {
310 assert(Ty == V->getType() && "Type mismatch in constant table!");
311 return cast<Constant>(V);
314 // Create and return a placeholder, which will later be RAUW'd.
315 Constant *C = new ConstantPlaceHolder(Ty, Context);
320 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
324 if (Value *V = ValuePtrs[Idx]) {
325 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
329 // No type specified, must be invalid reference.
330 if (!Ty) return nullptr;
332 // Create and return a placeholder, which will later be RAUW'd.
333 Value *V = new Argument(Ty);
338 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
339 /// resolves any forward references. The idea behind this is that we sometimes
340 /// get constants (such as large arrays) which reference *many* forward ref
341 /// constants. Replacing each of these causes a lot of thrashing when
342 /// building/reuniquing the constant. Instead of doing this, we look at all the
343 /// uses and rewrite all the place holders at once for any constant that uses
345 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
346 // Sort the values by-pointer so that they are efficient to look up with a
348 std::sort(ResolveConstants.begin(), ResolveConstants.end());
350 SmallVector<Constant*, 64> NewOps;
352 while (!ResolveConstants.empty()) {
353 Value *RealVal = operator[](ResolveConstants.back().second);
354 Constant *Placeholder = ResolveConstants.back().first;
355 ResolveConstants.pop_back();
357 // Loop over all users of the placeholder, updating them to reference the
358 // new value. If they reference more than one placeholder, update them all
360 while (!Placeholder->use_empty()) {
361 auto UI = Placeholder->user_begin();
364 // If the using object isn't uniqued, just update the operands. This
365 // handles instructions and initializers for global variables.
366 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
367 UI.getUse().set(RealVal);
371 // Otherwise, we have a constant that uses the placeholder. Replace that
372 // constant with a new constant that has *all* placeholder uses updated.
373 Constant *UserC = cast<Constant>(U);
374 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
377 if (!isa<ConstantPlaceHolder>(*I)) {
378 // Not a placeholder reference.
380 } else if (*I == Placeholder) {
381 // Common case is that it just references this one placeholder.
384 // Otherwise, look up the placeholder in ResolveConstants.
385 ResolveConstantsTy::iterator It =
386 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
387 std::pair<Constant*, unsigned>(cast<Constant>(*I),
389 assert(It != ResolveConstants.end() && It->first == *I);
390 NewOp = operator[](It->second);
393 NewOps.push_back(cast<Constant>(NewOp));
396 // Make the new constant.
398 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
399 NewC = ConstantArray::get(UserCA->getType(), NewOps);
400 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
401 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
402 } else if (isa<ConstantVector>(UserC)) {
403 NewC = ConstantVector::get(NewOps);
405 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
406 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
409 UserC->replaceAllUsesWith(NewC);
410 UserC->destroyConstant();
414 // Update all ValueHandles, they should be the only users at this point.
415 Placeholder->replaceAllUsesWith(RealVal);
420 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
429 WeakVH &OldV = MDValuePtrs[Idx];
435 // If there was a forward reference to this value, replace it.
436 MDNode *PrevVal = cast<MDNode>(OldV);
437 OldV->replaceAllUsesWith(V);
438 MDNode::deleteTemporary(PrevVal);
439 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
441 MDValuePtrs[Idx] = V;
444 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
448 if (Value *V = MDValuePtrs[Idx]) {
449 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
453 // Create and return a placeholder, which will later be RAUW'd.
454 Value *V = MDNode::getTemporary(Context, None);
455 MDValuePtrs[Idx] = V;
459 Type *BitcodeReader::getTypeByID(unsigned ID) {
460 // The type table size is always specified correctly.
461 if (ID >= TypeList.size())
464 if (Type *Ty = TypeList[ID])
467 // If we have a forward reference, the only possible case is when it is to a
468 // named struct. Just create a placeholder for now.
469 return TypeList[ID] = StructType::create(Context);
473 //===----------------------------------------------------------------------===//
474 // Functions for parsing blocks from the bitcode file
475 //===----------------------------------------------------------------------===//
478 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
479 /// been decoded from the given integer. This function must stay in sync with
480 /// 'encodeLLVMAttributesForBitcode'.
481 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
482 uint64_t EncodedAttrs) {
483 // FIXME: Remove in 4.0.
485 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
486 // the bits above 31 down by 11 bits.
487 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
488 assert((!Alignment || isPowerOf2_32(Alignment)) &&
489 "Alignment must be a power of two.");
492 B.addAlignmentAttr(Alignment);
493 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
494 (EncodedAttrs & 0xffff));
497 std::error_code BitcodeReader::ParseAttributeBlock() {
498 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
499 return Error(InvalidRecord);
501 if (!MAttributes.empty())
502 return Error(InvalidMultipleBlocks);
504 SmallVector<uint64_t, 64> Record;
506 SmallVector<AttributeSet, 8> Attrs;
508 // Read all the records.
510 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
512 switch (Entry.Kind) {
513 case BitstreamEntry::SubBlock: // Handled for us already.
514 case BitstreamEntry::Error:
515 return Error(MalformedBlock);
516 case BitstreamEntry::EndBlock:
517 return std::error_code();
518 case BitstreamEntry::Record:
519 // The interesting case.
525 switch (Stream.readRecord(Entry.ID, Record)) {
526 default: // Default behavior: ignore.
528 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
529 // FIXME: Remove in 4.0.
530 if (Record.size() & 1)
531 return Error(InvalidRecord);
533 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
535 decodeLLVMAttributesForBitcode(B, Record[i+1]);
536 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
539 MAttributes.push_back(AttributeSet::get(Context, Attrs));
543 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
544 for (unsigned i = 0, e = Record.size(); i != e; ++i)
545 Attrs.push_back(MAttributeGroups[Record[i]]);
547 MAttributes.push_back(AttributeSet::get(Context, Attrs));
555 // Returns Attribute::None on unrecognized codes.
556 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
559 return Attribute::None;
560 case bitc::ATTR_KIND_ALIGNMENT:
561 return Attribute::Alignment;
562 case bitc::ATTR_KIND_ALWAYS_INLINE:
563 return Attribute::AlwaysInline;
564 case bitc::ATTR_KIND_BUILTIN:
565 return Attribute::Builtin;
566 case bitc::ATTR_KIND_BY_VAL:
567 return Attribute::ByVal;
568 case bitc::ATTR_KIND_IN_ALLOCA:
569 return Attribute::InAlloca;
570 case bitc::ATTR_KIND_COLD:
571 return Attribute::Cold;
572 case bitc::ATTR_KIND_INLINE_HINT:
573 return Attribute::InlineHint;
574 case bitc::ATTR_KIND_IN_REG:
575 return Attribute::InReg;
576 case bitc::ATTR_KIND_JUMP_TABLE:
577 return Attribute::JumpTable;
578 case bitc::ATTR_KIND_MIN_SIZE:
579 return Attribute::MinSize;
580 case bitc::ATTR_KIND_NAKED:
581 return Attribute::Naked;
582 case bitc::ATTR_KIND_NEST:
583 return Attribute::Nest;
584 case bitc::ATTR_KIND_NO_ALIAS:
585 return Attribute::NoAlias;
586 case bitc::ATTR_KIND_NO_BUILTIN:
587 return Attribute::NoBuiltin;
588 case bitc::ATTR_KIND_NO_CAPTURE:
589 return Attribute::NoCapture;
590 case bitc::ATTR_KIND_NO_DUPLICATE:
591 return Attribute::NoDuplicate;
592 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
593 return Attribute::NoImplicitFloat;
594 case bitc::ATTR_KIND_NO_INLINE:
595 return Attribute::NoInline;
596 case bitc::ATTR_KIND_NON_LAZY_BIND:
597 return Attribute::NonLazyBind;
598 case bitc::ATTR_KIND_NON_NULL:
599 return Attribute::NonNull;
600 case bitc::ATTR_KIND_NO_RED_ZONE:
601 return Attribute::NoRedZone;
602 case bitc::ATTR_KIND_NO_RETURN:
603 return Attribute::NoReturn;
604 case bitc::ATTR_KIND_NO_UNWIND:
605 return Attribute::NoUnwind;
606 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
607 return Attribute::OptimizeForSize;
608 case bitc::ATTR_KIND_OPTIMIZE_NONE:
609 return Attribute::OptimizeNone;
610 case bitc::ATTR_KIND_READ_NONE:
611 return Attribute::ReadNone;
612 case bitc::ATTR_KIND_READ_ONLY:
613 return Attribute::ReadOnly;
614 case bitc::ATTR_KIND_RETURNED:
615 return Attribute::Returned;
616 case bitc::ATTR_KIND_RETURNS_TWICE:
617 return Attribute::ReturnsTwice;
618 case bitc::ATTR_KIND_S_EXT:
619 return Attribute::SExt;
620 case bitc::ATTR_KIND_STACK_ALIGNMENT:
621 return Attribute::StackAlignment;
622 case bitc::ATTR_KIND_STACK_PROTECT:
623 return Attribute::StackProtect;
624 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
625 return Attribute::StackProtectReq;
626 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
627 return Attribute::StackProtectStrong;
628 case bitc::ATTR_KIND_STRUCT_RET:
629 return Attribute::StructRet;
630 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
631 return Attribute::SanitizeAddress;
632 case bitc::ATTR_KIND_SANITIZE_THREAD:
633 return Attribute::SanitizeThread;
634 case bitc::ATTR_KIND_SANITIZE_MEMORY:
635 return Attribute::SanitizeMemory;
636 case bitc::ATTR_KIND_UW_TABLE:
637 return Attribute::UWTable;
638 case bitc::ATTR_KIND_Z_EXT:
639 return Attribute::ZExt;
643 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
644 Attribute::AttrKind *Kind) {
645 *Kind = GetAttrFromCode(Code);
646 if (*Kind == Attribute::None)
647 return Error(InvalidValue);
648 return std::error_code();
651 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
652 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
653 return Error(InvalidRecord);
655 if (!MAttributeGroups.empty())
656 return Error(InvalidMultipleBlocks);
658 SmallVector<uint64_t, 64> Record;
660 // Read all the records.
662 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
664 switch (Entry.Kind) {
665 case BitstreamEntry::SubBlock: // Handled for us already.
666 case BitstreamEntry::Error:
667 return Error(MalformedBlock);
668 case BitstreamEntry::EndBlock:
669 return std::error_code();
670 case BitstreamEntry::Record:
671 // The interesting case.
677 switch (Stream.readRecord(Entry.ID, Record)) {
678 default: // Default behavior: ignore.
680 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
681 if (Record.size() < 3)
682 return Error(InvalidRecord);
684 uint64_t GrpID = Record[0];
685 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
688 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
689 if (Record[i] == 0) { // Enum attribute
690 Attribute::AttrKind Kind;
691 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
694 B.addAttribute(Kind);
695 } else if (Record[i] == 1) { // Align attribute
696 Attribute::AttrKind Kind;
697 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
699 if (Kind == Attribute::Alignment)
700 B.addAlignmentAttr(Record[++i]);
702 B.addStackAlignmentAttr(Record[++i]);
703 } else { // String attribute
704 assert((Record[i] == 3 || Record[i] == 4) &&
705 "Invalid attribute group entry");
706 bool HasValue = (Record[i++] == 4);
707 SmallString<64> KindStr;
708 SmallString<64> ValStr;
710 while (Record[i] != 0 && i != e)
711 KindStr += Record[i++];
712 assert(Record[i] == 0 && "Kind string not null terminated");
715 // Has a value associated with it.
716 ++i; // Skip the '0' that terminates the "kind" string.
717 while (Record[i] != 0 && i != e)
718 ValStr += Record[i++];
719 assert(Record[i] == 0 && "Value string not null terminated");
722 B.addAttribute(KindStr.str(), ValStr.str());
726 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
733 std::error_code BitcodeReader::ParseTypeTable() {
734 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
735 return Error(InvalidRecord);
737 return ParseTypeTableBody();
740 std::error_code BitcodeReader::ParseTypeTableBody() {
741 if (!TypeList.empty())
742 return Error(InvalidMultipleBlocks);
744 SmallVector<uint64_t, 64> Record;
745 unsigned NumRecords = 0;
747 SmallString<64> TypeName;
749 // Read all the records for this type table.
751 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
753 switch (Entry.Kind) {
754 case BitstreamEntry::SubBlock: // Handled for us already.
755 case BitstreamEntry::Error:
756 return Error(MalformedBlock);
757 case BitstreamEntry::EndBlock:
758 if (NumRecords != TypeList.size())
759 return Error(MalformedBlock);
760 return std::error_code();
761 case BitstreamEntry::Record:
762 // The interesting case.
768 Type *ResultTy = nullptr;
769 switch (Stream.readRecord(Entry.ID, Record)) {
771 return Error(InvalidValue);
772 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
773 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
774 // type list. This allows us to reserve space.
775 if (Record.size() < 1)
776 return Error(InvalidRecord);
777 TypeList.resize(Record[0]);
779 case bitc::TYPE_CODE_VOID: // VOID
780 ResultTy = Type::getVoidTy(Context);
782 case bitc::TYPE_CODE_HALF: // HALF
783 ResultTy = Type::getHalfTy(Context);
785 case bitc::TYPE_CODE_FLOAT: // FLOAT
786 ResultTy = Type::getFloatTy(Context);
788 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
789 ResultTy = Type::getDoubleTy(Context);
791 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
792 ResultTy = Type::getX86_FP80Ty(Context);
794 case bitc::TYPE_CODE_FP128: // FP128
795 ResultTy = Type::getFP128Ty(Context);
797 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
798 ResultTy = Type::getPPC_FP128Ty(Context);
800 case bitc::TYPE_CODE_LABEL: // LABEL
801 ResultTy = Type::getLabelTy(Context);
803 case bitc::TYPE_CODE_METADATA: // METADATA
804 ResultTy = Type::getMetadataTy(Context);
806 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
807 ResultTy = Type::getX86_MMXTy(Context);
809 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
810 if (Record.size() < 1)
811 return Error(InvalidRecord);
813 ResultTy = IntegerType::get(Context, Record[0]);
815 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
816 // [pointee type, address space]
817 if (Record.size() < 1)
818 return Error(InvalidRecord);
819 unsigned AddressSpace = 0;
820 if (Record.size() == 2)
821 AddressSpace = Record[1];
822 ResultTy = getTypeByID(Record[0]);
824 return Error(InvalidType);
825 ResultTy = PointerType::get(ResultTy, AddressSpace);
828 case bitc::TYPE_CODE_FUNCTION_OLD: {
829 // FIXME: attrid is dead, remove it in LLVM 4.0
830 // FUNCTION: [vararg, attrid, retty, paramty x N]
831 if (Record.size() < 3)
832 return Error(InvalidRecord);
833 SmallVector<Type*, 8> ArgTys;
834 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
835 if (Type *T = getTypeByID(Record[i]))
841 ResultTy = getTypeByID(Record[2]);
842 if (!ResultTy || ArgTys.size() < Record.size()-3)
843 return Error(InvalidType);
845 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
848 case bitc::TYPE_CODE_FUNCTION: {
849 // FUNCTION: [vararg, retty, paramty x N]
850 if (Record.size() < 2)
851 return Error(InvalidRecord);
852 SmallVector<Type*, 8> ArgTys;
853 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
854 if (Type *T = getTypeByID(Record[i]))
860 ResultTy = getTypeByID(Record[1]);
861 if (!ResultTy || ArgTys.size() < Record.size()-2)
862 return Error(InvalidType);
864 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
867 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
868 if (Record.size() < 1)
869 return Error(InvalidRecord);
870 SmallVector<Type*, 8> EltTys;
871 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
872 if (Type *T = getTypeByID(Record[i]))
877 if (EltTys.size() != Record.size()-1)
878 return Error(InvalidType);
879 ResultTy = StructType::get(Context, EltTys, Record[0]);
882 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
883 if (ConvertToString(Record, 0, TypeName))
884 return Error(InvalidRecord);
887 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
888 if (Record.size() < 1)
889 return Error(InvalidRecord);
891 if (NumRecords >= TypeList.size())
892 return Error(InvalidTYPETable);
894 // Check to see if this was forward referenced, if so fill in the temp.
895 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
897 Res->setName(TypeName);
898 TypeList[NumRecords] = nullptr;
899 } else // Otherwise, create a new struct.
900 Res = StructType::create(Context, TypeName);
903 SmallVector<Type*, 8> EltTys;
904 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
905 if (Type *T = getTypeByID(Record[i]))
910 if (EltTys.size() != Record.size()-1)
911 return Error(InvalidRecord);
912 Res->setBody(EltTys, Record[0]);
916 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
917 if (Record.size() != 1)
918 return Error(InvalidRecord);
920 if (NumRecords >= TypeList.size())
921 return Error(InvalidTYPETable);
923 // Check to see if this was forward referenced, if so fill in the temp.
924 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
926 Res->setName(TypeName);
927 TypeList[NumRecords] = nullptr;
928 } else // Otherwise, create a new struct with no body.
929 Res = StructType::create(Context, TypeName);
934 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
935 if (Record.size() < 2)
936 return Error(InvalidRecord);
937 if ((ResultTy = getTypeByID(Record[1])))
938 ResultTy = ArrayType::get(ResultTy, Record[0]);
940 return Error(InvalidType);
942 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
943 if (Record.size() < 2)
944 return Error(InvalidRecord);
945 if ((ResultTy = getTypeByID(Record[1])))
946 ResultTy = VectorType::get(ResultTy, Record[0]);
948 return Error(InvalidType);
952 if (NumRecords >= TypeList.size())
953 return Error(InvalidTYPETable);
954 assert(ResultTy && "Didn't read a type?");
955 assert(!TypeList[NumRecords] && "Already read type?");
956 TypeList[NumRecords++] = ResultTy;
960 std::error_code BitcodeReader::ParseValueSymbolTable() {
961 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
962 return Error(InvalidRecord);
964 SmallVector<uint64_t, 64> Record;
966 // Read all the records for this value table.
967 SmallString<128> ValueName;
969 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
971 switch (Entry.Kind) {
972 case BitstreamEntry::SubBlock: // Handled for us already.
973 case BitstreamEntry::Error:
974 return Error(MalformedBlock);
975 case BitstreamEntry::EndBlock:
976 return std::error_code();
977 case BitstreamEntry::Record:
978 // The interesting case.
984 switch (Stream.readRecord(Entry.ID, Record)) {
985 default: // Default behavior: unknown type.
987 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
988 if (ConvertToString(Record, 1, ValueName))
989 return Error(InvalidRecord);
990 unsigned ValueID = Record[0];
991 if (ValueID >= ValueList.size() || !ValueList[ValueID])
992 return Error(InvalidRecord);
993 Value *V = ValueList[ValueID];
995 V->setName(StringRef(ValueName.data(), ValueName.size()));
999 case bitc::VST_CODE_BBENTRY: {
1000 if (ConvertToString(Record, 1, ValueName))
1001 return Error(InvalidRecord);
1002 BasicBlock *BB = getBasicBlock(Record[0]);
1004 return Error(InvalidRecord);
1006 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1014 std::error_code BitcodeReader::ParseMetadata() {
1015 unsigned NextMDValueNo = MDValueList.size();
1017 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1018 return Error(InvalidRecord);
1020 SmallVector<uint64_t, 64> Record;
1022 // Read all the records.
1024 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1026 switch (Entry.Kind) {
1027 case BitstreamEntry::SubBlock: // Handled for us already.
1028 case BitstreamEntry::Error:
1029 return Error(MalformedBlock);
1030 case BitstreamEntry::EndBlock:
1031 return std::error_code();
1032 case BitstreamEntry::Record:
1033 // The interesting case.
1037 bool IsFunctionLocal = false;
1040 unsigned Code = Stream.readRecord(Entry.ID, Record);
1042 default: // Default behavior: ignore.
1044 case bitc::METADATA_NAME: {
1045 // Read name of the named metadata.
1046 SmallString<8> Name(Record.begin(), Record.end());
1048 Code = Stream.ReadCode();
1050 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1051 unsigned NextBitCode = Stream.readRecord(Code, Record);
1052 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1054 // Read named metadata elements.
1055 unsigned Size = Record.size();
1056 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1057 for (unsigned i = 0; i != Size; ++i) {
1058 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1060 return Error(InvalidRecord);
1061 NMD->addOperand(MD);
1065 case bitc::METADATA_FN_NODE:
1066 IsFunctionLocal = true;
1068 case bitc::METADATA_NODE: {
1069 if (Record.size() % 2 == 1)
1070 return Error(InvalidRecord);
1072 unsigned Size = Record.size();
1073 SmallVector<Value*, 8> Elts;
1074 for (unsigned i = 0; i != Size; i += 2) {
1075 Type *Ty = getTypeByID(Record[i]);
1077 return Error(InvalidRecord);
1078 if (Ty->isMetadataTy())
1079 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1080 else if (!Ty->isVoidTy())
1081 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1083 Elts.push_back(nullptr);
1085 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1086 IsFunctionLocal = false;
1087 MDValueList.AssignValue(V, NextMDValueNo++);
1090 case bitc::METADATA_STRING: {
1091 std::string String(Record.begin(), Record.end());
1092 llvm::UpgradeMDStringConstant(String);
1093 Value *V = MDString::get(Context, String);
1094 MDValueList.AssignValue(V, NextMDValueNo++);
1097 case bitc::METADATA_KIND: {
1098 if (Record.size() < 2)
1099 return Error(InvalidRecord);
1101 unsigned Kind = Record[0];
1102 SmallString<8> Name(Record.begin()+1, Record.end());
1104 unsigned NewKind = TheModule->getMDKindID(Name.str());
1105 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1106 return Error(ConflictingMETADATA_KINDRecords);
1113 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1114 /// the LSB for dense VBR encoding.
1115 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1120 // There is no such thing as -0 with integers. "-0" really means MININT.
1124 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1125 /// values and aliases that we can.
1126 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1127 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1128 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1129 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1131 GlobalInitWorklist.swap(GlobalInits);
1132 AliasInitWorklist.swap(AliasInits);
1133 FunctionPrefixWorklist.swap(FunctionPrefixes);
1135 while (!GlobalInitWorklist.empty()) {
1136 unsigned ValID = GlobalInitWorklist.back().second;
1137 if (ValID >= ValueList.size()) {
1138 // Not ready to resolve this yet, it requires something later in the file.
1139 GlobalInits.push_back(GlobalInitWorklist.back());
1141 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1142 GlobalInitWorklist.back().first->setInitializer(C);
1144 return Error(ExpectedConstant);
1146 GlobalInitWorklist.pop_back();
1149 while (!AliasInitWorklist.empty()) {
1150 unsigned ValID = AliasInitWorklist.back().second;
1151 if (ValID >= ValueList.size()) {
1152 AliasInits.push_back(AliasInitWorklist.back());
1154 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1155 AliasInitWorklist.back().first->setAliasee(C);
1157 return Error(ExpectedConstant);
1159 AliasInitWorklist.pop_back();
1162 while (!FunctionPrefixWorklist.empty()) {
1163 unsigned ValID = FunctionPrefixWorklist.back().second;
1164 if (ValID >= ValueList.size()) {
1165 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1167 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1168 FunctionPrefixWorklist.back().first->setPrefixData(C);
1170 return Error(ExpectedConstant);
1172 FunctionPrefixWorklist.pop_back();
1175 return std::error_code();
1178 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1179 SmallVector<uint64_t, 8> Words(Vals.size());
1180 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1181 BitcodeReader::decodeSignRotatedValue);
1183 return APInt(TypeBits, Words);
1186 std::error_code BitcodeReader::ParseConstants() {
1187 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1188 return Error(InvalidRecord);
1190 SmallVector<uint64_t, 64> Record;
1192 // Read all the records for this value table.
1193 Type *CurTy = Type::getInt32Ty(Context);
1194 unsigned NextCstNo = ValueList.size();
1196 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1198 switch (Entry.Kind) {
1199 case BitstreamEntry::SubBlock: // Handled for us already.
1200 case BitstreamEntry::Error:
1201 return Error(MalformedBlock);
1202 case BitstreamEntry::EndBlock:
1203 if (NextCstNo != ValueList.size())
1204 return Error(InvalidConstantReference);
1206 // Once all the constants have been read, go through and resolve forward
1208 ValueList.ResolveConstantForwardRefs();
1209 return std::error_code();
1210 case BitstreamEntry::Record:
1211 // The interesting case.
1218 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1220 default: // Default behavior: unknown constant
1221 case bitc::CST_CODE_UNDEF: // UNDEF
1222 V = UndefValue::get(CurTy);
1224 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1226 return Error(InvalidRecord);
1227 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1228 return Error(InvalidRecord);
1229 CurTy = TypeList[Record[0]];
1230 continue; // Skip the ValueList manipulation.
1231 case bitc::CST_CODE_NULL: // NULL
1232 V = Constant::getNullValue(CurTy);
1234 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1235 if (!CurTy->isIntegerTy() || Record.empty())
1236 return Error(InvalidRecord);
1237 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1239 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1240 if (!CurTy->isIntegerTy() || Record.empty())
1241 return Error(InvalidRecord);
1243 APInt VInt = ReadWideAPInt(Record,
1244 cast<IntegerType>(CurTy)->getBitWidth());
1245 V = ConstantInt::get(Context, VInt);
1249 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1251 return Error(InvalidRecord);
1252 if (CurTy->isHalfTy())
1253 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1254 APInt(16, (uint16_t)Record[0])));
1255 else if (CurTy->isFloatTy())
1256 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1257 APInt(32, (uint32_t)Record[0])));
1258 else if (CurTy->isDoubleTy())
1259 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1260 APInt(64, Record[0])));
1261 else if (CurTy->isX86_FP80Ty()) {
1262 // Bits are not stored the same way as a normal i80 APInt, compensate.
1263 uint64_t Rearrange[2];
1264 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1265 Rearrange[1] = Record[0] >> 48;
1266 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1267 APInt(80, Rearrange)));
1268 } else if (CurTy->isFP128Ty())
1269 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1270 APInt(128, Record)));
1271 else if (CurTy->isPPC_FP128Ty())
1272 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1273 APInt(128, Record)));
1275 V = UndefValue::get(CurTy);
1279 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1281 return Error(InvalidRecord);
1283 unsigned Size = Record.size();
1284 SmallVector<Constant*, 16> Elts;
1286 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1287 for (unsigned i = 0; i != Size; ++i)
1288 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1289 STy->getElementType(i)));
1290 V = ConstantStruct::get(STy, Elts);
1291 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1292 Type *EltTy = ATy->getElementType();
1293 for (unsigned i = 0; i != Size; ++i)
1294 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1295 V = ConstantArray::get(ATy, Elts);
1296 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1297 Type *EltTy = VTy->getElementType();
1298 for (unsigned i = 0; i != Size; ++i)
1299 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1300 V = ConstantVector::get(Elts);
1302 V = UndefValue::get(CurTy);
1306 case bitc::CST_CODE_STRING: // STRING: [values]
1307 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1309 return Error(InvalidRecord);
1311 SmallString<16> Elts(Record.begin(), Record.end());
1312 V = ConstantDataArray::getString(Context, Elts,
1313 BitCode == bitc::CST_CODE_CSTRING);
1316 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1318 return Error(InvalidRecord);
1320 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1321 unsigned Size = Record.size();
1323 if (EltTy->isIntegerTy(8)) {
1324 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1325 if (isa<VectorType>(CurTy))
1326 V = ConstantDataVector::get(Context, Elts);
1328 V = ConstantDataArray::get(Context, Elts);
1329 } else if (EltTy->isIntegerTy(16)) {
1330 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1331 if (isa<VectorType>(CurTy))
1332 V = ConstantDataVector::get(Context, Elts);
1334 V = ConstantDataArray::get(Context, Elts);
1335 } else if (EltTy->isIntegerTy(32)) {
1336 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1337 if (isa<VectorType>(CurTy))
1338 V = ConstantDataVector::get(Context, Elts);
1340 V = ConstantDataArray::get(Context, Elts);
1341 } else if (EltTy->isIntegerTy(64)) {
1342 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1343 if (isa<VectorType>(CurTy))
1344 V = ConstantDataVector::get(Context, Elts);
1346 V = ConstantDataArray::get(Context, Elts);
1347 } else if (EltTy->isFloatTy()) {
1348 SmallVector<float, 16> Elts(Size);
1349 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1350 if (isa<VectorType>(CurTy))
1351 V = ConstantDataVector::get(Context, Elts);
1353 V = ConstantDataArray::get(Context, Elts);
1354 } else if (EltTy->isDoubleTy()) {
1355 SmallVector<double, 16> Elts(Size);
1356 std::transform(Record.begin(), Record.end(), Elts.begin(),
1358 if (isa<VectorType>(CurTy))
1359 V = ConstantDataVector::get(Context, Elts);
1361 V = ConstantDataArray::get(Context, Elts);
1363 return Error(InvalidTypeForValue);
1368 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1369 if (Record.size() < 3)
1370 return Error(InvalidRecord);
1371 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1373 V = UndefValue::get(CurTy); // Unknown binop.
1375 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1376 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1378 if (Record.size() >= 4) {
1379 if (Opc == Instruction::Add ||
1380 Opc == Instruction::Sub ||
1381 Opc == Instruction::Mul ||
1382 Opc == Instruction::Shl) {
1383 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1384 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1385 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1386 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1387 } else if (Opc == Instruction::SDiv ||
1388 Opc == Instruction::UDiv ||
1389 Opc == Instruction::LShr ||
1390 Opc == Instruction::AShr) {
1391 if (Record[3] & (1 << bitc::PEO_EXACT))
1392 Flags |= SDivOperator::IsExact;
1395 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1399 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1400 if (Record.size() < 3)
1401 return Error(InvalidRecord);
1402 int Opc = GetDecodedCastOpcode(Record[0]);
1404 V = UndefValue::get(CurTy); // Unknown cast.
1406 Type *OpTy = getTypeByID(Record[1]);
1408 return Error(InvalidRecord);
1409 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1410 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1411 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1415 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1416 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1417 if (Record.size() & 1)
1418 return Error(InvalidRecord);
1419 SmallVector<Constant*, 16> Elts;
1420 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1421 Type *ElTy = getTypeByID(Record[i]);
1423 return Error(InvalidRecord);
1424 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1426 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1427 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1429 bitc::CST_CODE_CE_INBOUNDS_GEP);
1432 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1433 if (Record.size() < 3)
1434 return Error(InvalidRecord);
1436 Type *SelectorTy = Type::getInt1Ty(Context);
1438 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1439 // vector. Otherwise, it must be a single bit.
1440 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1441 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1442 VTy->getNumElements());
1444 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1446 ValueList.getConstantFwdRef(Record[1],CurTy),
1447 ValueList.getConstantFwdRef(Record[2],CurTy));
1450 case bitc::CST_CODE_CE_EXTRACTELT
1451 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1452 if (Record.size() < 3)
1453 return Error(InvalidRecord);
1455 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1457 return Error(InvalidRecord);
1458 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1459 Constant *Op1 = nullptr;
1460 if (Record.size() == 4) {
1461 Type *IdxTy = getTypeByID(Record[2]);
1463 return Error(InvalidRecord);
1464 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1465 } else // TODO: Remove with llvm 4.0
1466 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1468 return Error(InvalidRecord);
1469 V = ConstantExpr::getExtractElement(Op0, Op1);
1472 case bitc::CST_CODE_CE_INSERTELT
1473 : { // CE_INSERTELT: [opval, opval, opty, opval]
1474 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1475 if (Record.size() < 3 || !OpTy)
1476 return Error(InvalidRecord);
1477 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1478 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1479 OpTy->getElementType());
1480 Constant *Op2 = nullptr;
1481 if (Record.size() == 4) {
1482 Type *IdxTy = getTypeByID(Record[2]);
1484 return Error(InvalidRecord);
1485 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1486 } else // TODO: Remove with llvm 4.0
1487 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1489 return Error(InvalidRecord);
1490 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1493 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1494 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1495 if (Record.size() < 3 || !OpTy)
1496 return Error(InvalidRecord);
1497 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1498 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1499 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1500 OpTy->getNumElements());
1501 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1502 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1505 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1506 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1508 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1509 if (Record.size() < 4 || !RTy || !OpTy)
1510 return Error(InvalidRecord);
1511 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1512 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1513 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1514 RTy->getNumElements());
1515 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1516 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1519 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1520 if (Record.size() < 4)
1521 return Error(InvalidRecord);
1522 Type *OpTy = getTypeByID(Record[0]);
1524 return Error(InvalidRecord);
1525 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1526 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1528 if (OpTy->isFPOrFPVectorTy())
1529 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1531 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1534 // This maintains backward compatibility, pre-asm dialect keywords.
1535 // FIXME: Remove with the 4.0 release.
1536 case bitc::CST_CODE_INLINEASM_OLD: {
1537 if (Record.size() < 2)
1538 return Error(InvalidRecord);
1539 std::string AsmStr, ConstrStr;
1540 bool HasSideEffects = Record[0] & 1;
1541 bool IsAlignStack = Record[0] >> 1;
1542 unsigned AsmStrSize = Record[1];
1543 if (2+AsmStrSize >= Record.size())
1544 return Error(InvalidRecord);
1545 unsigned ConstStrSize = Record[2+AsmStrSize];
1546 if (3+AsmStrSize+ConstStrSize > Record.size())
1547 return Error(InvalidRecord);
1549 for (unsigned i = 0; i != AsmStrSize; ++i)
1550 AsmStr += (char)Record[2+i];
1551 for (unsigned i = 0; i != ConstStrSize; ++i)
1552 ConstrStr += (char)Record[3+AsmStrSize+i];
1553 PointerType *PTy = cast<PointerType>(CurTy);
1554 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1555 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1558 // This version adds support for the asm dialect keywords (e.g.,
1560 case bitc::CST_CODE_INLINEASM: {
1561 if (Record.size() < 2)
1562 return Error(InvalidRecord);
1563 std::string AsmStr, ConstrStr;
1564 bool HasSideEffects = Record[0] & 1;
1565 bool IsAlignStack = (Record[0] >> 1) & 1;
1566 unsigned AsmDialect = Record[0] >> 2;
1567 unsigned AsmStrSize = Record[1];
1568 if (2+AsmStrSize >= Record.size())
1569 return Error(InvalidRecord);
1570 unsigned ConstStrSize = Record[2+AsmStrSize];
1571 if (3+AsmStrSize+ConstStrSize > Record.size())
1572 return Error(InvalidRecord);
1574 for (unsigned i = 0; i != AsmStrSize; ++i)
1575 AsmStr += (char)Record[2+i];
1576 for (unsigned i = 0; i != ConstStrSize; ++i)
1577 ConstrStr += (char)Record[3+AsmStrSize+i];
1578 PointerType *PTy = cast<PointerType>(CurTy);
1579 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1580 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1581 InlineAsm::AsmDialect(AsmDialect));
1584 case bitc::CST_CODE_BLOCKADDRESS:{
1585 if (Record.size() < 3)
1586 return Error(InvalidRecord);
1587 Type *FnTy = getTypeByID(Record[0]);
1589 return Error(InvalidRecord);
1591 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1593 return Error(InvalidRecord);
1595 // If the function is already parsed we can insert the block address right
1598 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1599 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1601 return Error(InvalidID);
1604 V = BlockAddress::get(Fn, BBI);
1606 // Otherwise insert a placeholder and remember it so it can be inserted
1607 // when the function is parsed.
1608 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1609 Type::getInt8Ty(Context),
1610 false, GlobalValue::InternalLinkage,
1612 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1619 ValueList.AssignValue(V, NextCstNo);
1624 std::error_code BitcodeReader::ParseUseLists() {
1625 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1626 return Error(InvalidRecord);
1628 SmallVector<uint64_t, 64> Record;
1630 // Read all the records.
1632 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1634 switch (Entry.Kind) {
1635 case BitstreamEntry::SubBlock: // Handled for us already.
1636 case BitstreamEntry::Error:
1637 return Error(MalformedBlock);
1638 case BitstreamEntry::EndBlock:
1639 return std::error_code();
1640 case BitstreamEntry::Record:
1641 // The interesting case.
1645 // Read a use list record.
1647 switch (Stream.readRecord(Entry.ID, Record)) {
1648 default: // Default behavior: unknown type.
1650 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1651 unsigned RecordLength = Record.size();
1652 if (RecordLength < 1)
1653 return Error(InvalidRecord);
1654 UseListRecords.push_back(Record);
1661 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1662 /// remember where it is and then skip it. This lets us lazily deserialize the
1664 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1665 // Get the function we are talking about.
1666 if (FunctionsWithBodies.empty())
1667 return Error(InsufficientFunctionProtos);
1669 Function *Fn = FunctionsWithBodies.back();
1670 FunctionsWithBodies.pop_back();
1672 // Save the current stream state.
1673 uint64_t CurBit = Stream.GetCurrentBitNo();
1674 DeferredFunctionInfo[Fn] = CurBit;
1676 // Skip over the function block for now.
1677 if (Stream.SkipBlock())
1678 return Error(InvalidRecord);
1679 return std::error_code();
1682 std::error_code BitcodeReader::GlobalCleanup() {
1683 // Patch the initializers for globals and aliases up.
1684 ResolveGlobalAndAliasInits();
1685 if (!GlobalInits.empty() || !AliasInits.empty())
1686 return Error(MalformedGlobalInitializerSet);
1688 // Look for intrinsic functions which need to be upgraded at some point
1689 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1692 if (UpgradeIntrinsicFunction(FI, NewFn))
1693 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1696 // Look for global variables which need to be renamed.
1697 for (Module::global_iterator
1698 GI = TheModule->global_begin(), GE = TheModule->global_end();
1700 GlobalVariable *GV = GI++;
1701 UpgradeGlobalVariable(GV);
1704 // Force deallocation of memory for these vectors to favor the client that
1705 // want lazy deserialization.
1706 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1707 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1708 return std::error_code();
1711 std::error_code BitcodeReader::ParseModule(bool Resume) {
1713 Stream.JumpToBit(NextUnreadBit);
1714 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1715 return Error(InvalidRecord);
1717 SmallVector<uint64_t, 64> Record;
1718 std::vector<std::string> SectionTable;
1719 std::vector<std::string> GCTable;
1721 // Read all the records for this module.
1723 BitstreamEntry Entry = Stream.advance();
1725 switch (Entry.Kind) {
1726 case BitstreamEntry::Error:
1727 return Error(MalformedBlock);
1728 case BitstreamEntry::EndBlock:
1729 return GlobalCleanup();
1731 case BitstreamEntry::SubBlock:
1733 default: // Skip unknown content.
1734 if (Stream.SkipBlock())
1735 return Error(InvalidRecord);
1737 case bitc::BLOCKINFO_BLOCK_ID:
1738 if (Stream.ReadBlockInfoBlock())
1739 return Error(MalformedBlock);
1741 case bitc::PARAMATTR_BLOCK_ID:
1742 if (std::error_code EC = ParseAttributeBlock())
1745 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1746 if (std::error_code EC = ParseAttributeGroupBlock())
1749 case bitc::TYPE_BLOCK_ID_NEW:
1750 if (std::error_code EC = ParseTypeTable())
1753 case bitc::VALUE_SYMTAB_BLOCK_ID:
1754 if (std::error_code EC = ParseValueSymbolTable())
1756 SeenValueSymbolTable = true;
1758 case bitc::CONSTANTS_BLOCK_ID:
1759 if (std::error_code EC = ParseConstants())
1761 if (std::error_code EC = ResolveGlobalAndAliasInits())
1764 case bitc::METADATA_BLOCK_ID:
1765 if (std::error_code EC = ParseMetadata())
1768 case bitc::FUNCTION_BLOCK_ID:
1769 // If this is the first function body we've seen, reverse the
1770 // FunctionsWithBodies list.
1771 if (!SeenFirstFunctionBody) {
1772 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1773 if (std::error_code EC = GlobalCleanup())
1775 SeenFirstFunctionBody = true;
1778 if (std::error_code EC = RememberAndSkipFunctionBody())
1780 // For streaming bitcode, suspend parsing when we reach the function
1781 // bodies. Subsequent materialization calls will resume it when
1782 // necessary. For streaming, the function bodies must be at the end of
1783 // the bitcode. If the bitcode file is old, the symbol table will be
1784 // at the end instead and will not have been seen yet. In this case,
1785 // just finish the parse now.
1786 if (LazyStreamer && SeenValueSymbolTable) {
1787 NextUnreadBit = Stream.GetCurrentBitNo();
1788 return std::error_code();
1791 case bitc::USELIST_BLOCK_ID:
1792 if (std::error_code EC = ParseUseLists())
1798 case BitstreamEntry::Record:
1799 // The interesting case.
1805 switch (Stream.readRecord(Entry.ID, Record)) {
1806 default: break; // Default behavior, ignore unknown content.
1807 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1808 if (Record.size() < 1)
1809 return Error(InvalidRecord);
1810 // Only version #0 and #1 are supported so far.
1811 unsigned module_version = Record[0];
1812 switch (module_version) {
1814 return Error(InvalidValue);
1816 UseRelativeIDs = false;
1819 UseRelativeIDs = true;
1824 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1826 if (ConvertToString(Record, 0, S))
1827 return Error(InvalidRecord);
1828 TheModule->setTargetTriple(S);
1831 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1833 if (ConvertToString(Record, 0, S))
1834 return Error(InvalidRecord);
1835 TheModule->setDataLayout(S);
1838 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1840 if (ConvertToString(Record, 0, S))
1841 return Error(InvalidRecord);
1842 TheModule->setModuleInlineAsm(S);
1845 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1846 // FIXME: Remove in 4.0.
1848 if (ConvertToString(Record, 0, S))
1849 return Error(InvalidRecord);
1853 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1855 if (ConvertToString(Record, 0, S))
1856 return Error(InvalidRecord);
1857 SectionTable.push_back(S);
1860 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1862 if (ConvertToString(Record, 0, S))
1863 return Error(InvalidRecord);
1864 GCTable.push_back(S);
1867 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1868 if (Record.size() < 2)
1869 return Error(InvalidRecord);
1870 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1871 unsigned ComdatNameSize = Record[1];
1872 std::string ComdatName;
1873 ComdatName.reserve(ComdatNameSize);
1874 for (unsigned i = 0; i != ComdatNameSize; ++i)
1875 ComdatName += (char)Record[2 + i];
1876 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1877 C->setSelectionKind(SK);
1878 ComdatList.push_back(C);
1881 // GLOBALVAR: [pointer type, isconst, initid,
1882 // linkage, alignment, section, visibility, threadlocal,
1883 // unnamed_addr, dllstorageclass]
1884 case bitc::MODULE_CODE_GLOBALVAR: {
1885 if (Record.size() < 6)
1886 return Error(InvalidRecord);
1887 Type *Ty = getTypeByID(Record[0]);
1889 return Error(InvalidRecord);
1890 if (!Ty->isPointerTy())
1891 return Error(InvalidTypeForValue);
1892 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1893 Ty = cast<PointerType>(Ty)->getElementType();
1895 bool isConstant = Record[1];
1896 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1897 unsigned Alignment = (1 << Record[4]) >> 1;
1898 std::string Section;
1900 if (Record[5]-1 >= SectionTable.size())
1901 return Error(InvalidID);
1902 Section = SectionTable[Record[5]-1];
1904 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1905 // Local linkage must have default visibility.
1906 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1907 // FIXME: Change to an error if non-default in 4.0.
1908 Visibility = GetDecodedVisibility(Record[6]);
1910 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1911 if (Record.size() > 7)
1912 TLM = GetDecodedThreadLocalMode(Record[7]);
1914 bool UnnamedAddr = false;
1915 if (Record.size() > 8)
1916 UnnamedAddr = Record[8];
1918 bool ExternallyInitialized = false;
1919 if (Record.size() > 9)
1920 ExternallyInitialized = Record[9];
1922 GlobalVariable *NewGV =
1923 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1924 TLM, AddressSpace, ExternallyInitialized);
1925 NewGV->setAlignment(Alignment);
1926 if (!Section.empty())
1927 NewGV->setSection(Section);
1928 NewGV->setVisibility(Visibility);
1929 NewGV->setUnnamedAddr(UnnamedAddr);
1931 if (Record.size() > 10)
1932 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1934 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1936 ValueList.push_back(NewGV);
1938 // Remember which value to use for the global initializer.
1939 if (unsigned InitID = Record[2])
1940 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1942 if (Record.size() > 11)
1943 if (unsigned ComdatID = Record[11]) {
1944 assert(ComdatID <= ComdatList.size());
1945 NewGV->setComdat(ComdatList[ComdatID - 1]);
1949 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1950 // alignment, section, visibility, gc, unnamed_addr,
1952 case bitc::MODULE_CODE_FUNCTION: {
1953 if (Record.size() < 8)
1954 return Error(InvalidRecord);
1955 Type *Ty = getTypeByID(Record[0]);
1957 return Error(InvalidRecord);
1958 if (!Ty->isPointerTy())
1959 return Error(InvalidTypeForValue);
1961 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1963 return Error(InvalidTypeForValue);
1965 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1968 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1969 bool isProto = Record[2];
1970 Func->setLinkage(GetDecodedLinkage(Record[3]));
1971 Func->setAttributes(getAttributes(Record[4]));
1973 Func->setAlignment((1 << Record[5]) >> 1);
1975 if (Record[6]-1 >= SectionTable.size())
1976 return Error(InvalidID);
1977 Func->setSection(SectionTable[Record[6]-1]);
1979 // Local linkage must have default visibility.
1980 if (!Func->hasLocalLinkage())
1981 // FIXME: Change to an error if non-default in 4.0.
1982 Func->setVisibility(GetDecodedVisibility(Record[7]));
1983 if (Record.size() > 8 && Record[8]) {
1984 if (Record[8]-1 > GCTable.size())
1985 return Error(InvalidID);
1986 Func->setGC(GCTable[Record[8]-1].c_str());
1988 bool UnnamedAddr = false;
1989 if (Record.size() > 9)
1990 UnnamedAddr = Record[9];
1991 Func->setUnnamedAddr(UnnamedAddr);
1992 if (Record.size() > 10 && Record[10] != 0)
1993 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1995 if (Record.size() > 11)
1996 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1998 UpgradeDLLImportExportLinkage(Func, Record[3]);
2000 if (Record.size() > 12)
2001 if (unsigned ComdatID = Record[12]) {
2002 assert(ComdatID <= ComdatList.size());
2003 Func->setComdat(ComdatList[ComdatID - 1]);
2006 ValueList.push_back(Func);
2008 // If this is a function with a body, remember the prototype we are
2009 // creating now, so that we can match up the body with them later.
2011 FunctionsWithBodies.push_back(Func);
2012 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
2016 // ALIAS: [alias type, aliasee val#, linkage]
2017 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2018 case bitc::MODULE_CODE_ALIAS: {
2019 if (Record.size() < 3)
2020 return Error(InvalidRecord);
2021 Type *Ty = getTypeByID(Record[0]);
2023 return Error(InvalidRecord);
2024 auto *PTy = dyn_cast<PointerType>(Ty);
2026 return Error(InvalidTypeForValue);
2029 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2030 GetDecodedLinkage(Record[2]), "", TheModule);
2031 // Old bitcode files didn't have visibility field.
2032 // Local linkage must have default visibility.
2033 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2034 // FIXME: Change to an error if non-default in 4.0.
2035 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2036 if (Record.size() > 4)
2037 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2039 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2040 if (Record.size() > 5)
2041 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2042 if (Record.size() > 6)
2043 NewGA->setUnnamedAddr(Record[6]);
2044 ValueList.push_back(NewGA);
2045 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2048 /// MODULE_CODE_PURGEVALS: [numvals]
2049 case bitc::MODULE_CODE_PURGEVALS:
2050 // Trim down the value list to the specified size.
2051 if (Record.size() < 1 || Record[0] > ValueList.size())
2052 return Error(InvalidRecord);
2053 ValueList.shrinkTo(Record[0]);
2060 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2061 TheModule = nullptr;
2063 if (std::error_code EC = InitStream())
2066 // Sniff for the signature.
2067 if (Stream.Read(8) != 'B' ||
2068 Stream.Read(8) != 'C' ||
2069 Stream.Read(4) != 0x0 ||
2070 Stream.Read(4) != 0xC ||
2071 Stream.Read(4) != 0xE ||
2072 Stream.Read(4) != 0xD)
2073 return Error(InvalidBitcodeSignature);
2075 // We expect a number of well-defined blocks, though we don't necessarily
2076 // need to understand them all.
2078 if (Stream.AtEndOfStream())
2079 return std::error_code();
2081 BitstreamEntry Entry =
2082 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2084 switch (Entry.Kind) {
2085 case BitstreamEntry::Error:
2086 return Error(MalformedBlock);
2087 case BitstreamEntry::EndBlock:
2088 return std::error_code();
2090 case BitstreamEntry::SubBlock:
2092 case bitc::BLOCKINFO_BLOCK_ID:
2093 if (Stream.ReadBlockInfoBlock())
2094 return Error(MalformedBlock);
2096 case bitc::MODULE_BLOCK_ID:
2097 // Reject multiple MODULE_BLOCK's in a single bitstream.
2099 return Error(InvalidMultipleBlocks);
2101 if (std::error_code EC = ParseModule(false))
2104 return std::error_code();
2107 if (Stream.SkipBlock())
2108 return Error(InvalidRecord);
2112 case BitstreamEntry::Record:
2113 // There should be no records in the top-level of blocks.
2115 // The ranlib in Xcode 4 will align archive members by appending newlines
2116 // to the end of them. If this file size is a multiple of 4 but not 8, we
2117 // have to read and ignore these final 4 bytes :-(
2118 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2119 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2120 Stream.AtEndOfStream())
2121 return std::error_code();
2123 return Error(InvalidRecord);
2128 ErrorOr<StringRef> BitcodeReader::parseModuleTriple() {
2129 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2130 return Error(InvalidRecord);
2132 SmallVector<uint64_t, 64> Record;
2135 // Read all the records for this module.
2137 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2139 switch (Entry.Kind) {
2140 case BitstreamEntry::SubBlock: // Handled for us already.
2141 case BitstreamEntry::Error:
2142 return Error(MalformedBlock);
2143 case BitstreamEntry::EndBlock:
2144 return std::error_code();
2145 case BitstreamEntry::Record:
2146 // The interesting case.
2151 switch (Stream.readRecord(Entry.ID, Record)) {
2152 default: break; // Default behavior, ignore unknown content.
2153 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2154 ErrorOr<StringRef> S = convertToStringRef(Record, 0);
2155 if (std::error_code EC = S.getError())
2166 ErrorOr<StringRef> BitcodeReader::parseTriple() {
2167 if (std::error_code EC = InitStream())
2170 // Sniff for the signature.
2171 if (Stream.Read(8) != 'B' ||
2172 Stream.Read(8) != 'C' ||
2173 Stream.Read(4) != 0x0 ||
2174 Stream.Read(4) != 0xC ||
2175 Stream.Read(4) != 0xE ||
2176 Stream.Read(4) != 0xD)
2177 return Error(InvalidBitcodeSignature);
2179 // We expect a number of well-defined blocks, though we don't necessarily
2180 // need to understand them all.
2182 BitstreamEntry Entry = Stream.advance();
2184 switch (Entry.Kind) {
2185 case BitstreamEntry::Error:
2186 return Error(MalformedBlock);
2187 case BitstreamEntry::EndBlock:
2188 return std::error_code();
2190 case BitstreamEntry::SubBlock:
2191 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2192 return parseModuleTriple();
2194 // Ignore other sub-blocks.
2195 if (Stream.SkipBlock())
2196 return Error(MalformedBlock);
2199 case BitstreamEntry::Record:
2200 Stream.skipRecord(Entry.ID);
2206 /// ParseMetadataAttachment - Parse metadata attachments.
2207 std::error_code BitcodeReader::ParseMetadataAttachment() {
2208 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2209 return Error(InvalidRecord);
2211 SmallVector<uint64_t, 64> Record;
2213 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2215 switch (Entry.Kind) {
2216 case BitstreamEntry::SubBlock: // Handled for us already.
2217 case BitstreamEntry::Error:
2218 return Error(MalformedBlock);
2219 case BitstreamEntry::EndBlock:
2220 return std::error_code();
2221 case BitstreamEntry::Record:
2222 // The interesting case.
2226 // Read a metadata attachment record.
2228 switch (Stream.readRecord(Entry.ID, Record)) {
2229 default: // Default behavior: ignore.
2231 case bitc::METADATA_ATTACHMENT: {
2232 unsigned RecordLength = Record.size();
2233 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2234 return Error(InvalidRecord);
2235 Instruction *Inst = InstructionList[Record[0]];
2236 for (unsigned i = 1; i != RecordLength; i = i+2) {
2237 unsigned Kind = Record[i];
2238 DenseMap<unsigned, unsigned>::iterator I =
2239 MDKindMap.find(Kind);
2240 if (I == MDKindMap.end())
2241 return Error(InvalidID);
2242 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2243 Inst->setMetadata(I->second, cast<MDNode>(Node));
2244 if (I->second == LLVMContext::MD_tbaa)
2245 InstsWithTBAATag.push_back(Inst);
2253 /// ParseFunctionBody - Lazily parse the specified function body block.
2254 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2255 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2256 return Error(InvalidRecord);
2258 InstructionList.clear();
2259 unsigned ModuleValueListSize = ValueList.size();
2260 unsigned ModuleMDValueListSize = MDValueList.size();
2262 // Add all the function arguments to the value table.
2263 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2264 ValueList.push_back(I);
2266 unsigned NextValueNo = ValueList.size();
2267 BasicBlock *CurBB = nullptr;
2268 unsigned CurBBNo = 0;
2272 // Read all the records.
2273 SmallVector<uint64_t, 64> Record;
2275 BitstreamEntry Entry = Stream.advance();
2277 switch (Entry.Kind) {
2278 case BitstreamEntry::Error:
2279 return Error(MalformedBlock);
2280 case BitstreamEntry::EndBlock:
2281 goto OutOfRecordLoop;
2283 case BitstreamEntry::SubBlock:
2285 default: // Skip unknown content.
2286 if (Stream.SkipBlock())
2287 return Error(InvalidRecord);
2289 case bitc::CONSTANTS_BLOCK_ID:
2290 if (std::error_code EC = ParseConstants())
2292 NextValueNo = ValueList.size();
2294 case bitc::VALUE_SYMTAB_BLOCK_ID:
2295 if (std::error_code EC = ParseValueSymbolTable())
2298 case bitc::METADATA_ATTACHMENT_ID:
2299 if (std::error_code EC = ParseMetadataAttachment())
2302 case bitc::METADATA_BLOCK_ID:
2303 if (std::error_code EC = ParseMetadata())
2309 case BitstreamEntry::Record:
2310 // The interesting case.
2316 Instruction *I = nullptr;
2317 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2319 default: // Default behavior: reject
2320 return Error(InvalidValue);
2321 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2322 if (Record.size() < 1 || Record[0] == 0)
2323 return Error(InvalidRecord);
2324 // Create all the basic blocks for the function.
2325 FunctionBBs.resize(Record[0]);
2326 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2327 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2328 CurBB = FunctionBBs[0];
2331 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2332 // This record indicates that the last instruction is at the same
2333 // location as the previous instruction with a location.
2336 // Get the last instruction emitted.
2337 if (CurBB && !CurBB->empty())
2339 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2340 !FunctionBBs[CurBBNo-1]->empty())
2341 I = &FunctionBBs[CurBBNo-1]->back();
2344 return Error(InvalidRecord);
2345 I->setDebugLoc(LastLoc);
2349 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2350 I = nullptr; // Get the last instruction emitted.
2351 if (CurBB && !CurBB->empty())
2353 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2354 !FunctionBBs[CurBBNo-1]->empty())
2355 I = &FunctionBBs[CurBBNo-1]->back();
2356 if (!I || Record.size() < 4)
2357 return Error(InvalidRecord);
2359 unsigned Line = Record[0], Col = Record[1];
2360 unsigned ScopeID = Record[2], IAID = Record[3];
2362 MDNode *Scope = nullptr, *IA = nullptr;
2363 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2364 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2365 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2366 I->setDebugLoc(LastLoc);
2371 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2374 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2375 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2376 OpNum+1 > Record.size())
2377 return Error(InvalidRecord);
2379 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2381 return Error(InvalidRecord);
2382 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2383 InstructionList.push_back(I);
2384 if (OpNum < Record.size()) {
2385 if (Opc == Instruction::Add ||
2386 Opc == Instruction::Sub ||
2387 Opc == Instruction::Mul ||
2388 Opc == Instruction::Shl) {
2389 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2390 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2391 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2392 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2393 } else if (Opc == Instruction::SDiv ||
2394 Opc == Instruction::UDiv ||
2395 Opc == Instruction::LShr ||
2396 Opc == Instruction::AShr) {
2397 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2398 cast<BinaryOperator>(I)->setIsExact(true);
2399 } else if (isa<FPMathOperator>(I)) {
2401 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2402 FMF.setUnsafeAlgebra();
2403 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2405 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2407 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2408 FMF.setNoSignedZeros();
2409 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2410 FMF.setAllowReciprocal();
2412 I->setFastMathFlags(FMF);
2418 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2421 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2422 OpNum+2 != Record.size())
2423 return Error(InvalidRecord);
2425 Type *ResTy = getTypeByID(Record[OpNum]);
2426 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2427 if (Opc == -1 || !ResTy)
2428 return Error(InvalidRecord);
2429 Instruction *Temp = nullptr;
2430 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2432 InstructionList.push_back(Temp);
2433 CurBB->getInstList().push_back(Temp);
2436 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2438 InstructionList.push_back(I);
2441 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2442 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2445 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2446 return Error(InvalidRecord);
2448 SmallVector<Value*, 16> GEPIdx;
2449 while (OpNum != Record.size()) {
2451 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2452 return Error(InvalidRecord);
2453 GEPIdx.push_back(Op);
2456 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2457 InstructionList.push_back(I);
2458 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2459 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2463 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2464 // EXTRACTVAL: [opty, opval, n x indices]
2467 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2468 return Error(InvalidRecord);
2470 SmallVector<unsigned, 4> EXTRACTVALIdx;
2471 for (unsigned RecSize = Record.size();
2472 OpNum != RecSize; ++OpNum) {
2473 uint64_t Index = Record[OpNum];
2474 if ((unsigned)Index != Index)
2475 return Error(InvalidValue);
2476 EXTRACTVALIdx.push_back((unsigned)Index);
2479 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2480 InstructionList.push_back(I);
2484 case bitc::FUNC_CODE_INST_INSERTVAL: {
2485 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2488 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2489 return Error(InvalidRecord);
2491 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2492 return Error(InvalidRecord);
2494 SmallVector<unsigned, 4> INSERTVALIdx;
2495 for (unsigned RecSize = Record.size();
2496 OpNum != RecSize; ++OpNum) {
2497 uint64_t Index = Record[OpNum];
2498 if ((unsigned)Index != Index)
2499 return Error(InvalidValue);
2500 INSERTVALIdx.push_back((unsigned)Index);
2503 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2504 InstructionList.push_back(I);
2508 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2509 // obsolete form of select
2510 // handles select i1 ... in old bitcode
2512 Value *TrueVal, *FalseVal, *Cond;
2513 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2514 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2515 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2516 return Error(InvalidRecord);
2518 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2519 InstructionList.push_back(I);
2523 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2524 // new form of select
2525 // handles select i1 or select [N x i1]
2527 Value *TrueVal, *FalseVal, *Cond;
2528 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2529 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2530 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2531 return Error(InvalidRecord);
2533 // select condition can be either i1 or [N x i1]
2534 if (VectorType* vector_type =
2535 dyn_cast<VectorType>(Cond->getType())) {
2537 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2538 return Error(InvalidTypeForValue);
2541 if (Cond->getType() != Type::getInt1Ty(Context))
2542 return Error(InvalidTypeForValue);
2545 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2546 InstructionList.push_back(I);
2550 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2553 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2554 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2555 return Error(InvalidRecord);
2556 I = ExtractElementInst::Create(Vec, Idx);
2557 InstructionList.push_back(I);
2561 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2563 Value *Vec, *Elt, *Idx;
2564 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2565 popValue(Record, OpNum, NextValueNo,
2566 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2567 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2568 return Error(InvalidRecord);
2569 I = InsertElementInst::Create(Vec, Elt, Idx);
2570 InstructionList.push_back(I);
2574 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2576 Value *Vec1, *Vec2, *Mask;
2577 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2578 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2579 return Error(InvalidRecord);
2581 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2582 return Error(InvalidRecord);
2583 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2584 InstructionList.push_back(I);
2588 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2589 // Old form of ICmp/FCmp returning bool
2590 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2591 // both legal on vectors but had different behaviour.
2592 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2593 // FCmp/ICmp returning bool or vector of bool
2597 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2598 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2599 OpNum+1 != Record.size())
2600 return Error(InvalidRecord);
2602 if (LHS->getType()->isFPOrFPVectorTy())
2603 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2605 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2606 InstructionList.push_back(I);
2610 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2612 unsigned Size = Record.size();
2614 I = ReturnInst::Create(Context);
2615 InstructionList.push_back(I);
2620 Value *Op = nullptr;
2621 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2622 return Error(InvalidRecord);
2623 if (OpNum != Record.size())
2624 return Error(InvalidRecord);
2626 I = ReturnInst::Create(Context, Op);
2627 InstructionList.push_back(I);
2630 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2631 if (Record.size() != 1 && Record.size() != 3)
2632 return Error(InvalidRecord);
2633 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2635 return Error(InvalidRecord);
2637 if (Record.size() == 1) {
2638 I = BranchInst::Create(TrueDest);
2639 InstructionList.push_back(I);
2642 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2643 Value *Cond = getValue(Record, 2, NextValueNo,
2644 Type::getInt1Ty(Context));
2645 if (!FalseDest || !Cond)
2646 return Error(InvalidRecord);
2647 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2648 InstructionList.push_back(I);
2652 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2654 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2655 // "New" SwitchInst format with case ranges. The changes to write this
2656 // format were reverted but we still recognize bitcode that uses it.
2657 // Hopefully someday we will have support for case ranges and can use
2658 // this format again.
2660 Type *OpTy = getTypeByID(Record[1]);
2661 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2663 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2664 BasicBlock *Default = getBasicBlock(Record[3]);
2665 if (!OpTy || !Cond || !Default)
2666 return Error(InvalidRecord);
2668 unsigned NumCases = Record[4];
2670 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2671 InstructionList.push_back(SI);
2673 unsigned CurIdx = 5;
2674 for (unsigned i = 0; i != NumCases; ++i) {
2675 SmallVector<ConstantInt*, 1> CaseVals;
2676 unsigned NumItems = Record[CurIdx++];
2677 for (unsigned ci = 0; ci != NumItems; ++ci) {
2678 bool isSingleNumber = Record[CurIdx++];
2681 unsigned ActiveWords = 1;
2682 if (ValueBitWidth > 64)
2683 ActiveWords = Record[CurIdx++];
2684 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2686 CurIdx += ActiveWords;
2688 if (!isSingleNumber) {
2690 if (ValueBitWidth > 64)
2691 ActiveWords = Record[CurIdx++];
2693 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2695 CurIdx += ActiveWords;
2697 // FIXME: It is not clear whether values in the range should be
2698 // compared as signed or unsigned values. The partially
2699 // implemented changes that used this format in the past used
2700 // unsigned comparisons.
2701 for ( ; Low.ule(High); ++Low)
2702 CaseVals.push_back(ConstantInt::get(Context, Low));
2704 CaseVals.push_back(ConstantInt::get(Context, Low));
2706 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2707 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2708 cve = CaseVals.end(); cvi != cve; ++cvi)
2709 SI->addCase(*cvi, DestBB);
2715 // Old SwitchInst format without case ranges.
2717 if (Record.size() < 3 || (Record.size() & 1) == 0)
2718 return Error(InvalidRecord);
2719 Type *OpTy = getTypeByID(Record[0]);
2720 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2721 BasicBlock *Default = getBasicBlock(Record[2]);
2722 if (!OpTy || !Cond || !Default)
2723 return Error(InvalidRecord);
2724 unsigned NumCases = (Record.size()-3)/2;
2725 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2726 InstructionList.push_back(SI);
2727 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2728 ConstantInt *CaseVal =
2729 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2730 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2731 if (!CaseVal || !DestBB) {
2733 return Error(InvalidRecord);
2735 SI->addCase(CaseVal, DestBB);
2740 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2741 if (Record.size() < 2)
2742 return Error(InvalidRecord);
2743 Type *OpTy = getTypeByID(Record[0]);
2744 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2745 if (!OpTy || !Address)
2746 return Error(InvalidRecord);
2747 unsigned NumDests = Record.size()-2;
2748 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2749 InstructionList.push_back(IBI);
2750 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2751 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2752 IBI->addDestination(DestBB);
2755 return Error(InvalidRecord);
2762 case bitc::FUNC_CODE_INST_INVOKE: {
2763 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2764 if (Record.size() < 4)
2765 return Error(InvalidRecord);
2766 AttributeSet PAL = getAttributes(Record[0]);
2767 unsigned CCInfo = Record[1];
2768 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2769 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2773 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2774 return Error(InvalidRecord);
2776 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2777 FunctionType *FTy = !CalleeTy ? nullptr :
2778 dyn_cast<FunctionType>(CalleeTy->getElementType());
2780 // Check that the right number of fixed parameters are here.
2781 if (!FTy || !NormalBB || !UnwindBB ||
2782 Record.size() < OpNum+FTy->getNumParams())
2783 return Error(InvalidRecord);
2785 SmallVector<Value*, 16> Ops;
2786 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2787 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2788 FTy->getParamType(i)));
2790 return Error(InvalidRecord);
2793 if (!FTy->isVarArg()) {
2794 if (Record.size() != OpNum)
2795 return Error(InvalidRecord);
2797 // Read type/value pairs for varargs params.
2798 while (OpNum != Record.size()) {
2800 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2801 return Error(InvalidRecord);
2806 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2807 InstructionList.push_back(I);
2808 cast<InvokeInst>(I)->setCallingConv(
2809 static_cast<CallingConv::ID>(CCInfo));
2810 cast<InvokeInst>(I)->setAttributes(PAL);
2813 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2815 Value *Val = nullptr;
2816 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2817 return Error(InvalidRecord);
2818 I = ResumeInst::Create(Val);
2819 InstructionList.push_back(I);
2822 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2823 I = new UnreachableInst(Context);
2824 InstructionList.push_back(I);
2826 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2827 if (Record.size() < 1 || ((Record.size()-1)&1))
2828 return Error(InvalidRecord);
2829 Type *Ty = getTypeByID(Record[0]);
2831 return Error(InvalidRecord);
2833 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2834 InstructionList.push_back(PN);
2836 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2838 // With the new function encoding, it is possible that operands have
2839 // negative IDs (for forward references). Use a signed VBR
2840 // representation to keep the encoding small.
2842 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2844 V = getValue(Record, 1+i, NextValueNo, Ty);
2845 BasicBlock *BB = getBasicBlock(Record[2+i]);
2847 return Error(InvalidRecord);
2848 PN->addIncoming(V, BB);
2854 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2855 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2857 if (Record.size() < 4)
2858 return Error(InvalidRecord);
2859 Type *Ty = getTypeByID(Record[Idx++]);
2861 return Error(InvalidRecord);
2862 Value *PersFn = nullptr;
2863 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2864 return Error(InvalidRecord);
2866 bool IsCleanup = !!Record[Idx++];
2867 unsigned NumClauses = Record[Idx++];
2868 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2869 LP->setCleanup(IsCleanup);
2870 for (unsigned J = 0; J != NumClauses; ++J) {
2871 LandingPadInst::ClauseType CT =
2872 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2875 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2877 return Error(InvalidRecord);
2880 assert((CT != LandingPadInst::Catch ||
2881 !isa<ArrayType>(Val->getType())) &&
2882 "Catch clause has a invalid type!");
2883 assert((CT != LandingPadInst::Filter ||
2884 isa<ArrayType>(Val->getType())) &&
2885 "Filter clause has invalid type!");
2886 LP->addClause(cast<Constant>(Val));
2890 InstructionList.push_back(I);
2894 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2895 if (Record.size() != 4)
2896 return Error(InvalidRecord);
2898 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2899 Type *OpTy = getTypeByID(Record[1]);
2900 Value *Size = getFnValueByID(Record[2], OpTy);
2901 unsigned Align = Record[3];
2903 return Error(InvalidRecord);
2904 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2905 InstructionList.push_back(I);
2908 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2911 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2912 OpNum+2 != Record.size())
2913 return Error(InvalidRecord);
2915 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2916 InstructionList.push_back(I);
2919 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2920 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2923 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2924 OpNum+4 != Record.size())
2925 return Error(InvalidRecord);
2928 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2929 if (Ordering == NotAtomic || Ordering == Release ||
2930 Ordering == AcquireRelease)
2931 return Error(InvalidRecord);
2932 if (Ordering != NotAtomic && Record[OpNum] == 0)
2933 return Error(InvalidRecord);
2934 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2936 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2937 Ordering, SynchScope);
2938 InstructionList.push_back(I);
2941 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2944 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2945 popValue(Record, OpNum, NextValueNo,
2946 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2947 OpNum+2 != Record.size())
2948 return Error(InvalidRecord);
2950 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2951 InstructionList.push_back(I);
2954 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2955 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2958 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2959 popValue(Record, OpNum, NextValueNo,
2960 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2961 OpNum+4 != Record.size())
2962 return Error(InvalidRecord);
2964 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2965 if (Ordering == NotAtomic || Ordering == Acquire ||
2966 Ordering == AcquireRelease)
2967 return Error(InvalidRecord);
2968 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2969 if (Ordering != NotAtomic && Record[OpNum] == 0)
2970 return Error(InvalidRecord);
2972 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2973 Ordering, SynchScope);
2974 InstructionList.push_back(I);
2977 case bitc::FUNC_CODE_INST_CMPXCHG: {
2978 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2979 // failureordering?, isweak?]
2981 Value *Ptr, *Cmp, *New;
2982 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2983 popValue(Record, OpNum, NextValueNo,
2984 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2985 popValue(Record, OpNum, NextValueNo,
2986 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2987 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
2988 return Error(InvalidRecord);
2989 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2990 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2991 return Error(InvalidRecord);
2992 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2994 AtomicOrdering FailureOrdering;
2995 if (Record.size() < 7)
2997 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2999 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3001 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3003 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3005 if (Record.size() < 8) {
3006 // Before weak cmpxchgs existed, the instruction simply returned the
3007 // value loaded from memory, so bitcode files from that era will be
3008 // expecting the first component of a modern cmpxchg.
3009 CurBB->getInstList().push_back(I);
3010 I = ExtractValueInst::Create(I, 0);
3012 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3015 InstructionList.push_back(I);
3018 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3019 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3022 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3023 popValue(Record, OpNum, NextValueNo,
3024 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3025 OpNum+4 != Record.size())
3026 return Error(InvalidRecord);
3027 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3028 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3029 Operation > AtomicRMWInst::LAST_BINOP)
3030 return Error(InvalidRecord);
3031 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3032 if (Ordering == NotAtomic || Ordering == Unordered)
3033 return Error(InvalidRecord);
3034 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3035 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3036 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3037 InstructionList.push_back(I);
3040 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3041 if (2 != Record.size())
3042 return Error(InvalidRecord);
3043 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3044 if (Ordering == NotAtomic || Ordering == Unordered ||
3045 Ordering == Monotonic)
3046 return Error(InvalidRecord);
3047 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3048 I = new FenceInst(Context, Ordering, SynchScope);
3049 InstructionList.push_back(I);
3052 case bitc::FUNC_CODE_INST_CALL: {
3053 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3054 if (Record.size() < 3)
3055 return Error(InvalidRecord);
3057 AttributeSet PAL = getAttributes(Record[0]);
3058 unsigned CCInfo = Record[1];
3062 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3063 return Error(InvalidRecord);
3065 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3066 FunctionType *FTy = nullptr;
3067 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3068 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3069 return Error(InvalidRecord);
3071 SmallVector<Value*, 16> Args;
3072 // Read the fixed params.
3073 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3074 if (FTy->getParamType(i)->isLabelTy())
3075 Args.push_back(getBasicBlock(Record[OpNum]));
3077 Args.push_back(getValue(Record, OpNum, NextValueNo,
3078 FTy->getParamType(i)));
3080 return Error(InvalidRecord);
3083 // Read type/value pairs for varargs params.
3084 if (!FTy->isVarArg()) {
3085 if (OpNum != Record.size())
3086 return Error(InvalidRecord);
3088 while (OpNum != Record.size()) {
3090 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3091 return Error(InvalidRecord);
3096 I = CallInst::Create(Callee, Args);
3097 InstructionList.push_back(I);
3098 cast<CallInst>(I)->setCallingConv(
3099 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3100 CallInst::TailCallKind TCK = CallInst::TCK_None;
3102 TCK = CallInst::TCK_Tail;
3103 if (CCInfo & (1 << 14))
3104 TCK = CallInst::TCK_MustTail;
3105 cast<CallInst>(I)->setTailCallKind(TCK);
3106 cast<CallInst>(I)->setAttributes(PAL);
3109 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3110 if (Record.size() < 3)
3111 return Error(InvalidRecord);
3112 Type *OpTy = getTypeByID(Record[0]);
3113 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3114 Type *ResTy = getTypeByID(Record[2]);
3115 if (!OpTy || !Op || !ResTy)
3116 return Error(InvalidRecord);
3117 I = new VAArgInst(Op, ResTy);
3118 InstructionList.push_back(I);
3123 // Add instruction to end of current BB. If there is no current BB, reject
3127 return Error(InvalidInstructionWithNoBB);
3129 CurBB->getInstList().push_back(I);
3131 // If this was a terminator instruction, move to the next block.
3132 if (isa<TerminatorInst>(I)) {
3134 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3137 // Non-void values get registered in the value table for future use.
3138 if (I && !I->getType()->isVoidTy())
3139 ValueList.AssignValue(I, NextValueNo++);
3144 // Check the function list for unresolved values.
3145 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3146 if (!A->getParent()) {
3147 // We found at least one unresolved value. Nuke them all to avoid leaks.
3148 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3149 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3150 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3154 return Error(NeverResolvedValueFoundInFunction);
3158 // FIXME: Check for unresolved forward-declared metadata references
3159 // and clean up leaks.
3161 // See if anything took the address of blocks in this function. If so,
3162 // resolve them now.
3163 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3164 BlockAddrFwdRefs.find(F);
3165 if (BAFRI != BlockAddrFwdRefs.end()) {
3166 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3167 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3168 unsigned BlockIdx = RefList[i].first;
3169 if (BlockIdx >= FunctionBBs.size())
3170 return Error(InvalidID);
3172 GlobalVariable *FwdRef = RefList[i].second;
3173 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3174 FwdRef->eraseFromParent();
3177 BlockAddrFwdRefs.erase(BAFRI);
3180 // Trim the value list down to the size it was before we parsed this function.
3181 ValueList.shrinkTo(ModuleValueListSize);
3182 MDValueList.shrinkTo(ModuleMDValueListSize);
3183 std::vector<BasicBlock*>().swap(FunctionBBs);
3184 return std::error_code();
3187 /// Find the function body in the bitcode stream
3188 std::error_code BitcodeReader::FindFunctionInStream(
3190 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3191 while (DeferredFunctionInfoIterator->second == 0) {
3192 if (Stream.AtEndOfStream())
3193 return Error(CouldNotFindFunctionInStream);
3194 // ParseModule will parse the next body in the stream and set its
3195 // position in the DeferredFunctionInfo map.
3196 if (std::error_code EC = ParseModule(true))
3199 return std::error_code();
3202 //===----------------------------------------------------------------------===//
3203 // GVMaterializer implementation
3204 //===----------------------------------------------------------------------===//
3206 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3208 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3209 if (const Function *F = dyn_cast<Function>(GV)) {
3210 return F->isDeclaration() &&
3211 DeferredFunctionInfo.count(const_cast<Function*>(F));
3216 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
3217 Function *F = dyn_cast<Function>(GV);
3218 // If it's not a function or is already material, ignore the request.
3219 if (!F || !F->isMaterializable())
3220 return std::error_code();
3222 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3223 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3224 // If its position is recorded as 0, its body is somewhere in the stream
3225 // but we haven't seen it yet.
3226 if (DFII->second == 0 && LazyStreamer)
3227 if (std::error_code EC = FindFunctionInStream(F, DFII))
3230 // Move the bit stream to the saved position of the deferred function body.
3231 Stream.JumpToBit(DFII->second);
3233 if (std::error_code EC = ParseFunctionBody(F))
3236 // Upgrade any old intrinsic calls in the function.
3237 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3238 E = UpgradedIntrinsics.end(); I != E; ++I) {
3239 if (I->first != I->second) {
3240 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3242 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3243 UpgradeIntrinsicCall(CI, I->second);
3248 return std::error_code();
3251 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3252 const Function *F = dyn_cast<Function>(GV);
3253 if (!F || F->isDeclaration())
3255 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3258 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3259 Function *F = dyn_cast<Function>(GV);
3260 // If this function isn't dematerializable, this is a noop.
3261 if (!F || !isDematerializable(F))
3264 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3266 // Just forget the function body, we can remat it later.
3270 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3271 assert(M == TheModule &&
3272 "Can only Materialize the Module this BitcodeReader is attached to.");
3273 // Iterate over the module, deserializing any functions that are still on
3275 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3277 if (F->isMaterializable()) {
3278 if (std::error_code EC = Materialize(F))
3282 // At this point, if there are any function bodies, the current bit is
3283 // pointing to the END_BLOCK record after them. Now make sure the rest
3284 // of the bits in the module have been read.
3288 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3289 // delete the old functions to clean up. We can't do this unless the entire
3290 // module is materialized because there could always be another function body
3291 // with calls to the old function.
3292 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3293 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3294 if (I->first != I->second) {
3295 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3297 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3298 UpgradeIntrinsicCall(CI, I->second);
3300 if (!I->first->use_empty())
3301 I->first->replaceAllUsesWith(I->second);
3302 I->first->eraseFromParent();
3305 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3307 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3308 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3310 UpgradeDebugInfo(*M);
3311 return std::error_code();
3314 std::error_code BitcodeReader::InitStream() {
3316 return InitLazyStream();
3317 return InitStreamFromBuffer();
3320 std::error_code BitcodeReader::InitStreamFromBuffer() {
3321 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3322 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3324 if (Buffer->getBufferSize() & 3) {
3325 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3326 return Error(InvalidBitcodeSignature);
3328 return Error(BitcodeStreamInvalidSize);
3331 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3332 // The magic number is 0x0B17C0DE stored in little endian.
3333 if (isBitcodeWrapper(BufPtr, BufEnd))
3334 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3335 return Error(InvalidBitcodeWrapperHeader);
3337 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3338 Stream.init(*StreamFile);
3340 return std::error_code();
3343 std::error_code BitcodeReader::InitLazyStream() {
3344 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3346 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3347 StreamFile.reset(new BitstreamReader(Bytes));
3348 Stream.init(*StreamFile);
3350 unsigned char buf[16];
3351 if (Bytes->readBytes(0, 16, buf) == -1)
3352 return Error(BitcodeStreamInvalidSize);
3354 if (!isBitcode(buf, buf + 16))
3355 return Error(InvalidBitcodeSignature);
3357 if (isBitcodeWrapper(buf, buf + 4)) {
3358 const unsigned char *bitcodeStart = buf;
3359 const unsigned char *bitcodeEnd = buf + 16;
3360 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3361 Bytes->dropLeadingBytes(bitcodeStart - buf);
3362 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3364 return std::error_code();
3368 class BitcodeErrorCategoryType : public std::error_category {
3369 const char *name() const LLVM_NOEXCEPT override {
3370 return "llvm.bitcode";
3372 std::string message(int IE) const override {
3373 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3375 case BitcodeReader::BitcodeStreamInvalidSize:
3376 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3377 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3378 return "Conflicting METADATA_KIND records";
3379 case BitcodeReader::CouldNotFindFunctionInStream:
3380 return "Could not find function in stream";
3381 case BitcodeReader::ExpectedConstant:
3382 return "Expected a constant";
3383 case BitcodeReader::InsufficientFunctionProtos:
3384 return "Insufficient function protos";
3385 case BitcodeReader::InvalidBitcodeSignature:
3386 return "Invalid bitcode signature";
3387 case BitcodeReader::InvalidBitcodeWrapperHeader:
3388 return "Invalid bitcode wrapper header";
3389 case BitcodeReader::InvalidConstantReference:
3390 return "Invalid ronstant reference";
3391 case BitcodeReader::InvalidID:
3392 return "Invalid ID";
3393 case BitcodeReader::InvalidInstructionWithNoBB:
3394 return "Invalid instruction with no BB";
3395 case BitcodeReader::InvalidRecord:
3396 return "Invalid record";
3397 case BitcodeReader::InvalidTypeForValue:
3398 return "Invalid type for value";
3399 case BitcodeReader::InvalidTYPETable:
3400 return "Invalid TYPE table";
3401 case BitcodeReader::InvalidType:
3402 return "Invalid type";
3403 case BitcodeReader::MalformedBlock:
3404 return "Malformed block";
3405 case BitcodeReader::MalformedGlobalInitializerSet:
3406 return "Malformed global initializer set";
3407 case BitcodeReader::InvalidMultipleBlocks:
3408 return "Invalid multiple blocks";
3409 case BitcodeReader::NeverResolvedValueFoundInFunction:
3410 return "Never resolved value found in function";
3411 case BitcodeReader::InvalidValue:
3412 return "Invalid value";
3414 llvm_unreachable("Unknown error type!");
3419 const std::error_category &BitcodeReader::BitcodeErrorCategory() {
3420 static BitcodeErrorCategoryType O;
3424 //===----------------------------------------------------------------------===//
3425 // External interface
3426 //===----------------------------------------------------------------------===//
3428 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3430 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3431 LLVMContext &Context) {
3432 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3433 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3434 M->setMaterializer(R);
3435 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3436 R->releaseBuffer(); // Never take ownership on error.
3437 delete M; // Also deletes R.
3441 R->materializeForwardReferencedFunctions();
3447 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3448 DataStreamer *streamer,
3449 LLVMContext &Context,
3450 std::string *ErrMsg) {
3451 Module *M = new Module(name, Context);
3452 BitcodeReader *R = new BitcodeReader(streamer, Context);
3453 M->setMaterializer(R);
3454 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3456 *ErrMsg = EC.message();
3457 delete M; // Also deletes R.
3463 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3464 LLVMContext &Context) {
3465 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3468 Module *M = ModuleOrErr.get();
3469 // Read in the entire module, and destroy the BitcodeReader.
3470 if (std::error_code EC = M->materializeAllPermanently(true)) {
3475 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3476 // written. We must defer until the Module has been fully materialized.
3481 StringRef llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3482 LLVMContext &Context) {
3483 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3484 ErrorOr<StringRef> Triple = R->parseTriple();
3487 if (Triple.getError())
3489 return Triple.get();