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);
47 std::vector<AttributeSet>().swap(MAttributes);
48 std::vector<BasicBlock*>().swap(FunctionBBs);
49 std::vector<Function*>().swap(FunctionsWithBodies);
50 DeferredFunctionInfo.clear();
53 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
56 //===----------------------------------------------------------------------===//
57 // Helper functions to implement forward reference resolution, etc.
58 //===----------------------------------------------------------------------===//
60 /// ConvertToString - Convert a string from a record into an std::string, return
62 template<typename StrTy>
63 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
65 if (Idx > Record.size())
68 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
69 Result += (char)Record[i];
73 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
75 default: // Map unknown/new linkages to external
76 case 0: return GlobalValue::ExternalLinkage;
77 case 1: return GlobalValue::WeakAnyLinkage;
78 case 2: return GlobalValue::AppendingLinkage;
79 case 3: return GlobalValue::InternalLinkage;
80 case 4: return GlobalValue::LinkOnceAnyLinkage;
81 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
82 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
83 case 7: return GlobalValue::ExternalWeakLinkage;
84 case 8: return GlobalValue::CommonLinkage;
85 case 9: return GlobalValue::PrivateLinkage;
86 case 10: return GlobalValue::WeakODRLinkage;
87 case 11: return GlobalValue::LinkOnceODRLinkage;
88 case 12: return GlobalValue::AvailableExternallyLinkage;
90 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
92 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
96 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
101 case 2: return GlobalValue::ProtectedVisibility;
105 static GlobalValue::DLLStorageClassTypes
106 GetDecodedDLLStorageClass(unsigned Val) {
108 default: // Map unknown values to default.
109 case 0: return GlobalValue::DefaultStorageClass;
110 case 1: return GlobalValue::DLLImportStorageClass;
111 case 2: return GlobalValue::DLLExportStorageClass;
115 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
117 case 0: return GlobalVariable::NotThreadLocal;
118 default: // Map unknown non-zero value to general dynamic.
119 case 1: return GlobalVariable::GeneralDynamicTLSModel;
120 case 2: return GlobalVariable::LocalDynamicTLSModel;
121 case 3: return GlobalVariable::InitialExecTLSModel;
122 case 4: return GlobalVariable::LocalExecTLSModel;
126 static int GetDecodedCastOpcode(unsigned Val) {
129 case bitc::CAST_TRUNC : return Instruction::Trunc;
130 case bitc::CAST_ZEXT : return Instruction::ZExt;
131 case bitc::CAST_SEXT : return Instruction::SExt;
132 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
133 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
134 case bitc::CAST_UITOFP : return Instruction::UIToFP;
135 case bitc::CAST_SITOFP : return Instruction::SIToFP;
136 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
137 case bitc::CAST_FPEXT : return Instruction::FPExt;
138 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
139 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
140 case bitc::CAST_BITCAST : return Instruction::BitCast;
141 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
144 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
147 case bitc::BINOP_ADD:
148 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
149 case bitc::BINOP_SUB:
150 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
151 case bitc::BINOP_MUL:
152 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
153 case bitc::BINOP_UDIV: return Instruction::UDiv;
154 case bitc::BINOP_SDIV:
155 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
156 case bitc::BINOP_UREM: return Instruction::URem;
157 case bitc::BINOP_SREM:
158 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
159 case bitc::BINOP_SHL: return Instruction::Shl;
160 case bitc::BINOP_LSHR: return Instruction::LShr;
161 case bitc::BINOP_ASHR: return Instruction::AShr;
162 case bitc::BINOP_AND: return Instruction::And;
163 case bitc::BINOP_OR: return Instruction::Or;
164 case bitc::BINOP_XOR: return Instruction::Xor;
168 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
170 default: return AtomicRMWInst::BAD_BINOP;
171 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
172 case bitc::RMW_ADD: return AtomicRMWInst::Add;
173 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
174 case bitc::RMW_AND: return AtomicRMWInst::And;
175 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
176 case bitc::RMW_OR: return AtomicRMWInst::Or;
177 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
178 case bitc::RMW_MAX: return AtomicRMWInst::Max;
179 case bitc::RMW_MIN: return AtomicRMWInst::Min;
180 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
181 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
185 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
187 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
188 case bitc::ORDERING_UNORDERED: return Unordered;
189 case bitc::ORDERING_MONOTONIC: return Monotonic;
190 case bitc::ORDERING_ACQUIRE: return Acquire;
191 case bitc::ORDERING_RELEASE: return Release;
192 case bitc::ORDERING_ACQREL: return AcquireRelease;
193 default: // Map unknown orderings to sequentially-consistent.
194 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
198 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
200 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
201 default: // Map unknown scopes to cross-thread.
202 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
206 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
208 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
209 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
215 /// @brief A class for maintaining the slot number definition
216 /// as a placeholder for the actual definition for forward constants defs.
217 class ConstantPlaceHolder : public ConstantExpr {
218 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
220 // allocate space for exactly one operand
221 void *operator new(size_t s) {
222 return User::operator new(s, 1);
224 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
225 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
226 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
229 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
230 static bool classof(const Value *V) {
231 return isa<ConstantExpr>(V) &&
232 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
236 /// Provide fast operand accessors
237 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
241 // FIXME: can we inherit this from ConstantExpr?
243 struct OperandTraits<ConstantPlaceHolder> :
244 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
249 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
258 WeakVH &OldV = ValuePtrs[Idx];
264 // Handle constants and non-constants (e.g. instrs) differently for
266 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
267 ResolveConstants.push_back(std::make_pair(PHC, Idx));
270 // If there was a forward reference to this value, replace it.
271 Value *PrevVal = OldV;
272 OldV->replaceAllUsesWith(V);
278 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
283 if (Value *V = ValuePtrs[Idx]) {
284 assert(Ty == V->getType() && "Type mismatch in constant table!");
285 return cast<Constant>(V);
288 // Create and return a placeholder, which will later be RAUW'd.
289 Constant *C = new ConstantPlaceHolder(Ty, Context);
294 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
298 if (Value *V = ValuePtrs[Idx]) {
299 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
303 // No type specified, must be invalid reference.
304 if (!Ty) return nullptr;
306 // Create and return a placeholder, which will later be RAUW'd.
307 Value *V = new Argument(Ty);
312 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
313 /// resolves any forward references. The idea behind this is that we sometimes
314 /// get constants (such as large arrays) which reference *many* forward ref
315 /// constants. Replacing each of these causes a lot of thrashing when
316 /// building/reuniquing the constant. Instead of doing this, we look at all the
317 /// uses and rewrite all the place holders at once for any constant that uses
319 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
320 // Sort the values by-pointer so that they are efficient to look up with a
322 std::sort(ResolveConstants.begin(), ResolveConstants.end());
324 SmallVector<Constant*, 64> NewOps;
326 while (!ResolveConstants.empty()) {
327 Value *RealVal = operator[](ResolveConstants.back().second);
328 Constant *Placeholder = ResolveConstants.back().first;
329 ResolveConstants.pop_back();
331 // Loop over all users of the placeholder, updating them to reference the
332 // new value. If they reference more than one placeholder, update them all
334 while (!Placeholder->use_empty()) {
335 auto UI = Placeholder->user_begin();
338 // If the using object isn't uniqued, just update the operands. This
339 // handles instructions and initializers for global variables.
340 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
341 UI.getUse().set(RealVal);
345 // Otherwise, we have a constant that uses the placeholder. Replace that
346 // constant with a new constant that has *all* placeholder uses updated.
347 Constant *UserC = cast<Constant>(U);
348 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
351 if (!isa<ConstantPlaceHolder>(*I)) {
352 // Not a placeholder reference.
354 } else if (*I == Placeholder) {
355 // Common case is that it just references this one placeholder.
358 // Otherwise, look up the placeholder in ResolveConstants.
359 ResolveConstantsTy::iterator It =
360 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
361 std::pair<Constant*, unsigned>(cast<Constant>(*I),
363 assert(It != ResolveConstants.end() && It->first == *I);
364 NewOp = operator[](It->second);
367 NewOps.push_back(cast<Constant>(NewOp));
370 // Make the new constant.
372 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
373 NewC = ConstantArray::get(UserCA->getType(), NewOps);
374 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
375 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
376 } else if (isa<ConstantVector>(UserC)) {
377 NewC = ConstantVector::get(NewOps);
379 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
380 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
383 UserC->replaceAllUsesWith(NewC);
384 UserC->destroyConstant();
388 // Update all ValueHandles, they should be the only users at this point.
389 Placeholder->replaceAllUsesWith(RealVal);
394 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
403 WeakVH &OldV = MDValuePtrs[Idx];
409 // If there was a forward reference to this value, replace it.
410 MDNode *PrevVal = cast<MDNode>(OldV);
411 OldV->replaceAllUsesWith(V);
412 MDNode::deleteTemporary(PrevVal);
413 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
415 MDValuePtrs[Idx] = V;
418 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
422 if (Value *V = MDValuePtrs[Idx]) {
423 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
427 // Create and return a placeholder, which will later be RAUW'd.
428 Value *V = MDNode::getTemporary(Context, None);
429 MDValuePtrs[Idx] = V;
433 Type *BitcodeReader::getTypeByID(unsigned ID) {
434 // The type table size is always specified correctly.
435 if (ID >= TypeList.size())
438 if (Type *Ty = TypeList[ID])
441 // If we have a forward reference, the only possible case is when it is to a
442 // named struct. Just create a placeholder for now.
443 return TypeList[ID] = StructType::create(Context);
447 //===----------------------------------------------------------------------===//
448 // Functions for parsing blocks from the bitcode file
449 //===----------------------------------------------------------------------===//
452 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
453 /// been decoded from the given integer. This function must stay in sync with
454 /// 'encodeLLVMAttributesForBitcode'.
455 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
456 uint64_t EncodedAttrs) {
457 // FIXME: Remove in 4.0.
459 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
460 // the bits above 31 down by 11 bits.
461 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
462 assert((!Alignment || isPowerOf2_32(Alignment)) &&
463 "Alignment must be a power of two.");
466 B.addAlignmentAttr(Alignment);
467 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
468 (EncodedAttrs & 0xffff));
471 std::error_code BitcodeReader::ParseAttributeBlock() {
472 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
473 return Error(InvalidRecord);
475 if (!MAttributes.empty())
476 return Error(InvalidMultipleBlocks);
478 SmallVector<uint64_t, 64> Record;
480 SmallVector<AttributeSet, 8> Attrs;
482 // Read all the records.
484 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
486 switch (Entry.Kind) {
487 case BitstreamEntry::SubBlock: // Handled for us already.
488 case BitstreamEntry::Error:
489 return Error(MalformedBlock);
490 case BitstreamEntry::EndBlock:
491 return std::error_code();
492 case BitstreamEntry::Record:
493 // The interesting case.
499 switch (Stream.readRecord(Entry.ID, Record)) {
500 default: // Default behavior: ignore.
502 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
503 // FIXME: Remove in 4.0.
504 if (Record.size() & 1)
505 return Error(InvalidRecord);
507 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
509 decodeLLVMAttributesForBitcode(B, Record[i+1]);
510 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
513 MAttributes.push_back(AttributeSet::get(Context, Attrs));
517 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
518 for (unsigned i = 0, e = Record.size(); i != e; ++i)
519 Attrs.push_back(MAttributeGroups[Record[i]]);
521 MAttributes.push_back(AttributeSet::get(Context, Attrs));
529 // Returns Attribute::None on unrecognized codes.
530 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
533 return Attribute::None;
534 case bitc::ATTR_KIND_ALIGNMENT:
535 return Attribute::Alignment;
536 case bitc::ATTR_KIND_ALWAYS_INLINE:
537 return Attribute::AlwaysInline;
538 case bitc::ATTR_KIND_BUILTIN:
539 return Attribute::Builtin;
540 case bitc::ATTR_KIND_BY_VAL:
541 return Attribute::ByVal;
542 case bitc::ATTR_KIND_IN_ALLOCA:
543 return Attribute::InAlloca;
544 case bitc::ATTR_KIND_COLD:
545 return Attribute::Cold;
546 case bitc::ATTR_KIND_INLINE_HINT:
547 return Attribute::InlineHint;
548 case bitc::ATTR_KIND_IN_REG:
549 return Attribute::InReg;
550 case bitc::ATTR_KIND_JUMP_TABLE:
551 return Attribute::JumpTable;
552 case bitc::ATTR_KIND_MIN_SIZE:
553 return Attribute::MinSize;
554 case bitc::ATTR_KIND_NAKED:
555 return Attribute::Naked;
556 case bitc::ATTR_KIND_NEST:
557 return Attribute::Nest;
558 case bitc::ATTR_KIND_NO_ALIAS:
559 return Attribute::NoAlias;
560 case bitc::ATTR_KIND_NO_BUILTIN:
561 return Attribute::NoBuiltin;
562 case bitc::ATTR_KIND_NO_CAPTURE:
563 return Attribute::NoCapture;
564 case bitc::ATTR_KIND_NO_DUPLICATE:
565 return Attribute::NoDuplicate;
566 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
567 return Attribute::NoImplicitFloat;
568 case bitc::ATTR_KIND_NO_INLINE:
569 return Attribute::NoInline;
570 case bitc::ATTR_KIND_NON_LAZY_BIND:
571 return Attribute::NonLazyBind;
572 case bitc::ATTR_KIND_NON_NULL:
573 return Attribute::NonNull;
574 case bitc::ATTR_KIND_NO_RED_ZONE:
575 return Attribute::NoRedZone;
576 case bitc::ATTR_KIND_NO_RETURN:
577 return Attribute::NoReturn;
578 case bitc::ATTR_KIND_NO_UNWIND:
579 return Attribute::NoUnwind;
580 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
581 return Attribute::OptimizeForSize;
582 case bitc::ATTR_KIND_OPTIMIZE_NONE:
583 return Attribute::OptimizeNone;
584 case bitc::ATTR_KIND_READ_NONE:
585 return Attribute::ReadNone;
586 case bitc::ATTR_KIND_READ_ONLY:
587 return Attribute::ReadOnly;
588 case bitc::ATTR_KIND_RETURNED:
589 return Attribute::Returned;
590 case bitc::ATTR_KIND_RETURNS_TWICE:
591 return Attribute::ReturnsTwice;
592 case bitc::ATTR_KIND_S_EXT:
593 return Attribute::SExt;
594 case bitc::ATTR_KIND_STACK_ALIGNMENT:
595 return Attribute::StackAlignment;
596 case bitc::ATTR_KIND_STACK_PROTECT:
597 return Attribute::StackProtect;
598 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
599 return Attribute::StackProtectReq;
600 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
601 return Attribute::StackProtectStrong;
602 case bitc::ATTR_KIND_STRUCT_RET:
603 return Attribute::StructRet;
604 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
605 return Attribute::SanitizeAddress;
606 case bitc::ATTR_KIND_SANITIZE_THREAD:
607 return Attribute::SanitizeThread;
608 case bitc::ATTR_KIND_SANITIZE_MEMORY:
609 return Attribute::SanitizeMemory;
610 case bitc::ATTR_KIND_UW_TABLE:
611 return Attribute::UWTable;
612 case bitc::ATTR_KIND_Z_EXT:
613 return Attribute::ZExt;
617 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
618 Attribute::AttrKind *Kind) {
619 *Kind = GetAttrFromCode(Code);
620 if (*Kind == Attribute::None)
621 return Error(InvalidValue);
622 return std::error_code();
625 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
626 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
627 return Error(InvalidRecord);
629 if (!MAttributeGroups.empty())
630 return Error(InvalidMultipleBlocks);
632 SmallVector<uint64_t, 64> Record;
634 // Read all the records.
636 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
638 switch (Entry.Kind) {
639 case BitstreamEntry::SubBlock: // Handled for us already.
640 case BitstreamEntry::Error:
641 return Error(MalformedBlock);
642 case BitstreamEntry::EndBlock:
643 return std::error_code();
644 case BitstreamEntry::Record:
645 // The interesting case.
651 switch (Stream.readRecord(Entry.ID, Record)) {
652 default: // Default behavior: ignore.
654 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
655 if (Record.size() < 3)
656 return Error(InvalidRecord);
658 uint64_t GrpID = Record[0];
659 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
662 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
663 if (Record[i] == 0) { // Enum attribute
664 Attribute::AttrKind Kind;
665 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
668 B.addAttribute(Kind);
669 } else if (Record[i] == 1) { // Align attribute
670 Attribute::AttrKind Kind;
671 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
673 if (Kind == Attribute::Alignment)
674 B.addAlignmentAttr(Record[++i]);
676 B.addStackAlignmentAttr(Record[++i]);
677 } else { // String attribute
678 assert((Record[i] == 3 || Record[i] == 4) &&
679 "Invalid attribute group entry");
680 bool HasValue = (Record[i++] == 4);
681 SmallString<64> KindStr;
682 SmallString<64> ValStr;
684 while (Record[i] != 0 && i != e)
685 KindStr += Record[i++];
686 assert(Record[i] == 0 && "Kind string not null terminated");
689 // Has a value associated with it.
690 ++i; // Skip the '0' that terminates the "kind" string.
691 while (Record[i] != 0 && i != e)
692 ValStr += Record[i++];
693 assert(Record[i] == 0 && "Value string not null terminated");
696 B.addAttribute(KindStr.str(), ValStr.str());
700 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
707 std::error_code BitcodeReader::ParseTypeTable() {
708 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
709 return Error(InvalidRecord);
711 return ParseTypeTableBody();
714 std::error_code BitcodeReader::ParseTypeTableBody() {
715 if (!TypeList.empty())
716 return Error(InvalidMultipleBlocks);
718 SmallVector<uint64_t, 64> Record;
719 unsigned NumRecords = 0;
721 SmallString<64> TypeName;
723 // Read all the records for this type table.
725 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
727 switch (Entry.Kind) {
728 case BitstreamEntry::SubBlock: // Handled for us already.
729 case BitstreamEntry::Error:
730 return Error(MalformedBlock);
731 case BitstreamEntry::EndBlock:
732 if (NumRecords != TypeList.size())
733 return Error(MalformedBlock);
734 return std::error_code();
735 case BitstreamEntry::Record:
736 // The interesting case.
742 Type *ResultTy = nullptr;
743 switch (Stream.readRecord(Entry.ID, Record)) {
745 return Error(InvalidValue);
746 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
747 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
748 // type list. This allows us to reserve space.
749 if (Record.size() < 1)
750 return Error(InvalidRecord);
751 TypeList.resize(Record[0]);
753 case bitc::TYPE_CODE_VOID: // VOID
754 ResultTy = Type::getVoidTy(Context);
756 case bitc::TYPE_CODE_HALF: // HALF
757 ResultTy = Type::getHalfTy(Context);
759 case bitc::TYPE_CODE_FLOAT: // FLOAT
760 ResultTy = Type::getFloatTy(Context);
762 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
763 ResultTy = Type::getDoubleTy(Context);
765 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
766 ResultTy = Type::getX86_FP80Ty(Context);
768 case bitc::TYPE_CODE_FP128: // FP128
769 ResultTy = Type::getFP128Ty(Context);
771 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
772 ResultTy = Type::getPPC_FP128Ty(Context);
774 case bitc::TYPE_CODE_LABEL: // LABEL
775 ResultTy = Type::getLabelTy(Context);
777 case bitc::TYPE_CODE_METADATA: // METADATA
778 ResultTy = Type::getMetadataTy(Context);
780 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
781 ResultTy = Type::getX86_MMXTy(Context);
783 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
784 if (Record.size() < 1)
785 return Error(InvalidRecord);
787 ResultTy = IntegerType::get(Context, Record[0]);
789 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
790 // [pointee type, address space]
791 if (Record.size() < 1)
792 return Error(InvalidRecord);
793 unsigned AddressSpace = 0;
794 if (Record.size() == 2)
795 AddressSpace = Record[1];
796 ResultTy = getTypeByID(Record[0]);
798 return Error(InvalidType);
799 ResultTy = PointerType::get(ResultTy, AddressSpace);
802 case bitc::TYPE_CODE_FUNCTION_OLD: {
803 // FIXME: attrid is dead, remove it in LLVM 4.0
804 // FUNCTION: [vararg, attrid, retty, paramty x N]
805 if (Record.size() < 3)
806 return Error(InvalidRecord);
807 SmallVector<Type*, 8> ArgTys;
808 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
809 if (Type *T = getTypeByID(Record[i]))
815 ResultTy = getTypeByID(Record[2]);
816 if (!ResultTy || ArgTys.size() < Record.size()-3)
817 return Error(InvalidType);
819 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
822 case bitc::TYPE_CODE_FUNCTION: {
823 // FUNCTION: [vararg, retty, paramty x N]
824 if (Record.size() < 2)
825 return Error(InvalidRecord);
826 SmallVector<Type*, 8> ArgTys;
827 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
828 if (Type *T = getTypeByID(Record[i]))
834 ResultTy = getTypeByID(Record[1]);
835 if (!ResultTy || ArgTys.size() < Record.size()-2)
836 return Error(InvalidType);
838 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
841 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
842 if (Record.size() < 1)
843 return Error(InvalidRecord);
844 SmallVector<Type*, 8> EltTys;
845 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
846 if (Type *T = getTypeByID(Record[i]))
851 if (EltTys.size() != Record.size()-1)
852 return Error(InvalidType);
853 ResultTy = StructType::get(Context, EltTys, Record[0]);
856 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
857 if (ConvertToString(Record, 0, TypeName))
858 return Error(InvalidRecord);
861 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
862 if (Record.size() < 1)
863 return Error(InvalidRecord);
865 if (NumRecords >= TypeList.size())
866 return Error(InvalidTYPETable);
868 // Check to see if this was forward referenced, if so fill in the temp.
869 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
871 Res->setName(TypeName);
872 TypeList[NumRecords] = nullptr;
873 } else // Otherwise, create a new struct.
874 Res = StructType::create(Context, TypeName);
877 SmallVector<Type*, 8> EltTys;
878 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
879 if (Type *T = getTypeByID(Record[i]))
884 if (EltTys.size() != Record.size()-1)
885 return Error(InvalidRecord);
886 Res->setBody(EltTys, Record[0]);
890 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
891 if (Record.size() != 1)
892 return Error(InvalidRecord);
894 if (NumRecords >= TypeList.size())
895 return Error(InvalidTYPETable);
897 // Check to see if this was forward referenced, if so fill in the temp.
898 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
900 Res->setName(TypeName);
901 TypeList[NumRecords] = nullptr;
902 } else // Otherwise, create a new struct with no body.
903 Res = StructType::create(Context, TypeName);
908 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
909 if (Record.size() < 2)
910 return Error(InvalidRecord);
911 if ((ResultTy = getTypeByID(Record[1])))
912 ResultTy = ArrayType::get(ResultTy, Record[0]);
914 return Error(InvalidType);
916 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
917 if (Record.size() < 2)
918 return Error(InvalidRecord);
919 if ((ResultTy = getTypeByID(Record[1])))
920 ResultTy = VectorType::get(ResultTy, Record[0]);
922 return Error(InvalidType);
926 if (NumRecords >= TypeList.size())
927 return Error(InvalidTYPETable);
928 assert(ResultTy && "Didn't read a type?");
929 assert(!TypeList[NumRecords] && "Already read type?");
930 TypeList[NumRecords++] = ResultTy;
934 std::error_code BitcodeReader::ParseValueSymbolTable() {
935 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
936 return Error(InvalidRecord);
938 SmallVector<uint64_t, 64> Record;
940 // Read all the records for this value table.
941 SmallString<128> ValueName;
943 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
945 switch (Entry.Kind) {
946 case BitstreamEntry::SubBlock: // Handled for us already.
947 case BitstreamEntry::Error:
948 return Error(MalformedBlock);
949 case BitstreamEntry::EndBlock:
950 return std::error_code();
951 case BitstreamEntry::Record:
952 // The interesting case.
958 switch (Stream.readRecord(Entry.ID, Record)) {
959 default: // Default behavior: unknown type.
961 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
962 if (ConvertToString(Record, 1, ValueName))
963 return Error(InvalidRecord);
964 unsigned ValueID = Record[0];
965 if (ValueID >= ValueList.size() || !ValueList[ValueID])
966 return Error(InvalidRecord);
967 Value *V = ValueList[ValueID];
969 V->setName(StringRef(ValueName.data(), ValueName.size()));
973 case bitc::VST_CODE_BBENTRY: {
974 if (ConvertToString(Record, 1, ValueName))
975 return Error(InvalidRecord);
976 BasicBlock *BB = getBasicBlock(Record[0]);
978 return Error(InvalidRecord);
980 BB->setName(StringRef(ValueName.data(), ValueName.size()));
988 std::error_code BitcodeReader::ParseMetadata() {
989 unsigned NextMDValueNo = MDValueList.size();
991 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
992 return Error(InvalidRecord);
994 SmallVector<uint64_t, 64> Record;
996 // Read all the records.
998 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1000 switch (Entry.Kind) {
1001 case BitstreamEntry::SubBlock: // Handled for us already.
1002 case BitstreamEntry::Error:
1003 return Error(MalformedBlock);
1004 case BitstreamEntry::EndBlock:
1005 return std::error_code();
1006 case BitstreamEntry::Record:
1007 // The interesting case.
1011 bool IsFunctionLocal = false;
1014 unsigned Code = Stream.readRecord(Entry.ID, Record);
1016 default: // Default behavior: ignore.
1018 case bitc::METADATA_NAME: {
1019 // Read name of the named metadata.
1020 SmallString<8> Name(Record.begin(), Record.end());
1022 Code = Stream.ReadCode();
1024 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1025 unsigned NextBitCode = Stream.readRecord(Code, Record);
1026 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1028 // Read named metadata elements.
1029 unsigned Size = Record.size();
1030 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1031 for (unsigned i = 0; i != Size; ++i) {
1032 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1034 return Error(InvalidRecord);
1035 NMD->addOperand(MD);
1039 case bitc::METADATA_FN_NODE:
1040 IsFunctionLocal = true;
1042 case bitc::METADATA_NODE: {
1043 if (Record.size() % 2 == 1)
1044 return Error(InvalidRecord);
1046 unsigned Size = Record.size();
1047 SmallVector<Value*, 8> Elts;
1048 for (unsigned i = 0; i != Size; i += 2) {
1049 Type *Ty = getTypeByID(Record[i]);
1051 return Error(InvalidRecord);
1052 if (Ty->isMetadataTy())
1053 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1054 else if (!Ty->isVoidTy())
1055 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1057 Elts.push_back(nullptr);
1059 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1060 IsFunctionLocal = false;
1061 MDValueList.AssignValue(V, NextMDValueNo++);
1064 case bitc::METADATA_STRING: {
1065 std::string String(Record.begin(), Record.end());
1066 llvm::UpgradeMDStringConstant(String);
1067 Value *V = MDString::get(Context, String);
1068 MDValueList.AssignValue(V, NextMDValueNo++);
1071 case bitc::METADATA_KIND: {
1072 if (Record.size() < 2)
1073 return Error(InvalidRecord);
1075 unsigned Kind = Record[0];
1076 SmallString<8> Name(Record.begin()+1, Record.end());
1078 unsigned NewKind = TheModule->getMDKindID(Name.str());
1079 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1080 return Error(ConflictingMETADATA_KINDRecords);
1087 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1088 /// the LSB for dense VBR encoding.
1089 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1094 // There is no such thing as -0 with integers. "-0" really means MININT.
1098 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1099 /// values and aliases that we can.
1100 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1101 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1102 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1103 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1105 GlobalInitWorklist.swap(GlobalInits);
1106 AliasInitWorklist.swap(AliasInits);
1107 FunctionPrefixWorklist.swap(FunctionPrefixes);
1109 while (!GlobalInitWorklist.empty()) {
1110 unsigned ValID = GlobalInitWorklist.back().second;
1111 if (ValID >= ValueList.size()) {
1112 // Not ready to resolve this yet, it requires something later in the file.
1113 GlobalInits.push_back(GlobalInitWorklist.back());
1115 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1116 GlobalInitWorklist.back().first->setInitializer(C);
1118 return Error(ExpectedConstant);
1120 GlobalInitWorklist.pop_back();
1123 while (!AliasInitWorklist.empty()) {
1124 unsigned ValID = AliasInitWorklist.back().second;
1125 if (ValID >= ValueList.size()) {
1126 AliasInits.push_back(AliasInitWorklist.back());
1128 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1129 AliasInitWorklist.back().first->setAliasee(C);
1131 return Error(ExpectedConstant);
1133 AliasInitWorklist.pop_back();
1136 while (!FunctionPrefixWorklist.empty()) {
1137 unsigned ValID = FunctionPrefixWorklist.back().second;
1138 if (ValID >= ValueList.size()) {
1139 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1141 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1142 FunctionPrefixWorklist.back().first->setPrefixData(C);
1144 return Error(ExpectedConstant);
1146 FunctionPrefixWorklist.pop_back();
1149 return std::error_code();
1152 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1153 SmallVector<uint64_t, 8> Words(Vals.size());
1154 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1155 BitcodeReader::decodeSignRotatedValue);
1157 return APInt(TypeBits, Words);
1160 std::error_code BitcodeReader::ParseConstants() {
1161 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1162 return Error(InvalidRecord);
1164 SmallVector<uint64_t, 64> Record;
1166 // Read all the records for this value table.
1167 Type *CurTy = Type::getInt32Ty(Context);
1168 unsigned NextCstNo = ValueList.size();
1170 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1172 switch (Entry.Kind) {
1173 case BitstreamEntry::SubBlock: // Handled for us already.
1174 case BitstreamEntry::Error:
1175 return Error(MalformedBlock);
1176 case BitstreamEntry::EndBlock:
1177 if (NextCstNo != ValueList.size())
1178 return Error(InvalidConstantReference);
1180 // Once all the constants have been read, go through and resolve forward
1182 ValueList.ResolveConstantForwardRefs();
1183 return std::error_code();
1184 case BitstreamEntry::Record:
1185 // The interesting case.
1192 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1194 default: // Default behavior: unknown constant
1195 case bitc::CST_CODE_UNDEF: // UNDEF
1196 V = UndefValue::get(CurTy);
1198 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1200 return Error(InvalidRecord);
1201 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1202 return Error(InvalidRecord);
1203 CurTy = TypeList[Record[0]];
1204 continue; // Skip the ValueList manipulation.
1205 case bitc::CST_CODE_NULL: // NULL
1206 V = Constant::getNullValue(CurTy);
1208 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1209 if (!CurTy->isIntegerTy() || Record.empty())
1210 return Error(InvalidRecord);
1211 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1213 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1214 if (!CurTy->isIntegerTy() || Record.empty())
1215 return Error(InvalidRecord);
1217 APInt VInt = ReadWideAPInt(Record,
1218 cast<IntegerType>(CurTy)->getBitWidth());
1219 V = ConstantInt::get(Context, VInt);
1223 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1225 return Error(InvalidRecord);
1226 if (CurTy->isHalfTy())
1227 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1228 APInt(16, (uint16_t)Record[0])));
1229 else if (CurTy->isFloatTy())
1230 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1231 APInt(32, (uint32_t)Record[0])));
1232 else if (CurTy->isDoubleTy())
1233 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1234 APInt(64, Record[0])));
1235 else if (CurTy->isX86_FP80Ty()) {
1236 // Bits are not stored the same way as a normal i80 APInt, compensate.
1237 uint64_t Rearrange[2];
1238 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1239 Rearrange[1] = Record[0] >> 48;
1240 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1241 APInt(80, Rearrange)));
1242 } else if (CurTy->isFP128Ty())
1243 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1244 APInt(128, Record)));
1245 else if (CurTy->isPPC_FP128Ty())
1246 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1247 APInt(128, Record)));
1249 V = UndefValue::get(CurTy);
1253 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1255 return Error(InvalidRecord);
1257 unsigned Size = Record.size();
1258 SmallVector<Constant*, 16> Elts;
1260 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1261 for (unsigned i = 0; i != Size; ++i)
1262 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1263 STy->getElementType(i)));
1264 V = ConstantStruct::get(STy, Elts);
1265 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1266 Type *EltTy = ATy->getElementType();
1267 for (unsigned i = 0; i != Size; ++i)
1268 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1269 V = ConstantArray::get(ATy, Elts);
1270 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1271 Type *EltTy = VTy->getElementType();
1272 for (unsigned i = 0; i != Size; ++i)
1273 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1274 V = ConstantVector::get(Elts);
1276 V = UndefValue::get(CurTy);
1280 case bitc::CST_CODE_STRING: // STRING: [values]
1281 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1283 return Error(InvalidRecord);
1285 SmallString<16> Elts(Record.begin(), Record.end());
1286 V = ConstantDataArray::getString(Context, Elts,
1287 BitCode == bitc::CST_CODE_CSTRING);
1290 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1292 return Error(InvalidRecord);
1294 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1295 unsigned Size = Record.size();
1297 if (EltTy->isIntegerTy(8)) {
1298 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1299 if (isa<VectorType>(CurTy))
1300 V = ConstantDataVector::get(Context, Elts);
1302 V = ConstantDataArray::get(Context, Elts);
1303 } else if (EltTy->isIntegerTy(16)) {
1304 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1305 if (isa<VectorType>(CurTy))
1306 V = ConstantDataVector::get(Context, Elts);
1308 V = ConstantDataArray::get(Context, Elts);
1309 } else if (EltTy->isIntegerTy(32)) {
1310 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1311 if (isa<VectorType>(CurTy))
1312 V = ConstantDataVector::get(Context, Elts);
1314 V = ConstantDataArray::get(Context, Elts);
1315 } else if (EltTy->isIntegerTy(64)) {
1316 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1317 if (isa<VectorType>(CurTy))
1318 V = ConstantDataVector::get(Context, Elts);
1320 V = ConstantDataArray::get(Context, Elts);
1321 } else if (EltTy->isFloatTy()) {
1322 SmallVector<float, 16> Elts(Size);
1323 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1324 if (isa<VectorType>(CurTy))
1325 V = ConstantDataVector::get(Context, Elts);
1327 V = ConstantDataArray::get(Context, Elts);
1328 } else if (EltTy->isDoubleTy()) {
1329 SmallVector<double, 16> Elts(Size);
1330 std::transform(Record.begin(), Record.end(), Elts.begin(),
1332 if (isa<VectorType>(CurTy))
1333 V = ConstantDataVector::get(Context, Elts);
1335 V = ConstantDataArray::get(Context, Elts);
1337 return Error(InvalidTypeForValue);
1342 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1343 if (Record.size() < 3)
1344 return Error(InvalidRecord);
1345 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1347 V = UndefValue::get(CurTy); // Unknown binop.
1349 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1350 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1352 if (Record.size() >= 4) {
1353 if (Opc == Instruction::Add ||
1354 Opc == Instruction::Sub ||
1355 Opc == Instruction::Mul ||
1356 Opc == Instruction::Shl) {
1357 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1358 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1359 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1360 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1361 } else if (Opc == Instruction::SDiv ||
1362 Opc == Instruction::UDiv ||
1363 Opc == Instruction::LShr ||
1364 Opc == Instruction::AShr) {
1365 if (Record[3] & (1 << bitc::PEO_EXACT))
1366 Flags |= SDivOperator::IsExact;
1369 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1373 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1374 if (Record.size() < 3)
1375 return Error(InvalidRecord);
1376 int Opc = GetDecodedCastOpcode(Record[0]);
1378 V = UndefValue::get(CurTy); // Unknown cast.
1380 Type *OpTy = getTypeByID(Record[1]);
1382 return Error(InvalidRecord);
1383 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1384 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1385 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1389 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1390 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1391 if (Record.size() & 1)
1392 return Error(InvalidRecord);
1393 SmallVector<Constant*, 16> Elts;
1394 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1395 Type *ElTy = getTypeByID(Record[i]);
1397 return Error(InvalidRecord);
1398 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1400 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1401 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1403 bitc::CST_CODE_CE_INBOUNDS_GEP);
1406 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1407 if (Record.size() < 3)
1408 return Error(InvalidRecord);
1410 Type *SelectorTy = Type::getInt1Ty(Context);
1412 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1413 // vector. Otherwise, it must be a single bit.
1414 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1415 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1416 VTy->getNumElements());
1418 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1420 ValueList.getConstantFwdRef(Record[1],CurTy),
1421 ValueList.getConstantFwdRef(Record[2],CurTy));
1424 case bitc::CST_CODE_CE_EXTRACTELT
1425 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1426 if (Record.size() < 3)
1427 return Error(InvalidRecord);
1429 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1431 return Error(InvalidRecord);
1432 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1433 Constant *Op1 = nullptr;
1434 if (Record.size() == 4) {
1435 Type *IdxTy = getTypeByID(Record[2]);
1437 return Error(InvalidRecord);
1438 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1439 } else // TODO: Remove with llvm 4.0
1440 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1442 return Error(InvalidRecord);
1443 V = ConstantExpr::getExtractElement(Op0, Op1);
1446 case bitc::CST_CODE_CE_INSERTELT
1447 : { // CE_INSERTELT: [opval, opval, opty, opval]
1448 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1449 if (Record.size() < 3 || !OpTy)
1450 return Error(InvalidRecord);
1451 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1452 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1453 OpTy->getElementType());
1454 Constant *Op2 = nullptr;
1455 if (Record.size() == 4) {
1456 Type *IdxTy = getTypeByID(Record[2]);
1458 return Error(InvalidRecord);
1459 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1460 } else // TODO: Remove with llvm 4.0
1461 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1463 return Error(InvalidRecord);
1464 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1467 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1468 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1469 if (Record.size() < 3 || !OpTy)
1470 return Error(InvalidRecord);
1471 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1472 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1473 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1474 OpTy->getNumElements());
1475 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1476 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1479 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1480 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1482 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1483 if (Record.size() < 4 || !RTy || !OpTy)
1484 return Error(InvalidRecord);
1485 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1486 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1487 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1488 RTy->getNumElements());
1489 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1490 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1493 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1494 if (Record.size() < 4)
1495 return Error(InvalidRecord);
1496 Type *OpTy = getTypeByID(Record[0]);
1498 return Error(InvalidRecord);
1499 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1500 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1502 if (OpTy->isFPOrFPVectorTy())
1503 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1505 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1508 // This maintains backward compatibility, pre-asm dialect keywords.
1509 // FIXME: Remove with the 4.0 release.
1510 case bitc::CST_CODE_INLINEASM_OLD: {
1511 if (Record.size() < 2)
1512 return Error(InvalidRecord);
1513 std::string AsmStr, ConstrStr;
1514 bool HasSideEffects = Record[0] & 1;
1515 bool IsAlignStack = Record[0] >> 1;
1516 unsigned AsmStrSize = Record[1];
1517 if (2+AsmStrSize >= Record.size())
1518 return Error(InvalidRecord);
1519 unsigned ConstStrSize = Record[2+AsmStrSize];
1520 if (3+AsmStrSize+ConstStrSize > Record.size())
1521 return Error(InvalidRecord);
1523 for (unsigned i = 0; i != AsmStrSize; ++i)
1524 AsmStr += (char)Record[2+i];
1525 for (unsigned i = 0; i != ConstStrSize; ++i)
1526 ConstrStr += (char)Record[3+AsmStrSize+i];
1527 PointerType *PTy = cast<PointerType>(CurTy);
1528 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1529 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1532 // This version adds support for the asm dialect keywords (e.g.,
1534 case bitc::CST_CODE_INLINEASM: {
1535 if (Record.size() < 2)
1536 return Error(InvalidRecord);
1537 std::string AsmStr, ConstrStr;
1538 bool HasSideEffects = Record[0] & 1;
1539 bool IsAlignStack = (Record[0] >> 1) & 1;
1540 unsigned AsmDialect = Record[0] >> 2;
1541 unsigned AsmStrSize = Record[1];
1542 if (2+AsmStrSize >= Record.size())
1543 return Error(InvalidRecord);
1544 unsigned ConstStrSize = Record[2+AsmStrSize];
1545 if (3+AsmStrSize+ConstStrSize > Record.size())
1546 return Error(InvalidRecord);
1548 for (unsigned i = 0; i != AsmStrSize; ++i)
1549 AsmStr += (char)Record[2+i];
1550 for (unsigned i = 0; i != ConstStrSize; ++i)
1551 ConstrStr += (char)Record[3+AsmStrSize+i];
1552 PointerType *PTy = cast<PointerType>(CurTy);
1553 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1554 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1555 InlineAsm::AsmDialect(AsmDialect));
1558 case bitc::CST_CODE_BLOCKADDRESS:{
1559 if (Record.size() < 3)
1560 return Error(InvalidRecord);
1561 Type *FnTy = getTypeByID(Record[0]);
1563 return Error(InvalidRecord);
1565 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1567 return Error(InvalidRecord);
1569 // If the function is already parsed we can insert the block address right
1572 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1573 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1575 return Error(InvalidID);
1578 V = BlockAddress::get(Fn, BBI);
1580 // Otherwise insert a placeholder and remember it so it can be inserted
1581 // when the function is parsed.
1582 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1583 Type::getInt8Ty(Context),
1584 false, GlobalValue::InternalLinkage,
1586 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1593 ValueList.AssignValue(V, NextCstNo);
1598 std::error_code BitcodeReader::ParseUseLists() {
1599 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1600 return Error(InvalidRecord);
1602 SmallVector<uint64_t, 64> Record;
1604 // Read all the records.
1606 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1608 switch (Entry.Kind) {
1609 case BitstreamEntry::SubBlock: // Handled for us already.
1610 case BitstreamEntry::Error:
1611 return Error(MalformedBlock);
1612 case BitstreamEntry::EndBlock:
1613 return std::error_code();
1614 case BitstreamEntry::Record:
1615 // The interesting case.
1619 // Read a use list record.
1621 switch (Stream.readRecord(Entry.ID, Record)) {
1622 default: // Default behavior: unknown type.
1624 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1625 unsigned RecordLength = Record.size();
1626 if (RecordLength < 1)
1627 return Error(InvalidRecord);
1628 UseListRecords.push_back(Record);
1635 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1636 /// remember where it is and then skip it. This lets us lazily deserialize the
1638 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1639 // Get the function we are talking about.
1640 if (FunctionsWithBodies.empty())
1641 return Error(InsufficientFunctionProtos);
1643 Function *Fn = FunctionsWithBodies.back();
1644 FunctionsWithBodies.pop_back();
1646 // Save the current stream state.
1647 uint64_t CurBit = Stream.GetCurrentBitNo();
1648 DeferredFunctionInfo[Fn] = CurBit;
1650 // Skip over the function block for now.
1651 if (Stream.SkipBlock())
1652 return Error(InvalidRecord);
1653 return std::error_code();
1656 std::error_code BitcodeReader::GlobalCleanup() {
1657 // Patch the initializers for globals and aliases up.
1658 ResolveGlobalAndAliasInits();
1659 if (!GlobalInits.empty() || !AliasInits.empty())
1660 return Error(MalformedGlobalInitializerSet);
1662 // Look for intrinsic functions which need to be upgraded at some point
1663 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1666 if (UpgradeIntrinsicFunction(FI, NewFn))
1667 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1670 // Look for global variables which need to be renamed.
1671 for (Module::global_iterator
1672 GI = TheModule->global_begin(), GE = TheModule->global_end();
1674 GlobalVariable *GV = GI++;
1675 UpgradeGlobalVariable(GV);
1678 // Force deallocation of memory for these vectors to favor the client that
1679 // want lazy deserialization.
1680 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1681 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1682 return std::error_code();
1685 std::error_code BitcodeReader::ParseModule(bool Resume) {
1687 Stream.JumpToBit(NextUnreadBit);
1688 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1689 return Error(InvalidRecord);
1691 SmallVector<uint64_t, 64> Record;
1692 std::vector<std::string> SectionTable;
1693 std::vector<std::string> GCTable;
1695 // Read all the records for this module.
1697 BitstreamEntry Entry = Stream.advance();
1699 switch (Entry.Kind) {
1700 case BitstreamEntry::Error:
1701 return Error(MalformedBlock);
1702 case BitstreamEntry::EndBlock:
1703 return GlobalCleanup();
1705 case BitstreamEntry::SubBlock:
1707 default: // Skip unknown content.
1708 if (Stream.SkipBlock())
1709 return Error(InvalidRecord);
1711 case bitc::BLOCKINFO_BLOCK_ID:
1712 if (Stream.ReadBlockInfoBlock())
1713 return Error(MalformedBlock);
1715 case bitc::PARAMATTR_BLOCK_ID:
1716 if (std::error_code EC = ParseAttributeBlock())
1719 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1720 if (std::error_code EC = ParseAttributeGroupBlock())
1723 case bitc::TYPE_BLOCK_ID_NEW:
1724 if (std::error_code EC = ParseTypeTable())
1727 case bitc::VALUE_SYMTAB_BLOCK_ID:
1728 if (std::error_code EC = ParseValueSymbolTable())
1730 SeenValueSymbolTable = true;
1732 case bitc::CONSTANTS_BLOCK_ID:
1733 if (std::error_code EC = ParseConstants())
1735 if (std::error_code EC = ResolveGlobalAndAliasInits())
1738 case bitc::METADATA_BLOCK_ID:
1739 if (std::error_code EC = ParseMetadata())
1742 case bitc::FUNCTION_BLOCK_ID:
1743 // If this is the first function body we've seen, reverse the
1744 // FunctionsWithBodies list.
1745 if (!SeenFirstFunctionBody) {
1746 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1747 if (std::error_code EC = GlobalCleanup())
1749 SeenFirstFunctionBody = true;
1752 if (std::error_code EC = RememberAndSkipFunctionBody())
1754 // For streaming bitcode, suspend parsing when we reach the function
1755 // bodies. Subsequent materialization calls will resume it when
1756 // necessary. For streaming, the function bodies must be at the end of
1757 // the bitcode. If the bitcode file is old, the symbol table will be
1758 // at the end instead and will not have been seen yet. In this case,
1759 // just finish the parse now.
1760 if (LazyStreamer && SeenValueSymbolTable) {
1761 NextUnreadBit = Stream.GetCurrentBitNo();
1762 return std::error_code();
1765 case bitc::USELIST_BLOCK_ID:
1766 if (std::error_code EC = ParseUseLists())
1772 case BitstreamEntry::Record:
1773 // The interesting case.
1779 switch (Stream.readRecord(Entry.ID, Record)) {
1780 default: break; // Default behavior, ignore unknown content.
1781 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1782 if (Record.size() < 1)
1783 return Error(InvalidRecord);
1784 // Only version #0 and #1 are supported so far.
1785 unsigned module_version = Record[0];
1786 switch (module_version) {
1788 return Error(InvalidValue);
1790 UseRelativeIDs = false;
1793 UseRelativeIDs = true;
1798 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1800 if (ConvertToString(Record, 0, S))
1801 return Error(InvalidRecord);
1802 TheModule->setTargetTriple(S);
1805 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1807 if (ConvertToString(Record, 0, S))
1808 return Error(InvalidRecord);
1809 TheModule->setDataLayout(S);
1812 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1814 if (ConvertToString(Record, 0, S))
1815 return Error(InvalidRecord);
1816 TheModule->setModuleInlineAsm(S);
1819 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1820 // FIXME: Remove in 4.0.
1822 if (ConvertToString(Record, 0, S))
1823 return Error(InvalidRecord);
1827 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1829 if (ConvertToString(Record, 0, S))
1830 return Error(InvalidRecord);
1831 SectionTable.push_back(S);
1834 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1836 if (ConvertToString(Record, 0, S))
1837 return Error(InvalidRecord);
1838 GCTable.push_back(S);
1841 // GLOBALVAR: [pointer type, isconst, initid,
1842 // linkage, alignment, section, visibility, threadlocal,
1843 // unnamed_addr, dllstorageclass]
1844 case bitc::MODULE_CODE_GLOBALVAR: {
1845 if (Record.size() < 6)
1846 return Error(InvalidRecord);
1847 Type *Ty = getTypeByID(Record[0]);
1849 return Error(InvalidRecord);
1850 if (!Ty->isPointerTy())
1851 return Error(InvalidTypeForValue);
1852 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1853 Ty = cast<PointerType>(Ty)->getElementType();
1855 bool isConstant = Record[1];
1856 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1857 unsigned Alignment = (1 << Record[4]) >> 1;
1858 std::string Section;
1860 if (Record[5]-1 >= SectionTable.size())
1861 return Error(InvalidID);
1862 Section = SectionTable[Record[5]-1];
1864 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1865 // Local linkage must have default visibility.
1866 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1867 // FIXME: Change to an error if non-default in 4.0.
1868 Visibility = GetDecodedVisibility(Record[6]);
1870 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1871 if (Record.size() > 7)
1872 TLM = GetDecodedThreadLocalMode(Record[7]);
1874 bool UnnamedAddr = false;
1875 if (Record.size() > 8)
1876 UnnamedAddr = Record[8];
1878 bool ExternallyInitialized = false;
1879 if (Record.size() > 9)
1880 ExternallyInitialized = Record[9];
1882 GlobalVariable *NewGV =
1883 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1884 TLM, AddressSpace, ExternallyInitialized);
1885 NewGV->setAlignment(Alignment);
1886 if (!Section.empty())
1887 NewGV->setSection(Section);
1888 NewGV->setVisibility(Visibility);
1889 NewGV->setUnnamedAddr(UnnamedAddr);
1891 if (Record.size() > 10)
1892 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1894 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1896 ValueList.push_back(NewGV);
1898 // Remember which value to use for the global initializer.
1899 if (unsigned InitID = Record[2])
1900 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1903 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1904 // alignment, section, visibility, gc, unnamed_addr,
1906 case bitc::MODULE_CODE_FUNCTION: {
1907 if (Record.size() < 8)
1908 return Error(InvalidRecord);
1909 Type *Ty = getTypeByID(Record[0]);
1911 return Error(InvalidRecord);
1912 if (!Ty->isPointerTy())
1913 return Error(InvalidTypeForValue);
1915 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1917 return Error(InvalidTypeForValue);
1919 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1922 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1923 bool isProto = Record[2];
1924 Func->setLinkage(GetDecodedLinkage(Record[3]));
1925 Func->setAttributes(getAttributes(Record[4]));
1927 Func->setAlignment((1 << Record[5]) >> 1);
1929 if (Record[6]-1 >= SectionTable.size())
1930 return Error(InvalidID);
1931 Func->setSection(SectionTable[Record[6]-1]);
1933 // Local linkage must have default visibility.
1934 if (!Func->hasLocalLinkage())
1935 // FIXME: Change to an error if non-default in 4.0.
1936 Func->setVisibility(GetDecodedVisibility(Record[7]));
1937 if (Record.size() > 8 && Record[8]) {
1938 if (Record[8]-1 > GCTable.size())
1939 return Error(InvalidID);
1940 Func->setGC(GCTable[Record[8]-1].c_str());
1942 bool UnnamedAddr = false;
1943 if (Record.size() > 9)
1944 UnnamedAddr = Record[9];
1945 Func->setUnnamedAddr(UnnamedAddr);
1946 if (Record.size() > 10 && Record[10] != 0)
1947 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1949 if (Record.size() > 11)
1950 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1952 UpgradeDLLImportExportLinkage(Func, Record[3]);
1954 ValueList.push_back(Func);
1956 // If this is a function with a body, remember the prototype we are
1957 // creating now, so that we can match up the body with them later.
1959 FunctionsWithBodies.push_back(Func);
1960 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1964 // ALIAS: [alias type, aliasee val#, linkage]
1965 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
1966 case bitc::MODULE_CODE_ALIAS: {
1967 if (Record.size() < 3)
1968 return Error(InvalidRecord);
1969 Type *Ty = getTypeByID(Record[0]);
1971 return Error(InvalidRecord);
1972 auto *PTy = dyn_cast<PointerType>(Ty);
1974 return Error(InvalidTypeForValue);
1977 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1978 GetDecodedLinkage(Record[2]), "", TheModule);
1979 // Old bitcode files didn't have visibility field.
1980 // Local linkage must have default visibility.
1981 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
1982 // FIXME: Change to an error if non-default in 4.0.
1983 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1984 if (Record.size() > 4)
1985 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
1987 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
1988 if (Record.size() > 5)
1989 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
1990 if (Record.size() > 6)
1991 NewGA->setUnnamedAddr(Record[6]);
1992 ValueList.push_back(NewGA);
1993 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1996 /// MODULE_CODE_PURGEVALS: [numvals]
1997 case bitc::MODULE_CODE_PURGEVALS:
1998 // Trim down the value list to the specified size.
1999 if (Record.size() < 1 || Record[0] > ValueList.size())
2000 return Error(InvalidRecord);
2001 ValueList.shrinkTo(Record[0]);
2008 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2009 TheModule = nullptr;
2011 if (std::error_code EC = InitStream())
2014 // Sniff for the signature.
2015 if (Stream.Read(8) != 'B' ||
2016 Stream.Read(8) != 'C' ||
2017 Stream.Read(4) != 0x0 ||
2018 Stream.Read(4) != 0xC ||
2019 Stream.Read(4) != 0xE ||
2020 Stream.Read(4) != 0xD)
2021 return Error(InvalidBitcodeSignature);
2023 // We expect a number of well-defined blocks, though we don't necessarily
2024 // need to understand them all.
2026 if (Stream.AtEndOfStream())
2027 return std::error_code();
2029 BitstreamEntry Entry =
2030 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2032 switch (Entry.Kind) {
2033 case BitstreamEntry::Error:
2034 return Error(MalformedBlock);
2035 case BitstreamEntry::EndBlock:
2036 return std::error_code();
2038 case BitstreamEntry::SubBlock:
2040 case bitc::BLOCKINFO_BLOCK_ID:
2041 if (Stream.ReadBlockInfoBlock())
2042 return Error(MalformedBlock);
2044 case bitc::MODULE_BLOCK_ID:
2045 // Reject multiple MODULE_BLOCK's in a single bitstream.
2047 return Error(InvalidMultipleBlocks);
2049 if (std::error_code EC = ParseModule(false))
2052 return std::error_code();
2055 if (Stream.SkipBlock())
2056 return Error(InvalidRecord);
2060 case BitstreamEntry::Record:
2061 // There should be no records in the top-level of blocks.
2063 // The ranlib in Xcode 4 will align archive members by appending newlines
2064 // to the end of them. If this file size is a multiple of 4 but not 8, we
2065 // have to read and ignore these final 4 bytes :-(
2066 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2067 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2068 Stream.AtEndOfStream())
2069 return std::error_code();
2071 return Error(InvalidRecord);
2076 std::error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2077 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2078 return Error(InvalidRecord);
2080 SmallVector<uint64_t, 64> Record;
2082 // Read all the records for this module.
2084 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2086 switch (Entry.Kind) {
2087 case BitstreamEntry::SubBlock: // Handled for us already.
2088 case BitstreamEntry::Error:
2089 return Error(MalformedBlock);
2090 case BitstreamEntry::EndBlock:
2091 return std::error_code();
2092 case BitstreamEntry::Record:
2093 // The interesting case.
2098 switch (Stream.readRecord(Entry.ID, Record)) {
2099 default: break; // Default behavior, ignore unknown content.
2100 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2102 if (ConvertToString(Record, 0, S))
2103 return Error(InvalidRecord);
2112 std::error_code BitcodeReader::ParseTriple(std::string &Triple) {
2113 if (std::error_code EC = InitStream())
2116 // Sniff for the signature.
2117 if (Stream.Read(8) != 'B' ||
2118 Stream.Read(8) != 'C' ||
2119 Stream.Read(4) != 0x0 ||
2120 Stream.Read(4) != 0xC ||
2121 Stream.Read(4) != 0xE ||
2122 Stream.Read(4) != 0xD)
2123 return Error(InvalidBitcodeSignature);
2125 // We expect a number of well-defined blocks, though we don't necessarily
2126 // need to understand them all.
2128 BitstreamEntry Entry = Stream.advance();
2130 switch (Entry.Kind) {
2131 case BitstreamEntry::Error:
2132 return Error(MalformedBlock);
2133 case BitstreamEntry::EndBlock:
2134 return std::error_code();
2136 case BitstreamEntry::SubBlock:
2137 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2138 return ParseModuleTriple(Triple);
2140 // Ignore other sub-blocks.
2141 if (Stream.SkipBlock())
2142 return Error(MalformedBlock);
2145 case BitstreamEntry::Record:
2146 Stream.skipRecord(Entry.ID);
2152 /// ParseMetadataAttachment - Parse metadata attachments.
2153 std::error_code BitcodeReader::ParseMetadataAttachment() {
2154 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2155 return Error(InvalidRecord);
2157 SmallVector<uint64_t, 64> Record;
2159 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2161 switch (Entry.Kind) {
2162 case BitstreamEntry::SubBlock: // Handled for us already.
2163 case BitstreamEntry::Error:
2164 return Error(MalformedBlock);
2165 case BitstreamEntry::EndBlock:
2166 return std::error_code();
2167 case BitstreamEntry::Record:
2168 // The interesting case.
2172 // Read a metadata attachment record.
2174 switch (Stream.readRecord(Entry.ID, Record)) {
2175 default: // Default behavior: ignore.
2177 case bitc::METADATA_ATTACHMENT: {
2178 unsigned RecordLength = Record.size();
2179 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2180 return Error(InvalidRecord);
2181 Instruction *Inst = InstructionList[Record[0]];
2182 for (unsigned i = 1; i != RecordLength; i = i+2) {
2183 unsigned Kind = Record[i];
2184 DenseMap<unsigned, unsigned>::iterator I =
2185 MDKindMap.find(Kind);
2186 if (I == MDKindMap.end())
2187 return Error(InvalidID);
2188 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2189 Inst->setMetadata(I->second, cast<MDNode>(Node));
2190 if (I->second == LLVMContext::MD_tbaa)
2191 InstsWithTBAATag.push_back(Inst);
2199 /// ParseFunctionBody - Lazily parse the specified function body block.
2200 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2201 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2202 return Error(InvalidRecord);
2204 InstructionList.clear();
2205 unsigned ModuleValueListSize = ValueList.size();
2206 unsigned ModuleMDValueListSize = MDValueList.size();
2208 // Add all the function arguments to the value table.
2209 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2210 ValueList.push_back(I);
2212 unsigned NextValueNo = ValueList.size();
2213 BasicBlock *CurBB = nullptr;
2214 unsigned CurBBNo = 0;
2218 // Read all the records.
2219 SmallVector<uint64_t, 64> Record;
2221 BitstreamEntry Entry = Stream.advance();
2223 switch (Entry.Kind) {
2224 case BitstreamEntry::Error:
2225 return Error(MalformedBlock);
2226 case BitstreamEntry::EndBlock:
2227 goto OutOfRecordLoop;
2229 case BitstreamEntry::SubBlock:
2231 default: // Skip unknown content.
2232 if (Stream.SkipBlock())
2233 return Error(InvalidRecord);
2235 case bitc::CONSTANTS_BLOCK_ID:
2236 if (std::error_code EC = ParseConstants())
2238 NextValueNo = ValueList.size();
2240 case bitc::VALUE_SYMTAB_BLOCK_ID:
2241 if (std::error_code EC = ParseValueSymbolTable())
2244 case bitc::METADATA_ATTACHMENT_ID:
2245 if (std::error_code EC = ParseMetadataAttachment())
2248 case bitc::METADATA_BLOCK_ID:
2249 if (std::error_code EC = ParseMetadata())
2255 case BitstreamEntry::Record:
2256 // The interesting case.
2262 Instruction *I = nullptr;
2263 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2265 default: // Default behavior: reject
2266 return Error(InvalidValue);
2267 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2268 if (Record.size() < 1 || Record[0] == 0)
2269 return Error(InvalidRecord);
2270 // Create all the basic blocks for the function.
2271 FunctionBBs.resize(Record[0]);
2272 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2273 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2274 CurBB = FunctionBBs[0];
2277 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2278 // This record indicates that the last instruction is at the same
2279 // location as the previous instruction with a location.
2282 // Get the last instruction emitted.
2283 if (CurBB && !CurBB->empty())
2285 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2286 !FunctionBBs[CurBBNo-1]->empty())
2287 I = &FunctionBBs[CurBBNo-1]->back();
2290 return Error(InvalidRecord);
2291 I->setDebugLoc(LastLoc);
2295 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2296 I = nullptr; // Get the last instruction emitted.
2297 if (CurBB && !CurBB->empty())
2299 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2300 !FunctionBBs[CurBBNo-1]->empty())
2301 I = &FunctionBBs[CurBBNo-1]->back();
2302 if (!I || Record.size() < 4)
2303 return Error(InvalidRecord);
2305 unsigned Line = Record[0], Col = Record[1];
2306 unsigned ScopeID = Record[2], IAID = Record[3];
2308 MDNode *Scope = nullptr, *IA = nullptr;
2309 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2310 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2311 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2312 I->setDebugLoc(LastLoc);
2317 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2320 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2321 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2322 OpNum+1 > Record.size())
2323 return Error(InvalidRecord);
2325 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2327 return Error(InvalidRecord);
2328 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2329 InstructionList.push_back(I);
2330 if (OpNum < Record.size()) {
2331 if (Opc == Instruction::Add ||
2332 Opc == Instruction::Sub ||
2333 Opc == Instruction::Mul ||
2334 Opc == Instruction::Shl) {
2335 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2336 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2337 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2338 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2339 } else if (Opc == Instruction::SDiv ||
2340 Opc == Instruction::UDiv ||
2341 Opc == Instruction::LShr ||
2342 Opc == Instruction::AShr) {
2343 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2344 cast<BinaryOperator>(I)->setIsExact(true);
2345 } else if (isa<FPMathOperator>(I)) {
2347 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2348 FMF.setUnsafeAlgebra();
2349 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2351 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2353 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2354 FMF.setNoSignedZeros();
2355 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2356 FMF.setAllowReciprocal();
2358 I->setFastMathFlags(FMF);
2364 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2367 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2368 OpNum+2 != Record.size())
2369 return Error(InvalidRecord);
2371 Type *ResTy = getTypeByID(Record[OpNum]);
2372 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2373 if (Opc == -1 || !ResTy)
2374 return Error(InvalidRecord);
2375 Instruction *Temp = nullptr;
2376 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2378 InstructionList.push_back(Temp);
2379 CurBB->getInstList().push_back(Temp);
2382 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2384 InstructionList.push_back(I);
2387 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2388 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2391 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2392 return Error(InvalidRecord);
2394 SmallVector<Value*, 16> GEPIdx;
2395 while (OpNum != Record.size()) {
2397 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2398 return Error(InvalidRecord);
2399 GEPIdx.push_back(Op);
2402 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2403 InstructionList.push_back(I);
2404 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2405 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2409 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2410 // EXTRACTVAL: [opty, opval, n x indices]
2413 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2414 return Error(InvalidRecord);
2416 SmallVector<unsigned, 4> EXTRACTVALIdx;
2417 for (unsigned RecSize = Record.size();
2418 OpNum != RecSize; ++OpNum) {
2419 uint64_t Index = Record[OpNum];
2420 if ((unsigned)Index != Index)
2421 return Error(InvalidValue);
2422 EXTRACTVALIdx.push_back((unsigned)Index);
2425 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2426 InstructionList.push_back(I);
2430 case bitc::FUNC_CODE_INST_INSERTVAL: {
2431 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2434 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2435 return Error(InvalidRecord);
2437 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2438 return Error(InvalidRecord);
2440 SmallVector<unsigned, 4> INSERTVALIdx;
2441 for (unsigned RecSize = Record.size();
2442 OpNum != RecSize; ++OpNum) {
2443 uint64_t Index = Record[OpNum];
2444 if ((unsigned)Index != Index)
2445 return Error(InvalidValue);
2446 INSERTVALIdx.push_back((unsigned)Index);
2449 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2450 InstructionList.push_back(I);
2454 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2455 // obsolete form of select
2456 // handles select i1 ... in old bitcode
2458 Value *TrueVal, *FalseVal, *Cond;
2459 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2460 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2461 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2462 return Error(InvalidRecord);
2464 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2465 InstructionList.push_back(I);
2469 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2470 // new form of select
2471 // handles select i1 or select [N x i1]
2473 Value *TrueVal, *FalseVal, *Cond;
2474 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2475 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2476 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2477 return Error(InvalidRecord);
2479 // select condition can be either i1 or [N x i1]
2480 if (VectorType* vector_type =
2481 dyn_cast<VectorType>(Cond->getType())) {
2483 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2484 return Error(InvalidTypeForValue);
2487 if (Cond->getType() != Type::getInt1Ty(Context))
2488 return Error(InvalidTypeForValue);
2491 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2492 InstructionList.push_back(I);
2496 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2499 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2500 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2501 return Error(InvalidRecord);
2502 I = ExtractElementInst::Create(Vec, Idx);
2503 InstructionList.push_back(I);
2507 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2509 Value *Vec, *Elt, *Idx;
2510 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2511 popValue(Record, OpNum, NextValueNo,
2512 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2513 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2514 return Error(InvalidRecord);
2515 I = InsertElementInst::Create(Vec, Elt, Idx);
2516 InstructionList.push_back(I);
2520 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2522 Value *Vec1, *Vec2, *Mask;
2523 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2524 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2525 return Error(InvalidRecord);
2527 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2528 return Error(InvalidRecord);
2529 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2530 InstructionList.push_back(I);
2534 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2535 // Old form of ICmp/FCmp returning bool
2536 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2537 // both legal on vectors but had different behaviour.
2538 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2539 // FCmp/ICmp returning bool or vector of bool
2543 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2544 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2545 OpNum+1 != Record.size())
2546 return Error(InvalidRecord);
2548 if (LHS->getType()->isFPOrFPVectorTy())
2549 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2551 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2552 InstructionList.push_back(I);
2556 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2558 unsigned Size = Record.size();
2560 I = ReturnInst::Create(Context);
2561 InstructionList.push_back(I);
2566 Value *Op = nullptr;
2567 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2568 return Error(InvalidRecord);
2569 if (OpNum != Record.size())
2570 return Error(InvalidRecord);
2572 I = ReturnInst::Create(Context, Op);
2573 InstructionList.push_back(I);
2576 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2577 if (Record.size() != 1 && Record.size() != 3)
2578 return Error(InvalidRecord);
2579 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2581 return Error(InvalidRecord);
2583 if (Record.size() == 1) {
2584 I = BranchInst::Create(TrueDest);
2585 InstructionList.push_back(I);
2588 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2589 Value *Cond = getValue(Record, 2, NextValueNo,
2590 Type::getInt1Ty(Context));
2591 if (!FalseDest || !Cond)
2592 return Error(InvalidRecord);
2593 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2594 InstructionList.push_back(I);
2598 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2600 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2601 // "New" SwitchInst format with case ranges. The changes to write this
2602 // format were reverted but we still recognize bitcode that uses it.
2603 // Hopefully someday we will have support for case ranges and can use
2604 // this format again.
2606 Type *OpTy = getTypeByID(Record[1]);
2607 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2609 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2610 BasicBlock *Default = getBasicBlock(Record[3]);
2611 if (!OpTy || !Cond || !Default)
2612 return Error(InvalidRecord);
2614 unsigned NumCases = Record[4];
2616 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2617 InstructionList.push_back(SI);
2619 unsigned CurIdx = 5;
2620 for (unsigned i = 0; i != NumCases; ++i) {
2621 SmallVector<ConstantInt*, 1> CaseVals;
2622 unsigned NumItems = Record[CurIdx++];
2623 for (unsigned ci = 0; ci != NumItems; ++ci) {
2624 bool isSingleNumber = Record[CurIdx++];
2627 unsigned ActiveWords = 1;
2628 if (ValueBitWidth > 64)
2629 ActiveWords = Record[CurIdx++];
2630 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2632 CurIdx += ActiveWords;
2634 if (!isSingleNumber) {
2636 if (ValueBitWidth > 64)
2637 ActiveWords = Record[CurIdx++];
2639 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2641 CurIdx += ActiveWords;
2643 // FIXME: It is not clear whether values in the range should be
2644 // compared as signed or unsigned values. The partially
2645 // implemented changes that used this format in the past used
2646 // unsigned comparisons.
2647 for ( ; Low.ule(High); ++Low)
2648 CaseVals.push_back(ConstantInt::get(Context, Low));
2650 CaseVals.push_back(ConstantInt::get(Context, Low));
2652 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2653 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2654 cve = CaseVals.end(); cvi != cve; ++cvi)
2655 SI->addCase(*cvi, DestBB);
2661 // Old SwitchInst format without case ranges.
2663 if (Record.size() < 3 || (Record.size() & 1) == 0)
2664 return Error(InvalidRecord);
2665 Type *OpTy = getTypeByID(Record[0]);
2666 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2667 BasicBlock *Default = getBasicBlock(Record[2]);
2668 if (!OpTy || !Cond || !Default)
2669 return Error(InvalidRecord);
2670 unsigned NumCases = (Record.size()-3)/2;
2671 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2672 InstructionList.push_back(SI);
2673 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2674 ConstantInt *CaseVal =
2675 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2676 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2677 if (!CaseVal || !DestBB) {
2679 return Error(InvalidRecord);
2681 SI->addCase(CaseVal, DestBB);
2686 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2687 if (Record.size() < 2)
2688 return Error(InvalidRecord);
2689 Type *OpTy = getTypeByID(Record[0]);
2690 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2691 if (!OpTy || !Address)
2692 return Error(InvalidRecord);
2693 unsigned NumDests = Record.size()-2;
2694 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2695 InstructionList.push_back(IBI);
2696 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2697 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2698 IBI->addDestination(DestBB);
2701 return Error(InvalidRecord);
2708 case bitc::FUNC_CODE_INST_INVOKE: {
2709 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2710 if (Record.size() < 4)
2711 return Error(InvalidRecord);
2712 AttributeSet PAL = getAttributes(Record[0]);
2713 unsigned CCInfo = Record[1];
2714 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2715 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2719 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2720 return Error(InvalidRecord);
2722 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2723 FunctionType *FTy = !CalleeTy ? nullptr :
2724 dyn_cast<FunctionType>(CalleeTy->getElementType());
2726 // Check that the right number of fixed parameters are here.
2727 if (!FTy || !NormalBB || !UnwindBB ||
2728 Record.size() < OpNum+FTy->getNumParams())
2729 return Error(InvalidRecord);
2731 SmallVector<Value*, 16> Ops;
2732 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2733 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2734 FTy->getParamType(i)));
2736 return Error(InvalidRecord);
2739 if (!FTy->isVarArg()) {
2740 if (Record.size() != OpNum)
2741 return Error(InvalidRecord);
2743 // Read type/value pairs for varargs params.
2744 while (OpNum != Record.size()) {
2746 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2747 return Error(InvalidRecord);
2752 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2753 InstructionList.push_back(I);
2754 cast<InvokeInst>(I)->setCallingConv(
2755 static_cast<CallingConv::ID>(CCInfo));
2756 cast<InvokeInst>(I)->setAttributes(PAL);
2759 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2761 Value *Val = nullptr;
2762 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2763 return Error(InvalidRecord);
2764 I = ResumeInst::Create(Val);
2765 InstructionList.push_back(I);
2768 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2769 I = new UnreachableInst(Context);
2770 InstructionList.push_back(I);
2772 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2773 if (Record.size() < 1 || ((Record.size()-1)&1))
2774 return Error(InvalidRecord);
2775 Type *Ty = getTypeByID(Record[0]);
2777 return Error(InvalidRecord);
2779 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2780 InstructionList.push_back(PN);
2782 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2784 // With the new function encoding, it is possible that operands have
2785 // negative IDs (for forward references). Use a signed VBR
2786 // representation to keep the encoding small.
2788 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2790 V = getValue(Record, 1+i, NextValueNo, Ty);
2791 BasicBlock *BB = getBasicBlock(Record[2+i]);
2793 return Error(InvalidRecord);
2794 PN->addIncoming(V, BB);
2800 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2801 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2803 if (Record.size() < 4)
2804 return Error(InvalidRecord);
2805 Type *Ty = getTypeByID(Record[Idx++]);
2807 return Error(InvalidRecord);
2808 Value *PersFn = nullptr;
2809 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2810 return Error(InvalidRecord);
2812 bool IsCleanup = !!Record[Idx++];
2813 unsigned NumClauses = Record[Idx++];
2814 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2815 LP->setCleanup(IsCleanup);
2816 for (unsigned J = 0; J != NumClauses; ++J) {
2817 LandingPadInst::ClauseType CT =
2818 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2821 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2823 return Error(InvalidRecord);
2826 assert((CT != LandingPadInst::Catch ||
2827 !isa<ArrayType>(Val->getType())) &&
2828 "Catch clause has a invalid type!");
2829 assert((CT != LandingPadInst::Filter ||
2830 isa<ArrayType>(Val->getType())) &&
2831 "Filter clause has invalid type!");
2832 LP->addClause(cast<Constant>(Val));
2836 InstructionList.push_back(I);
2840 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2841 if (Record.size() != 4)
2842 return Error(InvalidRecord);
2844 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2845 Type *OpTy = getTypeByID(Record[1]);
2846 Value *Size = getFnValueByID(Record[2], OpTy);
2847 unsigned Align = Record[3];
2849 return Error(InvalidRecord);
2850 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2851 InstructionList.push_back(I);
2854 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2857 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2858 OpNum+2 != Record.size())
2859 return Error(InvalidRecord);
2861 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2862 InstructionList.push_back(I);
2865 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2866 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2869 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2870 OpNum+4 != Record.size())
2871 return Error(InvalidRecord);
2874 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2875 if (Ordering == NotAtomic || Ordering == Release ||
2876 Ordering == AcquireRelease)
2877 return Error(InvalidRecord);
2878 if (Ordering != NotAtomic && Record[OpNum] == 0)
2879 return Error(InvalidRecord);
2880 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2882 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2883 Ordering, SynchScope);
2884 InstructionList.push_back(I);
2887 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2890 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2891 popValue(Record, OpNum, NextValueNo,
2892 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2893 OpNum+2 != Record.size())
2894 return Error(InvalidRecord);
2896 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2897 InstructionList.push_back(I);
2900 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2901 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2904 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2905 popValue(Record, OpNum, NextValueNo,
2906 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2907 OpNum+4 != Record.size())
2908 return Error(InvalidRecord);
2910 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2911 if (Ordering == NotAtomic || Ordering == Acquire ||
2912 Ordering == AcquireRelease)
2913 return Error(InvalidRecord);
2914 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2915 if (Ordering != NotAtomic && Record[OpNum] == 0)
2916 return Error(InvalidRecord);
2918 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2919 Ordering, SynchScope);
2920 InstructionList.push_back(I);
2923 case bitc::FUNC_CODE_INST_CMPXCHG: {
2924 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2925 // failureordering?, isweak?]
2927 Value *Ptr, *Cmp, *New;
2928 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2929 popValue(Record, OpNum, NextValueNo,
2930 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2931 popValue(Record, OpNum, NextValueNo,
2932 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2933 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
2934 return Error(InvalidRecord);
2935 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2936 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2937 return Error(InvalidRecord);
2938 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2940 AtomicOrdering FailureOrdering;
2941 if (Record.size() < 7)
2943 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2945 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
2947 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
2949 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2951 if (Record.size() < 8) {
2952 // Before weak cmpxchgs existed, the instruction simply returned the
2953 // value loaded from memory, so bitcode files from that era will be
2954 // expecting the first component of a modern cmpxchg.
2955 CurBB->getInstList().push_back(I);
2956 I = ExtractValueInst::Create(I, 0);
2958 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
2961 InstructionList.push_back(I);
2964 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2965 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2968 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2969 popValue(Record, OpNum, NextValueNo,
2970 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2971 OpNum+4 != Record.size())
2972 return Error(InvalidRecord);
2973 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2974 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2975 Operation > AtomicRMWInst::LAST_BINOP)
2976 return Error(InvalidRecord);
2977 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2978 if (Ordering == NotAtomic || Ordering == Unordered)
2979 return Error(InvalidRecord);
2980 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2981 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2982 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2983 InstructionList.push_back(I);
2986 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2987 if (2 != Record.size())
2988 return Error(InvalidRecord);
2989 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2990 if (Ordering == NotAtomic || Ordering == Unordered ||
2991 Ordering == Monotonic)
2992 return Error(InvalidRecord);
2993 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2994 I = new FenceInst(Context, Ordering, SynchScope);
2995 InstructionList.push_back(I);
2998 case bitc::FUNC_CODE_INST_CALL: {
2999 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3000 if (Record.size() < 3)
3001 return Error(InvalidRecord);
3003 AttributeSet PAL = getAttributes(Record[0]);
3004 unsigned CCInfo = Record[1];
3008 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3009 return Error(InvalidRecord);
3011 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3012 FunctionType *FTy = nullptr;
3013 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3014 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3015 return Error(InvalidRecord);
3017 SmallVector<Value*, 16> Args;
3018 // Read the fixed params.
3019 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3020 if (FTy->getParamType(i)->isLabelTy())
3021 Args.push_back(getBasicBlock(Record[OpNum]));
3023 Args.push_back(getValue(Record, OpNum, NextValueNo,
3024 FTy->getParamType(i)));
3026 return Error(InvalidRecord);
3029 // Read type/value pairs for varargs params.
3030 if (!FTy->isVarArg()) {
3031 if (OpNum != Record.size())
3032 return Error(InvalidRecord);
3034 while (OpNum != Record.size()) {
3036 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3037 return Error(InvalidRecord);
3042 I = CallInst::Create(Callee, Args);
3043 InstructionList.push_back(I);
3044 cast<CallInst>(I)->setCallingConv(
3045 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3046 CallInst::TailCallKind TCK = CallInst::TCK_None;
3048 TCK = CallInst::TCK_Tail;
3049 if (CCInfo & (1 << 14))
3050 TCK = CallInst::TCK_MustTail;
3051 cast<CallInst>(I)->setTailCallKind(TCK);
3052 cast<CallInst>(I)->setAttributes(PAL);
3055 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3056 if (Record.size() < 3)
3057 return Error(InvalidRecord);
3058 Type *OpTy = getTypeByID(Record[0]);
3059 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3060 Type *ResTy = getTypeByID(Record[2]);
3061 if (!OpTy || !Op || !ResTy)
3062 return Error(InvalidRecord);
3063 I = new VAArgInst(Op, ResTy);
3064 InstructionList.push_back(I);
3069 // Add instruction to end of current BB. If there is no current BB, reject
3073 return Error(InvalidInstructionWithNoBB);
3075 CurBB->getInstList().push_back(I);
3077 // If this was a terminator instruction, move to the next block.
3078 if (isa<TerminatorInst>(I)) {
3080 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3083 // Non-void values get registered in the value table for future use.
3084 if (I && !I->getType()->isVoidTy())
3085 ValueList.AssignValue(I, NextValueNo++);
3090 // Check the function list for unresolved values.
3091 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3092 if (!A->getParent()) {
3093 // We found at least one unresolved value. Nuke them all to avoid leaks.
3094 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3095 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3096 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3100 return Error(NeverResolvedValueFoundInFunction);
3104 // FIXME: Check for unresolved forward-declared metadata references
3105 // and clean up leaks.
3107 // See if anything took the address of blocks in this function. If so,
3108 // resolve them now.
3109 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3110 BlockAddrFwdRefs.find(F);
3111 if (BAFRI != BlockAddrFwdRefs.end()) {
3112 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3113 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3114 unsigned BlockIdx = RefList[i].first;
3115 if (BlockIdx >= FunctionBBs.size())
3116 return Error(InvalidID);
3118 GlobalVariable *FwdRef = RefList[i].second;
3119 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3120 FwdRef->eraseFromParent();
3123 BlockAddrFwdRefs.erase(BAFRI);
3126 // Trim the value list down to the size it was before we parsed this function.
3127 ValueList.shrinkTo(ModuleValueListSize);
3128 MDValueList.shrinkTo(ModuleMDValueListSize);
3129 std::vector<BasicBlock*>().swap(FunctionBBs);
3130 return std::error_code();
3133 /// Find the function body in the bitcode stream
3134 std::error_code BitcodeReader::FindFunctionInStream(
3136 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3137 while (DeferredFunctionInfoIterator->second == 0) {
3138 if (Stream.AtEndOfStream())
3139 return Error(CouldNotFindFunctionInStream);
3140 // ParseModule will parse the next body in the stream and set its
3141 // position in the DeferredFunctionInfo map.
3142 if (std::error_code EC = ParseModule(true))
3145 return std::error_code();
3148 //===----------------------------------------------------------------------===//
3149 // GVMaterializer implementation
3150 //===----------------------------------------------------------------------===//
3152 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3154 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3155 if (const Function *F = dyn_cast<Function>(GV)) {
3156 return F->isDeclaration() &&
3157 DeferredFunctionInfo.count(const_cast<Function*>(F));
3162 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
3163 Function *F = dyn_cast<Function>(GV);
3164 // If it's not a function or is already material, ignore the request.
3165 if (!F || !F->isMaterializable())
3166 return std::error_code();
3168 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3169 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3170 // If its position is recorded as 0, its body is somewhere in the stream
3171 // but we haven't seen it yet.
3172 if (DFII->second == 0 && LazyStreamer)
3173 if (std::error_code EC = FindFunctionInStream(F, DFII))
3176 // Move the bit stream to the saved position of the deferred function body.
3177 Stream.JumpToBit(DFII->second);
3179 if (std::error_code EC = ParseFunctionBody(F))
3182 // Upgrade any old intrinsic calls in the function.
3183 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3184 E = UpgradedIntrinsics.end(); I != E; ++I) {
3185 if (I->first != I->second) {
3186 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3188 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3189 UpgradeIntrinsicCall(CI, I->second);
3194 return std::error_code();
3197 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3198 const Function *F = dyn_cast<Function>(GV);
3199 if (!F || F->isDeclaration())
3201 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3204 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3205 Function *F = dyn_cast<Function>(GV);
3206 // If this function isn't dematerializable, this is a noop.
3207 if (!F || !isDematerializable(F))
3210 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3212 // Just forget the function body, we can remat it later.
3216 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3217 assert(M == TheModule &&
3218 "Can only Materialize the Module this BitcodeReader is attached to.");
3219 // Iterate over the module, deserializing any functions that are still on
3221 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3223 if (F->isMaterializable()) {
3224 if (std::error_code EC = Materialize(F))
3228 // At this point, if there are any function bodies, the current bit is
3229 // pointing to the END_BLOCK record after them. Now make sure the rest
3230 // of the bits in the module have been read.
3234 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3235 // delete the old functions to clean up. We can't do this unless the entire
3236 // module is materialized because there could always be another function body
3237 // with calls to the old function.
3238 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3239 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3240 if (I->first != I->second) {
3241 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3243 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3244 UpgradeIntrinsicCall(CI, I->second);
3246 if (!I->first->use_empty())
3247 I->first->replaceAllUsesWith(I->second);
3248 I->first->eraseFromParent();
3251 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3253 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3254 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3256 UpgradeDebugInfo(*M);
3257 return std::error_code();
3260 std::error_code BitcodeReader::InitStream() {
3262 return InitLazyStream();
3263 return InitStreamFromBuffer();
3266 std::error_code BitcodeReader::InitStreamFromBuffer() {
3267 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3268 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3270 if (Buffer->getBufferSize() & 3) {
3271 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3272 return Error(InvalidBitcodeSignature);
3274 return Error(BitcodeStreamInvalidSize);
3277 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3278 // The magic number is 0x0B17C0DE stored in little endian.
3279 if (isBitcodeWrapper(BufPtr, BufEnd))
3280 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3281 return Error(InvalidBitcodeWrapperHeader);
3283 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3284 Stream.init(*StreamFile);
3286 return std::error_code();
3289 std::error_code BitcodeReader::InitLazyStream() {
3290 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3292 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3293 StreamFile.reset(new BitstreamReader(Bytes));
3294 Stream.init(*StreamFile);
3296 unsigned char buf[16];
3297 if (Bytes->readBytes(0, 16, buf) == -1)
3298 return Error(BitcodeStreamInvalidSize);
3300 if (!isBitcode(buf, buf + 16))
3301 return Error(InvalidBitcodeSignature);
3303 if (isBitcodeWrapper(buf, buf + 4)) {
3304 const unsigned char *bitcodeStart = buf;
3305 const unsigned char *bitcodeEnd = buf + 16;
3306 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3307 Bytes->dropLeadingBytes(bitcodeStart - buf);
3308 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3310 return std::error_code();
3314 class BitcodeErrorCategoryType : public std::error_category {
3315 const char *name() const LLVM_NOEXCEPT override {
3316 return "llvm.bitcode";
3318 std::string message(int IE) const override {
3319 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3321 case BitcodeReader::BitcodeStreamInvalidSize:
3322 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3323 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3324 return "Conflicting METADATA_KIND records";
3325 case BitcodeReader::CouldNotFindFunctionInStream:
3326 return "Could not find function in stream";
3327 case BitcodeReader::ExpectedConstant:
3328 return "Expected a constant";
3329 case BitcodeReader::InsufficientFunctionProtos:
3330 return "Insufficient function protos";
3331 case BitcodeReader::InvalidBitcodeSignature:
3332 return "Invalid bitcode signature";
3333 case BitcodeReader::InvalidBitcodeWrapperHeader:
3334 return "Invalid bitcode wrapper header";
3335 case BitcodeReader::InvalidConstantReference:
3336 return "Invalid ronstant reference";
3337 case BitcodeReader::InvalidID:
3338 return "Invalid ID";
3339 case BitcodeReader::InvalidInstructionWithNoBB:
3340 return "Invalid instruction with no BB";
3341 case BitcodeReader::InvalidRecord:
3342 return "Invalid record";
3343 case BitcodeReader::InvalidTypeForValue:
3344 return "Invalid type for value";
3345 case BitcodeReader::InvalidTYPETable:
3346 return "Invalid TYPE table";
3347 case BitcodeReader::InvalidType:
3348 return "Invalid type";
3349 case BitcodeReader::MalformedBlock:
3350 return "Malformed block";
3351 case BitcodeReader::MalformedGlobalInitializerSet:
3352 return "Malformed global initializer set";
3353 case BitcodeReader::InvalidMultipleBlocks:
3354 return "Invalid multiple blocks";
3355 case BitcodeReader::NeverResolvedValueFoundInFunction:
3356 return "Never resolved value found in function";
3357 case BitcodeReader::InvalidValue:
3358 return "Invalid value";
3360 llvm_unreachable("Unknown error type!");
3365 const std::error_category &BitcodeReader::BitcodeErrorCategory() {
3366 static BitcodeErrorCategoryType O;
3370 //===----------------------------------------------------------------------===//
3371 // External interface
3372 //===----------------------------------------------------------------------===//
3374 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3376 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3377 LLVMContext &Context) {
3378 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3379 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3380 M->setMaterializer(R);
3381 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3382 R->releaseBuffer(); // Never take ownership on error.
3383 delete M; // Also deletes R.
3387 R->materializeForwardReferencedFunctions();
3393 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3394 DataStreamer *streamer,
3395 LLVMContext &Context,
3396 std::string *ErrMsg) {
3397 Module *M = new Module(name, Context);
3398 BitcodeReader *R = new BitcodeReader(streamer, Context);
3399 M->setMaterializer(R);
3400 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3402 *ErrMsg = EC.message();
3403 delete M; // Also deletes R.
3409 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3410 LLVMContext &Context) {
3411 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3414 Module *M = ModuleOrErr.get();
3415 // Read in the entire module, and destroy the BitcodeReader.
3416 if (std::error_code EC = M->materializeAllPermanently(true)) {
3421 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3422 // written. We must defer until the Module has been fully materialized.
3427 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3428 LLVMContext& Context,
3429 std::string *ErrMsg) {
3430 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3432 std::string Triple("");
3433 if (std::error_code EC = R->ParseTriple(Triple))
3435 *ErrMsg = EC.message();