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"
29 using std::error_code;
32 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
35 void BitcodeReader::materializeForwardReferencedFunctions() {
36 while (!BlockAddrFwdRefs.empty()) {
37 Function *F = BlockAddrFwdRefs.begin()->first;
42 void BitcodeReader::FreeState() {
46 std::vector<Type*>().swap(TypeList);
50 std::vector<AttributeSet>().swap(MAttributes);
51 std::vector<BasicBlock*>().swap(FunctionBBs);
52 std::vector<Function*>().swap(FunctionsWithBodies);
53 DeferredFunctionInfo.clear();
56 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
59 //===----------------------------------------------------------------------===//
60 // Helper functions to implement forward reference resolution, etc.
61 //===----------------------------------------------------------------------===//
63 /// ConvertToString - Convert a string from a record into an std::string, return
65 template<typename StrTy>
66 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
68 if (Idx > Record.size())
71 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
72 Result += (char)Record[i];
76 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
78 default: // Map unknown/new linkages to external
79 case 0: return GlobalValue::ExternalLinkage;
80 case 1: return GlobalValue::WeakAnyLinkage;
81 case 2: return GlobalValue::AppendingLinkage;
82 case 3: return GlobalValue::InternalLinkage;
83 case 4: return GlobalValue::LinkOnceAnyLinkage;
84 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
85 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
86 case 7: return GlobalValue::ExternalWeakLinkage;
87 case 8: return GlobalValue::CommonLinkage;
88 case 9: return GlobalValue::PrivateLinkage;
89 case 10: return GlobalValue::WeakODRLinkage;
90 case 11: return GlobalValue::LinkOnceODRLinkage;
91 case 12: return GlobalValue::AvailableExternallyLinkage;
93 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
95 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
99 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
101 default: // Map unknown visibilities to default.
102 case 0: return GlobalValue::DefaultVisibility;
103 case 1: return GlobalValue::HiddenVisibility;
104 case 2: return GlobalValue::ProtectedVisibility;
108 static GlobalValue::DLLStorageClassTypes
109 GetDecodedDLLStorageClass(unsigned Val) {
111 default: // Map unknown values to default.
112 case 0: return GlobalValue::DefaultStorageClass;
113 case 1: return GlobalValue::DLLImportStorageClass;
114 case 2: return GlobalValue::DLLExportStorageClass;
118 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
120 case 0: return GlobalVariable::NotThreadLocal;
121 default: // Map unknown non-zero value to general dynamic.
122 case 1: return GlobalVariable::GeneralDynamicTLSModel;
123 case 2: return GlobalVariable::LocalDynamicTLSModel;
124 case 3: return GlobalVariable::InitialExecTLSModel;
125 case 4: return GlobalVariable::LocalExecTLSModel;
129 static int GetDecodedCastOpcode(unsigned Val) {
132 case bitc::CAST_TRUNC : return Instruction::Trunc;
133 case bitc::CAST_ZEXT : return Instruction::ZExt;
134 case bitc::CAST_SEXT : return Instruction::SExt;
135 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
136 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
137 case bitc::CAST_UITOFP : return Instruction::UIToFP;
138 case bitc::CAST_SITOFP : return Instruction::SIToFP;
139 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
140 case bitc::CAST_FPEXT : return Instruction::FPExt;
141 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
142 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
143 case bitc::CAST_BITCAST : return Instruction::BitCast;
144 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
147 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
150 case bitc::BINOP_ADD:
151 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
152 case bitc::BINOP_SUB:
153 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
154 case bitc::BINOP_MUL:
155 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
156 case bitc::BINOP_UDIV: return Instruction::UDiv;
157 case bitc::BINOP_SDIV:
158 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
159 case bitc::BINOP_UREM: return Instruction::URem;
160 case bitc::BINOP_SREM:
161 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
162 case bitc::BINOP_SHL: return Instruction::Shl;
163 case bitc::BINOP_LSHR: return Instruction::LShr;
164 case bitc::BINOP_ASHR: return Instruction::AShr;
165 case bitc::BINOP_AND: return Instruction::And;
166 case bitc::BINOP_OR: return Instruction::Or;
167 case bitc::BINOP_XOR: return Instruction::Xor;
171 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
173 default: return AtomicRMWInst::BAD_BINOP;
174 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
175 case bitc::RMW_ADD: return AtomicRMWInst::Add;
176 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
177 case bitc::RMW_AND: return AtomicRMWInst::And;
178 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
179 case bitc::RMW_OR: return AtomicRMWInst::Or;
180 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
181 case bitc::RMW_MAX: return AtomicRMWInst::Max;
182 case bitc::RMW_MIN: return AtomicRMWInst::Min;
183 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
184 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
188 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
190 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
191 case bitc::ORDERING_UNORDERED: return Unordered;
192 case bitc::ORDERING_MONOTONIC: return Monotonic;
193 case bitc::ORDERING_ACQUIRE: return Acquire;
194 case bitc::ORDERING_RELEASE: return Release;
195 case bitc::ORDERING_ACQREL: return AcquireRelease;
196 default: // Map unknown orderings to sequentially-consistent.
197 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
201 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
203 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
204 default: // Map unknown scopes to cross-thread.
205 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
209 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
211 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
212 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
218 /// @brief A class for maintaining the slot number definition
219 /// as a placeholder for the actual definition for forward constants defs.
220 class ConstantPlaceHolder : public ConstantExpr {
221 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
223 // allocate space for exactly one operand
224 void *operator new(size_t s) {
225 return User::operator new(s, 1);
227 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
228 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
229 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
232 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
233 static bool classof(const Value *V) {
234 return isa<ConstantExpr>(V) &&
235 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
239 /// Provide fast operand accessors
240 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
244 // FIXME: can we inherit this from ConstantExpr?
246 struct OperandTraits<ConstantPlaceHolder> :
247 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
252 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
261 WeakVH &OldV = ValuePtrs[Idx];
267 // Handle constants and non-constants (e.g. instrs) differently for
269 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
270 ResolveConstants.push_back(std::make_pair(PHC, Idx));
273 // If there was a forward reference to this value, replace it.
274 Value *PrevVal = OldV;
275 OldV->replaceAllUsesWith(V);
281 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
286 if (Value *V = ValuePtrs[Idx]) {
287 assert(Ty == V->getType() && "Type mismatch in constant table!");
288 return cast<Constant>(V);
291 // Create and return a placeholder, which will later be RAUW'd.
292 Constant *C = new ConstantPlaceHolder(Ty, Context);
297 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
301 if (Value *V = ValuePtrs[Idx]) {
302 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
306 // No type specified, must be invalid reference.
307 if (!Ty) return nullptr;
309 // Create and return a placeholder, which will later be RAUW'd.
310 Value *V = new Argument(Ty);
315 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
316 /// resolves any forward references. The idea behind this is that we sometimes
317 /// get constants (such as large arrays) which reference *many* forward ref
318 /// constants. Replacing each of these causes a lot of thrashing when
319 /// building/reuniquing the constant. Instead of doing this, we look at all the
320 /// uses and rewrite all the place holders at once for any constant that uses
322 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
323 // Sort the values by-pointer so that they are efficient to look up with a
325 std::sort(ResolveConstants.begin(), ResolveConstants.end());
327 SmallVector<Constant*, 64> NewOps;
329 while (!ResolveConstants.empty()) {
330 Value *RealVal = operator[](ResolveConstants.back().second);
331 Constant *Placeholder = ResolveConstants.back().first;
332 ResolveConstants.pop_back();
334 // Loop over all users of the placeholder, updating them to reference the
335 // new value. If they reference more than one placeholder, update them all
337 while (!Placeholder->use_empty()) {
338 auto UI = Placeholder->user_begin();
341 // If the using object isn't uniqued, just update the operands. This
342 // handles instructions and initializers for global variables.
343 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
344 UI.getUse().set(RealVal);
348 // Otherwise, we have a constant that uses the placeholder. Replace that
349 // constant with a new constant that has *all* placeholder uses updated.
350 Constant *UserC = cast<Constant>(U);
351 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
354 if (!isa<ConstantPlaceHolder>(*I)) {
355 // Not a placeholder reference.
357 } else if (*I == Placeholder) {
358 // Common case is that it just references this one placeholder.
361 // Otherwise, look up the placeholder in ResolveConstants.
362 ResolveConstantsTy::iterator It =
363 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
364 std::pair<Constant*, unsigned>(cast<Constant>(*I),
366 assert(It != ResolveConstants.end() && It->first == *I);
367 NewOp = operator[](It->second);
370 NewOps.push_back(cast<Constant>(NewOp));
373 // Make the new constant.
375 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
376 NewC = ConstantArray::get(UserCA->getType(), NewOps);
377 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
378 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
379 } else if (isa<ConstantVector>(UserC)) {
380 NewC = ConstantVector::get(NewOps);
382 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
383 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
386 UserC->replaceAllUsesWith(NewC);
387 UserC->destroyConstant();
391 // Update all ValueHandles, they should be the only users at this point.
392 Placeholder->replaceAllUsesWith(RealVal);
397 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
406 WeakVH &OldV = MDValuePtrs[Idx];
412 // If there was a forward reference to this value, replace it.
413 MDNode *PrevVal = cast<MDNode>(OldV);
414 OldV->replaceAllUsesWith(V);
415 MDNode::deleteTemporary(PrevVal);
416 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
418 MDValuePtrs[Idx] = V;
421 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
425 if (Value *V = MDValuePtrs[Idx]) {
426 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
430 // Create and return a placeholder, which will later be RAUW'd.
431 Value *V = MDNode::getTemporary(Context, None);
432 MDValuePtrs[Idx] = V;
436 Type *BitcodeReader::getTypeByID(unsigned ID) {
437 // The type table size is always specified correctly.
438 if (ID >= TypeList.size())
441 if (Type *Ty = TypeList[ID])
444 // If we have a forward reference, the only possible case is when it is to a
445 // named struct. Just create a placeholder for now.
446 return TypeList[ID] = StructType::create(Context);
450 //===----------------------------------------------------------------------===//
451 // Functions for parsing blocks from the bitcode file
452 //===----------------------------------------------------------------------===//
455 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
456 /// been decoded from the given integer. This function must stay in sync with
457 /// 'encodeLLVMAttributesForBitcode'.
458 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
459 uint64_t EncodedAttrs) {
460 // FIXME: Remove in 4.0.
462 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
463 // the bits above 31 down by 11 bits.
464 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
465 assert((!Alignment || isPowerOf2_32(Alignment)) &&
466 "Alignment must be a power of two.");
469 B.addAlignmentAttr(Alignment);
470 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
471 (EncodedAttrs & 0xffff));
474 error_code BitcodeReader::ParseAttributeBlock() {
475 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
476 return Error(InvalidRecord);
478 if (!MAttributes.empty())
479 return Error(InvalidMultipleBlocks);
481 SmallVector<uint64_t, 64> Record;
483 SmallVector<AttributeSet, 8> Attrs;
485 // Read all the records.
487 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
489 switch (Entry.Kind) {
490 case BitstreamEntry::SubBlock: // Handled for us already.
491 case BitstreamEntry::Error:
492 return Error(MalformedBlock);
493 case BitstreamEntry::EndBlock:
495 case BitstreamEntry::Record:
496 // The interesting case.
502 switch (Stream.readRecord(Entry.ID, Record)) {
503 default: // Default behavior: ignore.
505 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
506 // FIXME: Remove in 4.0.
507 if (Record.size() & 1)
508 return Error(InvalidRecord);
510 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
512 decodeLLVMAttributesForBitcode(B, Record[i+1]);
513 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
516 MAttributes.push_back(AttributeSet::get(Context, Attrs));
520 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
521 for (unsigned i = 0, e = Record.size(); i != e; ++i)
522 Attrs.push_back(MAttributeGroups[Record[i]]);
524 MAttributes.push_back(AttributeSet::get(Context, Attrs));
532 // Returns Attribute::None on unrecognized codes.
533 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
536 return Attribute::None;
537 case bitc::ATTR_KIND_ALIGNMENT:
538 return Attribute::Alignment;
539 case bitc::ATTR_KIND_ALWAYS_INLINE:
540 return Attribute::AlwaysInline;
541 case bitc::ATTR_KIND_BUILTIN:
542 return Attribute::Builtin;
543 case bitc::ATTR_KIND_BY_VAL:
544 return Attribute::ByVal;
545 case bitc::ATTR_KIND_IN_ALLOCA:
546 return Attribute::InAlloca;
547 case bitc::ATTR_KIND_COLD:
548 return Attribute::Cold;
549 case bitc::ATTR_KIND_INLINE_HINT:
550 return Attribute::InlineHint;
551 case bitc::ATTR_KIND_IN_REG:
552 return Attribute::InReg;
553 case bitc::ATTR_KIND_JUMP_TABLE:
554 return Attribute::JumpTable;
555 case bitc::ATTR_KIND_MIN_SIZE:
556 return Attribute::MinSize;
557 case bitc::ATTR_KIND_NAKED:
558 return Attribute::Naked;
559 case bitc::ATTR_KIND_NEST:
560 return Attribute::Nest;
561 case bitc::ATTR_KIND_NO_ALIAS:
562 return Attribute::NoAlias;
563 case bitc::ATTR_KIND_NO_BUILTIN:
564 return Attribute::NoBuiltin;
565 case bitc::ATTR_KIND_NO_CAPTURE:
566 return Attribute::NoCapture;
567 case bitc::ATTR_KIND_NO_DUPLICATE:
568 return Attribute::NoDuplicate;
569 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
570 return Attribute::NoImplicitFloat;
571 case bitc::ATTR_KIND_NO_INLINE:
572 return Attribute::NoInline;
573 case bitc::ATTR_KIND_NON_LAZY_BIND:
574 return Attribute::NonLazyBind;
575 case bitc::ATTR_KIND_NON_NULL:
576 return Attribute::NonNull;
577 case bitc::ATTR_KIND_NO_RED_ZONE:
578 return Attribute::NoRedZone;
579 case bitc::ATTR_KIND_NO_RETURN:
580 return Attribute::NoReturn;
581 case bitc::ATTR_KIND_NO_UNWIND:
582 return Attribute::NoUnwind;
583 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
584 return Attribute::OptimizeForSize;
585 case bitc::ATTR_KIND_OPTIMIZE_NONE:
586 return Attribute::OptimizeNone;
587 case bitc::ATTR_KIND_READ_NONE:
588 return Attribute::ReadNone;
589 case bitc::ATTR_KIND_READ_ONLY:
590 return Attribute::ReadOnly;
591 case bitc::ATTR_KIND_RETURNED:
592 return Attribute::Returned;
593 case bitc::ATTR_KIND_RETURNS_TWICE:
594 return Attribute::ReturnsTwice;
595 case bitc::ATTR_KIND_S_EXT:
596 return Attribute::SExt;
597 case bitc::ATTR_KIND_STACK_ALIGNMENT:
598 return Attribute::StackAlignment;
599 case bitc::ATTR_KIND_STACK_PROTECT:
600 return Attribute::StackProtect;
601 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
602 return Attribute::StackProtectReq;
603 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
604 return Attribute::StackProtectStrong;
605 case bitc::ATTR_KIND_STRUCT_RET:
606 return Attribute::StructRet;
607 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
608 return Attribute::SanitizeAddress;
609 case bitc::ATTR_KIND_SANITIZE_THREAD:
610 return Attribute::SanitizeThread;
611 case bitc::ATTR_KIND_SANITIZE_MEMORY:
612 return Attribute::SanitizeMemory;
613 case bitc::ATTR_KIND_UW_TABLE:
614 return Attribute::UWTable;
615 case bitc::ATTR_KIND_Z_EXT:
616 return Attribute::ZExt;
620 error_code BitcodeReader::ParseAttrKind(uint64_t Code,
621 Attribute::AttrKind *Kind) {
622 *Kind = GetAttrFromCode(Code);
623 if (*Kind == Attribute::None)
624 return Error(InvalidValue);
628 error_code BitcodeReader::ParseAttributeGroupBlock() {
629 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
630 return Error(InvalidRecord);
632 if (!MAttributeGroups.empty())
633 return Error(InvalidMultipleBlocks);
635 SmallVector<uint64_t, 64> Record;
637 // Read all the records.
639 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
641 switch (Entry.Kind) {
642 case BitstreamEntry::SubBlock: // Handled for us already.
643 case BitstreamEntry::Error:
644 return Error(MalformedBlock);
645 case BitstreamEntry::EndBlock:
647 case BitstreamEntry::Record:
648 // The interesting case.
654 switch (Stream.readRecord(Entry.ID, Record)) {
655 default: // Default behavior: ignore.
657 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
658 if (Record.size() < 3)
659 return Error(InvalidRecord);
661 uint64_t GrpID = Record[0];
662 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
665 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
666 if (Record[i] == 0) { // Enum attribute
667 Attribute::AttrKind Kind;
668 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
671 B.addAttribute(Kind);
672 } else if (Record[i] == 1) { // Align attribute
673 Attribute::AttrKind Kind;
674 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
676 if (Kind == Attribute::Alignment)
677 B.addAlignmentAttr(Record[++i]);
679 B.addStackAlignmentAttr(Record[++i]);
680 } else { // String attribute
681 assert((Record[i] == 3 || Record[i] == 4) &&
682 "Invalid attribute group entry");
683 bool HasValue = (Record[i++] == 4);
684 SmallString<64> KindStr;
685 SmallString<64> ValStr;
687 while (Record[i] != 0 && i != e)
688 KindStr += Record[i++];
689 assert(Record[i] == 0 && "Kind string not null terminated");
692 // Has a value associated with it.
693 ++i; // Skip the '0' that terminates the "kind" string.
694 while (Record[i] != 0 && i != e)
695 ValStr += Record[i++];
696 assert(Record[i] == 0 && "Value string not null terminated");
699 B.addAttribute(KindStr.str(), ValStr.str());
703 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
710 error_code BitcodeReader::ParseTypeTable() {
711 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
712 return Error(InvalidRecord);
714 return ParseTypeTableBody();
717 error_code BitcodeReader::ParseTypeTableBody() {
718 if (!TypeList.empty())
719 return Error(InvalidMultipleBlocks);
721 SmallVector<uint64_t, 64> Record;
722 unsigned NumRecords = 0;
724 SmallString<64> TypeName;
726 // Read all the records for this type table.
728 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
730 switch (Entry.Kind) {
731 case BitstreamEntry::SubBlock: // Handled for us already.
732 case BitstreamEntry::Error:
733 return Error(MalformedBlock);
734 case BitstreamEntry::EndBlock:
735 if (NumRecords != TypeList.size())
736 return Error(MalformedBlock);
738 case BitstreamEntry::Record:
739 // The interesting case.
745 Type *ResultTy = nullptr;
746 switch (Stream.readRecord(Entry.ID, Record)) {
748 return Error(InvalidValue);
749 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
750 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
751 // type list. This allows us to reserve space.
752 if (Record.size() < 1)
753 return Error(InvalidRecord);
754 TypeList.resize(Record[0]);
756 case bitc::TYPE_CODE_VOID: // VOID
757 ResultTy = Type::getVoidTy(Context);
759 case bitc::TYPE_CODE_HALF: // HALF
760 ResultTy = Type::getHalfTy(Context);
762 case bitc::TYPE_CODE_FLOAT: // FLOAT
763 ResultTy = Type::getFloatTy(Context);
765 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
766 ResultTy = Type::getDoubleTy(Context);
768 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
769 ResultTy = Type::getX86_FP80Ty(Context);
771 case bitc::TYPE_CODE_FP128: // FP128
772 ResultTy = Type::getFP128Ty(Context);
774 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
775 ResultTy = Type::getPPC_FP128Ty(Context);
777 case bitc::TYPE_CODE_LABEL: // LABEL
778 ResultTy = Type::getLabelTy(Context);
780 case bitc::TYPE_CODE_METADATA: // METADATA
781 ResultTy = Type::getMetadataTy(Context);
783 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
784 ResultTy = Type::getX86_MMXTy(Context);
786 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
787 if (Record.size() < 1)
788 return Error(InvalidRecord);
790 ResultTy = IntegerType::get(Context, Record[0]);
792 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
793 // [pointee type, address space]
794 if (Record.size() < 1)
795 return Error(InvalidRecord);
796 unsigned AddressSpace = 0;
797 if (Record.size() == 2)
798 AddressSpace = Record[1];
799 ResultTy = getTypeByID(Record[0]);
801 return Error(InvalidType);
802 ResultTy = PointerType::get(ResultTy, AddressSpace);
805 case bitc::TYPE_CODE_FUNCTION_OLD: {
806 // FIXME: attrid is dead, remove it in LLVM 4.0
807 // FUNCTION: [vararg, attrid, retty, paramty x N]
808 if (Record.size() < 3)
809 return Error(InvalidRecord);
810 SmallVector<Type*, 8> ArgTys;
811 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
812 if (Type *T = getTypeByID(Record[i]))
818 ResultTy = getTypeByID(Record[2]);
819 if (!ResultTy || ArgTys.size() < Record.size()-3)
820 return Error(InvalidType);
822 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
825 case bitc::TYPE_CODE_FUNCTION: {
826 // FUNCTION: [vararg, retty, paramty x N]
827 if (Record.size() < 2)
828 return Error(InvalidRecord);
829 SmallVector<Type*, 8> ArgTys;
830 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
831 if (Type *T = getTypeByID(Record[i]))
837 ResultTy = getTypeByID(Record[1]);
838 if (!ResultTy || ArgTys.size() < Record.size()-2)
839 return Error(InvalidType);
841 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
844 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
845 if (Record.size() < 1)
846 return Error(InvalidRecord);
847 SmallVector<Type*, 8> EltTys;
848 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
849 if (Type *T = getTypeByID(Record[i]))
854 if (EltTys.size() != Record.size()-1)
855 return Error(InvalidType);
856 ResultTy = StructType::get(Context, EltTys, Record[0]);
859 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
860 if (ConvertToString(Record, 0, TypeName))
861 return Error(InvalidRecord);
864 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
865 if (Record.size() < 1)
866 return Error(InvalidRecord);
868 if (NumRecords >= TypeList.size())
869 return Error(InvalidTYPETable);
871 // Check to see if this was forward referenced, if so fill in the temp.
872 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
874 Res->setName(TypeName);
875 TypeList[NumRecords] = nullptr;
876 } else // Otherwise, create a new struct.
877 Res = StructType::create(Context, TypeName);
880 SmallVector<Type*, 8> EltTys;
881 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
882 if (Type *T = getTypeByID(Record[i]))
887 if (EltTys.size() != Record.size()-1)
888 return Error(InvalidRecord);
889 Res->setBody(EltTys, Record[0]);
893 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
894 if (Record.size() != 1)
895 return Error(InvalidRecord);
897 if (NumRecords >= TypeList.size())
898 return Error(InvalidTYPETable);
900 // Check to see if this was forward referenced, if so fill in the temp.
901 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
903 Res->setName(TypeName);
904 TypeList[NumRecords] = nullptr;
905 } else // Otherwise, create a new struct with no body.
906 Res = StructType::create(Context, TypeName);
911 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
912 if (Record.size() < 2)
913 return Error(InvalidRecord);
914 if ((ResultTy = getTypeByID(Record[1])))
915 ResultTy = ArrayType::get(ResultTy, Record[0]);
917 return Error(InvalidType);
919 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
920 if (Record.size() < 2)
921 return Error(InvalidRecord);
922 if ((ResultTy = getTypeByID(Record[1])))
923 ResultTy = VectorType::get(ResultTy, Record[0]);
925 return Error(InvalidType);
929 if (NumRecords >= TypeList.size())
930 return Error(InvalidTYPETable);
931 assert(ResultTy && "Didn't read a type?");
932 assert(!TypeList[NumRecords] && "Already read type?");
933 TypeList[NumRecords++] = ResultTy;
937 error_code BitcodeReader::ParseValueSymbolTable() {
938 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
939 return Error(InvalidRecord);
941 SmallVector<uint64_t, 64> Record;
943 // Read all the records for this value table.
944 SmallString<128> ValueName;
946 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
948 switch (Entry.Kind) {
949 case BitstreamEntry::SubBlock: // Handled for us already.
950 case BitstreamEntry::Error:
951 return Error(MalformedBlock);
952 case BitstreamEntry::EndBlock:
954 case BitstreamEntry::Record:
955 // The interesting case.
961 switch (Stream.readRecord(Entry.ID, Record)) {
962 default: // Default behavior: unknown type.
964 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
965 if (ConvertToString(Record, 1, ValueName))
966 return Error(InvalidRecord);
967 unsigned ValueID = Record[0];
968 if (ValueID >= ValueList.size() || !ValueList[ValueID])
969 return Error(InvalidRecord);
970 Value *V = ValueList[ValueID];
972 V->setName(StringRef(ValueName.data(), ValueName.size()));
976 case bitc::VST_CODE_BBENTRY: {
977 if (ConvertToString(Record, 1, ValueName))
978 return Error(InvalidRecord);
979 BasicBlock *BB = getBasicBlock(Record[0]);
981 return Error(InvalidRecord);
983 BB->setName(StringRef(ValueName.data(), ValueName.size()));
991 error_code BitcodeReader::ParseMetadata() {
992 unsigned NextMDValueNo = MDValueList.size();
994 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
995 return Error(InvalidRecord);
997 SmallVector<uint64_t, 64> Record;
999 // Read all the records.
1001 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1003 switch (Entry.Kind) {
1004 case BitstreamEntry::SubBlock: // Handled for us already.
1005 case BitstreamEntry::Error:
1006 return Error(MalformedBlock);
1007 case BitstreamEntry::EndBlock:
1008 return error_code();
1009 case BitstreamEntry::Record:
1010 // The interesting case.
1014 bool IsFunctionLocal = false;
1017 unsigned Code = Stream.readRecord(Entry.ID, Record);
1019 default: // Default behavior: ignore.
1021 case bitc::METADATA_NAME: {
1022 // Read name of the named metadata.
1023 SmallString<8> Name(Record.begin(), Record.end());
1025 Code = Stream.ReadCode();
1027 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1028 unsigned NextBitCode = Stream.readRecord(Code, Record);
1029 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1031 // Read named metadata elements.
1032 unsigned Size = Record.size();
1033 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1034 for (unsigned i = 0; i != Size; ++i) {
1035 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1037 return Error(InvalidRecord);
1038 NMD->addOperand(MD);
1042 case bitc::METADATA_FN_NODE:
1043 IsFunctionLocal = true;
1045 case bitc::METADATA_NODE: {
1046 if (Record.size() % 2 == 1)
1047 return Error(InvalidRecord);
1049 unsigned Size = Record.size();
1050 SmallVector<Value*, 8> Elts;
1051 for (unsigned i = 0; i != Size; i += 2) {
1052 Type *Ty = getTypeByID(Record[i]);
1054 return Error(InvalidRecord);
1055 if (Ty->isMetadataTy())
1056 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1057 else if (!Ty->isVoidTy())
1058 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1060 Elts.push_back(nullptr);
1062 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1063 IsFunctionLocal = false;
1064 MDValueList.AssignValue(V, NextMDValueNo++);
1067 case bitc::METADATA_STRING: {
1068 SmallString<8> String(Record.begin(), Record.end());
1069 Value *V = MDString::get(Context, String);
1070 MDValueList.AssignValue(V, NextMDValueNo++);
1073 case bitc::METADATA_KIND: {
1074 if (Record.size() < 2)
1075 return Error(InvalidRecord);
1077 unsigned Kind = Record[0];
1078 SmallString<8> Name(Record.begin()+1, Record.end());
1080 unsigned NewKind = TheModule->getMDKindID(Name.str());
1081 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1082 return Error(ConflictingMETADATA_KINDRecords);
1089 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1090 /// the LSB for dense VBR encoding.
1091 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1096 // There is no such thing as -0 with integers. "-0" really means MININT.
1100 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1101 /// values and aliases that we can.
1102 error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1103 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1104 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1105 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1107 GlobalInitWorklist.swap(GlobalInits);
1108 AliasInitWorklist.swap(AliasInits);
1109 FunctionPrefixWorklist.swap(FunctionPrefixes);
1111 while (!GlobalInitWorklist.empty()) {
1112 unsigned ValID = GlobalInitWorklist.back().second;
1113 if (ValID >= ValueList.size()) {
1114 // Not ready to resolve this yet, it requires something later in the file.
1115 GlobalInits.push_back(GlobalInitWorklist.back());
1117 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1118 GlobalInitWorklist.back().first->setInitializer(C);
1120 return Error(ExpectedConstant);
1122 GlobalInitWorklist.pop_back();
1125 while (!AliasInitWorklist.empty()) {
1126 unsigned ValID = AliasInitWorklist.back().second;
1127 if (ValID >= ValueList.size()) {
1128 AliasInits.push_back(AliasInitWorklist.back());
1130 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1131 AliasInitWorklist.back().first->setAliasee(C);
1133 return Error(ExpectedConstant);
1135 AliasInitWorklist.pop_back();
1138 while (!FunctionPrefixWorklist.empty()) {
1139 unsigned ValID = FunctionPrefixWorklist.back().second;
1140 if (ValID >= ValueList.size()) {
1141 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1143 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1144 FunctionPrefixWorklist.back().first->setPrefixData(C);
1146 return Error(ExpectedConstant);
1148 FunctionPrefixWorklist.pop_back();
1151 return error_code();
1154 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1155 SmallVector<uint64_t, 8> Words(Vals.size());
1156 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1157 BitcodeReader::decodeSignRotatedValue);
1159 return APInt(TypeBits, Words);
1162 error_code BitcodeReader::ParseConstants() {
1163 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1164 return Error(InvalidRecord);
1166 SmallVector<uint64_t, 64> Record;
1168 // Read all the records for this value table.
1169 Type *CurTy = Type::getInt32Ty(Context);
1170 unsigned NextCstNo = ValueList.size();
1172 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1174 switch (Entry.Kind) {
1175 case BitstreamEntry::SubBlock: // Handled for us already.
1176 case BitstreamEntry::Error:
1177 return Error(MalformedBlock);
1178 case BitstreamEntry::EndBlock:
1179 if (NextCstNo != ValueList.size())
1180 return Error(InvalidConstantReference);
1182 // Once all the constants have been read, go through and resolve forward
1184 ValueList.ResolveConstantForwardRefs();
1185 return error_code();
1186 case BitstreamEntry::Record:
1187 // The interesting case.
1194 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1196 default: // Default behavior: unknown constant
1197 case bitc::CST_CODE_UNDEF: // UNDEF
1198 V = UndefValue::get(CurTy);
1200 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1202 return Error(InvalidRecord);
1203 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1204 return Error(InvalidRecord);
1205 CurTy = TypeList[Record[0]];
1206 continue; // Skip the ValueList manipulation.
1207 case bitc::CST_CODE_NULL: // NULL
1208 V = Constant::getNullValue(CurTy);
1210 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1211 if (!CurTy->isIntegerTy() || Record.empty())
1212 return Error(InvalidRecord);
1213 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1215 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1216 if (!CurTy->isIntegerTy() || Record.empty())
1217 return Error(InvalidRecord);
1219 APInt VInt = ReadWideAPInt(Record,
1220 cast<IntegerType>(CurTy)->getBitWidth());
1221 V = ConstantInt::get(Context, VInt);
1225 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1227 return Error(InvalidRecord);
1228 if (CurTy->isHalfTy())
1229 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1230 APInt(16, (uint16_t)Record[0])));
1231 else if (CurTy->isFloatTy())
1232 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1233 APInt(32, (uint32_t)Record[0])));
1234 else if (CurTy->isDoubleTy())
1235 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1236 APInt(64, Record[0])));
1237 else if (CurTy->isX86_FP80Ty()) {
1238 // Bits are not stored the same way as a normal i80 APInt, compensate.
1239 uint64_t Rearrange[2];
1240 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1241 Rearrange[1] = Record[0] >> 48;
1242 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1243 APInt(80, Rearrange)));
1244 } else if (CurTy->isFP128Ty())
1245 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1246 APInt(128, Record)));
1247 else if (CurTy->isPPC_FP128Ty())
1248 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1249 APInt(128, Record)));
1251 V = UndefValue::get(CurTy);
1255 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1257 return Error(InvalidRecord);
1259 unsigned Size = Record.size();
1260 SmallVector<Constant*, 16> Elts;
1262 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1263 for (unsigned i = 0; i != Size; ++i)
1264 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1265 STy->getElementType(i)));
1266 V = ConstantStruct::get(STy, Elts);
1267 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1268 Type *EltTy = ATy->getElementType();
1269 for (unsigned i = 0; i != Size; ++i)
1270 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1271 V = ConstantArray::get(ATy, Elts);
1272 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1273 Type *EltTy = VTy->getElementType();
1274 for (unsigned i = 0; i != Size; ++i)
1275 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1276 V = ConstantVector::get(Elts);
1278 V = UndefValue::get(CurTy);
1282 case bitc::CST_CODE_STRING: // STRING: [values]
1283 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1285 return Error(InvalidRecord);
1287 SmallString<16> Elts(Record.begin(), Record.end());
1288 V = ConstantDataArray::getString(Context, Elts,
1289 BitCode == bitc::CST_CODE_CSTRING);
1292 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1294 return Error(InvalidRecord);
1296 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1297 unsigned Size = Record.size();
1299 if (EltTy->isIntegerTy(8)) {
1300 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1301 if (isa<VectorType>(CurTy))
1302 V = ConstantDataVector::get(Context, Elts);
1304 V = ConstantDataArray::get(Context, Elts);
1305 } else if (EltTy->isIntegerTy(16)) {
1306 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1307 if (isa<VectorType>(CurTy))
1308 V = ConstantDataVector::get(Context, Elts);
1310 V = ConstantDataArray::get(Context, Elts);
1311 } else if (EltTy->isIntegerTy(32)) {
1312 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1313 if (isa<VectorType>(CurTy))
1314 V = ConstantDataVector::get(Context, Elts);
1316 V = ConstantDataArray::get(Context, Elts);
1317 } else if (EltTy->isIntegerTy(64)) {
1318 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1319 if (isa<VectorType>(CurTy))
1320 V = ConstantDataVector::get(Context, Elts);
1322 V = ConstantDataArray::get(Context, Elts);
1323 } else if (EltTy->isFloatTy()) {
1324 SmallVector<float, 16> Elts(Size);
1325 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1326 if (isa<VectorType>(CurTy))
1327 V = ConstantDataVector::get(Context, Elts);
1329 V = ConstantDataArray::get(Context, Elts);
1330 } else if (EltTy->isDoubleTy()) {
1331 SmallVector<double, 16> Elts(Size);
1332 std::transform(Record.begin(), Record.end(), Elts.begin(),
1334 if (isa<VectorType>(CurTy))
1335 V = ConstantDataVector::get(Context, Elts);
1337 V = ConstantDataArray::get(Context, Elts);
1339 return Error(InvalidTypeForValue);
1344 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1345 if (Record.size() < 3)
1346 return Error(InvalidRecord);
1347 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1349 V = UndefValue::get(CurTy); // Unknown binop.
1351 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1352 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1354 if (Record.size() >= 4) {
1355 if (Opc == Instruction::Add ||
1356 Opc == Instruction::Sub ||
1357 Opc == Instruction::Mul ||
1358 Opc == Instruction::Shl) {
1359 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1360 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1361 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1362 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1363 } else if (Opc == Instruction::SDiv ||
1364 Opc == Instruction::UDiv ||
1365 Opc == Instruction::LShr ||
1366 Opc == Instruction::AShr) {
1367 if (Record[3] & (1 << bitc::PEO_EXACT))
1368 Flags |= SDivOperator::IsExact;
1371 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1375 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1376 if (Record.size() < 3)
1377 return Error(InvalidRecord);
1378 int Opc = GetDecodedCastOpcode(Record[0]);
1380 V = UndefValue::get(CurTy); // Unknown cast.
1382 Type *OpTy = getTypeByID(Record[1]);
1384 return Error(InvalidRecord);
1385 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1386 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1387 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1391 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1392 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1393 if (Record.size() & 1)
1394 return Error(InvalidRecord);
1395 SmallVector<Constant*, 16> Elts;
1396 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1397 Type *ElTy = getTypeByID(Record[i]);
1399 return Error(InvalidRecord);
1400 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1402 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1403 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1405 bitc::CST_CODE_CE_INBOUNDS_GEP);
1408 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1409 if (Record.size() < 3)
1410 return Error(InvalidRecord);
1412 Type *SelectorTy = Type::getInt1Ty(Context);
1414 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1415 // vector. Otherwise, it must be a single bit.
1416 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1417 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1418 VTy->getNumElements());
1420 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1422 ValueList.getConstantFwdRef(Record[1],CurTy),
1423 ValueList.getConstantFwdRef(Record[2],CurTy));
1426 case bitc::CST_CODE_CE_EXTRACTELT
1427 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1428 if (Record.size() < 3)
1429 return Error(InvalidRecord);
1431 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1433 return Error(InvalidRecord);
1434 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1435 Constant *Op1 = nullptr;
1436 if (Record.size() == 4) {
1437 Type *IdxTy = getTypeByID(Record[2]);
1439 return Error(InvalidRecord);
1440 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1441 } else // TODO: Remove with llvm 4.0
1442 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1444 return Error(InvalidRecord);
1445 V = ConstantExpr::getExtractElement(Op0, Op1);
1448 case bitc::CST_CODE_CE_INSERTELT
1449 : { // CE_INSERTELT: [opval, opval, opty, opval]
1450 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1451 if (Record.size() < 3 || !OpTy)
1452 return Error(InvalidRecord);
1453 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1454 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1455 OpTy->getElementType());
1456 Constant *Op2 = nullptr;
1457 if (Record.size() == 4) {
1458 Type *IdxTy = getTypeByID(Record[2]);
1460 return Error(InvalidRecord);
1461 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1462 } else // TODO: Remove with llvm 4.0
1463 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1465 return Error(InvalidRecord);
1466 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1469 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1470 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1471 if (Record.size() < 3 || !OpTy)
1472 return Error(InvalidRecord);
1473 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1474 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1475 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1476 OpTy->getNumElements());
1477 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1478 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1481 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1482 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1484 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1485 if (Record.size() < 4 || !RTy || !OpTy)
1486 return Error(InvalidRecord);
1487 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1488 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1489 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1490 RTy->getNumElements());
1491 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1492 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1495 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1496 if (Record.size() < 4)
1497 return Error(InvalidRecord);
1498 Type *OpTy = getTypeByID(Record[0]);
1500 return Error(InvalidRecord);
1501 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1502 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1504 if (OpTy->isFPOrFPVectorTy())
1505 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1507 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1510 // This maintains backward compatibility, pre-asm dialect keywords.
1511 // FIXME: Remove with the 4.0 release.
1512 case bitc::CST_CODE_INLINEASM_OLD: {
1513 if (Record.size() < 2)
1514 return Error(InvalidRecord);
1515 std::string AsmStr, ConstrStr;
1516 bool HasSideEffects = Record[0] & 1;
1517 bool IsAlignStack = Record[0] >> 1;
1518 unsigned AsmStrSize = Record[1];
1519 if (2+AsmStrSize >= Record.size())
1520 return Error(InvalidRecord);
1521 unsigned ConstStrSize = Record[2+AsmStrSize];
1522 if (3+AsmStrSize+ConstStrSize > Record.size())
1523 return Error(InvalidRecord);
1525 for (unsigned i = 0; i != AsmStrSize; ++i)
1526 AsmStr += (char)Record[2+i];
1527 for (unsigned i = 0; i != ConstStrSize; ++i)
1528 ConstrStr += (char)Record[3+AsmStrSize+i];
1529 PointerType *PTy = cast<PointerType>(CurTy);
1530 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1531 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1534 // This version adds support for the asm dialect keywords (e.g.,
1536 case bitc::CST_CODE_INLINEASM: {
1537 if (Record.size() < 2)
1538 return Error(InvalidRecord);
1539 std::string AsmStr, ConstrStr;
1540 bool HasSideEffects = Record[0] & 1;
1541 bool IsAlignStack = (Record[0] >> 1) & 1;
1542 unsigned AsmDialect = Record[0] >> 2;
1543 unsigned AsmStrSize = Record[1];
1544 if (2+AsmStrSize >= Record.size())
1545 return Error(InvalidRecord);
1546 unsigned ConstStrSize = Record[2+AsmStrSize];
1547 if (3+AsmStrSize+ConstStrSize > Record.size())
1548 return Error(InvalidRecord);
1550 for (unsigned i = 0; i != AsmStrSize; ++i)
1551 AsmStr += (char)Record[2+i];
1552 for (unsigned i = 0; i != ConstStrSize; ++i)
1553 ConstrStr += (char)Record[3+AsmStrSize+i];
1554 PointerType *PTy = cast<PointerType>(CurTy);
1555 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1556 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1557 InlineAsm::AsmDialect(AsmDialect));
1560 case bitc::CST_CODE_BLOCKADDRESS:{
1561 if (Record.size() < 3)
1562 return Error(InvalidRecord);
1563 Type *FnTy = getTypeByID(Record[0]);
1565 return Error(InvalidRecord);
1567 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1569 return Error(InvalidRecord);
1571 // If the function is already parsed we can insert the block address right
1574 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1575 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1577 return Error(InvalidID);
1580 V = BlockAddress::get(Fn, BBI);
1582 // Otherwise insert a placeholder and remember it so it can be inserted
1583 // when the function is parsed.
1584 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1585 Type::getInt8Ty(Context),
1586 false, GlobalValue::InternalLinkage,
1588 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1595 ValueList.AssignValue(V, NextCstNo);
1600 error_code BitcodeReader::ParseUseLists() {
1601 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1602 return Error(InvalidRecord);
1604 SmallVector<uint64_t, 64> Record;
1606 // Read all the records.
1608 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1610 switch (Entry.Kind) {
1611 case BitstreamEntry::SubBlock: // Handled for us already.
1612 case BitstreamEntry::Error:
1613 return Error(MalformedBlock);
1614 case BitstreamEntry::EndBlock:
1615 return error_code();
1616 case BitstreamEntry::Record:
1617 // The interesting case.
1621 // Read a use list record.
1623 switch (Stream.readRecord(Entry.ID, Record)) {
1624 default: // Default behavior: unknown type.
1626 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1627 unsigned RecordLength = Record.size();
1628 if (RecordLength < 1)
1629 return Error(InvalidRecord);
1630 UseListRecords.push_back(Record);
1637 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1638 /// remember where it is and then skip it. This lets us lazily deserialize the
1640 error_code BitcodeReader::RememberAndSkipFunctionBody() {
1641 // Get the function we are talking about.
1642 if (FunctionsWithBodies.empty())
1643 return Error(InsufficientFunctionProtos);
1645 Function *Fn = FunctionsWithBodies.back();
1646 FunctionsWithBodies.pop_back();
1648 // Save the current stream state.
1649 uint64_t CurBit = Stream.GetCurrentBitNo();
1650 DeferredFunctionInfo[Fn] = CurBit;
1652 // Skip over the function block for now.
1653 if (Stream.SkipBlock())
1654 return Error(InvalidRecord);
1655 return error_code();
1658 error_code BitcodeReader::GlobalCleanup() {
1659 // Patch the initializers for globals and aliases up.
1660 ResolveGlobalAndAliasInits();
1661 if (!GlobalInits.empty() || !AliasInits.empty())
1662 return Error(MalformedGlobalInitializerSet);
1664 // Look for intrinsic functions which need to be upgraded at some point
1665 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1668 if (UpgradeIntrinsicFunction(FI, NewFn))
1669 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1672 // Look for global variables which need to be renamed.
1673 for (Module::global_iterator
1674 GI = TheModule->global_begin(), GE = TheModule->global_end();
1676 GlobalVariable *GV = GI++;
1677 UpgradeGlobalVariable(GV);
1680 // Force deallocation of memory for these vectors to favor the client that
1681 // want lazy deserialization.
1682 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1683 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1684 return error_code();
1687 error_code BitcodeReader::ParseModule(bool Resume) {
1689 Stream.JumpToBit(NextUnreadBit);
1690 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1691 return Error(InvalidRecord);
1693 SmallVector<uint64_t, 64> Record;
1694 std::vector<std::string> SectionTable;
1695 std::vector<std::string> GCTable;
1697 // Read all the records for this module.
1699 BitstreamEntry Entry = Stream.advance();
1701 switch (Entry.Kind) {
1702 case BitstreamEntry::Error:
1703 return Error(MalformedBlock);
1704 case BitstreamEntry::EndBlock:
1705 return GlobalCleanup();
1707 case BitstreamEntry::SubBlock:
1709 default: // Skip unknown content.
1710 if (Stream.SkipBlock())
1711 return Error(InvalidRecord);
1713 case bitc::BLOCKINFO_BLOCK_ID:
1714 if (Stream.ReadBlockInfoBlock())
1715 return Error(MalformedBlock);
1717 case bitc::PARAMATTR_BLOCK_ID:
1718 if (error_code EC = ParseAttributeBlock())
1721 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1722 if (error_code EC = ParseAttributeGroupBlock())
1725 case bitc::TYPE_BLOCK_ID_NEW:
1726 if (error_code EC = ParseTypeTable())
1729 case bitc::VALUE_SYMTAB_BLOCK_ID:
1730 if (error_code EC = ParseValueSymbolTable())
1732 SeenValueSymbolTable = true;
1734 case bitc::CONSTANTS_BLOCK_ID:
1735 if (error_code EC = ParseConstants())
1737 if (error_code EC = ResolveGlobalAndAliasInits())
1740 case bitc::METADATA_BLOCK_ID:
1741 if (error_code EC = ParseMetadata())
1744 case bitc::FUNCTION_BLOCK_ID:
1745 // If this is the first function body we've seen, reverse the
1746 // FunctionsWithBodies list.
1747 if (!SeenFirstFunctionBody) {
1748 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1749 if (error_code EC = GlobalCleanup())
1751 SeenFirstFunctionBody = true;
1754 if (error_code EC = RememberAndSkipFunctionBody())
1756 // For streaming bitcode, suspend parsing when we reach the function
1757 // bodies. Subsequent materialization calls will resume it when
1758 // necessary. For streaming, the function bodies must be at the end of
1759 // the bitcode. If the bitcode file is old, the symbol table will be
1760 // at the end instead and will not have been seen yet. In this case,
1761 // just finish the parse now.
1762 if (LazyStreamer && SeenValueSymbolTable) {
1763 NextUnreadBit = Stream.GetCurrentBitNo();
1764 return error_code();
1767 case bitc::USELIST_BLOCK_ID:
1768 if (error_code EC = ParseUseLists())
1774 case BitstreamEntry::Record:
1775 // The interesting case.
1781 switch (Stream.readRecord(Entry.ID, Record)) {
1782 default: break; // Default behavior, ignore unknown content.
1783 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1784 if (Record.size() < 1)
1785 return Error(InvalidRecord);
1786 // Only version #0 and #1 are supported so far.
1787 unsigned module_version = Record[0];
1788 switch (module_version) {
1790 return Error(InvalidValue);
1792 UseRelativeIDs = false;
1795 UseRelativeIDs = true;
1800 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1802 if (ConvertToString(Record, 0, S))
1803 return Error(InvalidRecord);
1804 TheModule->setTargetTriple(S);
1807 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1809 if (ConvertToString(Record, 0, S))
1810 return Error(InvalidRecord);
1811 TheModule->setDataLayout(S);
1814 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1816 if (ConvertToString(Record, 0, S))
1817 return Error(InvalidRecord);
1818 TheModule->setModuleInlineAsm(S);
1821 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1822 // FIXME: Remove in 4.0.
1824 if (ConvertToString(Record, 0, S))
1825 return Error(InvalidRecord);
1829 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1831 if (ConvertToString(Record, 0, S))
1832 return Error(InvalidRecord);
1833 SectionTable.push_back(S);
1836 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1838 if (ConvertToString(Record, 0, S))
1839 return Error(InvalidRecord);
1840 GCTable.push_back(S);
1843 // GLOBALVAR: [pointer type, isconst, initid,
1844 // linkage, alignment, section, visibility, threadlocal,
1845 // unnamed_addr, dllstorageclass]
1846 case bitc::MODULE_CODE_GLOBALVAR: {
1847 if (Record.size() < 6)
1848 return Error(InvalidRecord);
1849 Type *Ty = getTypeByID(Record[0]);
1851 return Error(InvalidRecord);
1852 if (!Ty->isPointerTy())
1853 return Error(InvalidTypeForValue);
1854 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1855 Ty = cast<PointerType>(Ty)->getElementType();
1857 bool isConstant = Record[1];
1858 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1859 unsigned Alignment = (1 << Record[4]) >> 1;
1860 std::string Section;
1862 if (Record[5]-1 >= SectionTable.size())
1863 return Error(InvalidID);
1864 Section = SectionTable[Record[5]-1];
1866 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1867 // Local linkage must have default visibility.
1868 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1869 // FIXME: Change to an error if non-default in 4.0.
1870 Visibility = GetDecodedVisibility(Record[6]);
1872 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1873 if (Record.size() > 7)
1874 TLM = GetDecodedThreadLocalMode(Record[7]);
1876 bool UnnamedAddr = false;
1877 if (Record.size() > 8)
1878 UnnamedAddr = Record[8];
1880 bool ExternallyInitialized = false;
1881 if (Record.size() > 9)
1882 ExternallyInitialized = Record[9];
1884 GlobalVariable *NewGV =
1885 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1886 TLM, AddressSpace, ExternallyInitialized);
1887 NewGV->setAlignment(Alignment);
1888 if (!Section.empty())
1889 NewGV->setSection(Section);
1890 NewGV->setVisibility(Visibility);
1891 NewGV->setUnnamedAddr(UnnamedAddr);
1893 if (Record.size() > 10)
1894 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1896 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1898 ValueList.push_back(NewGV);
1900 // Remember which value to use for the global initializer.
1901 if (unsigned InitID = Record[2])
1902 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1905 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1906 // alignment, section, visibility, gc, unnamed_addr,
1908 case bitc::MODULE_CODE_FUNCTION: {
1909 if (Record.size() < 8)
1910 return Error(InvalidRecord);
1911 Type *Ty = getTypeByID(Record[0]);
1913 return Error(InvalidRecord);
1914 if (!Ty->isPointerTy())
1915 return Error(InvalidTypeForValue);
1917 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1919 return Error(InvalidTypeForValue);
1921 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1924 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1925 bool isProto = Record[2];
1926 Func->setLinkage(GetDecodedLinkage(Record[3]));
1927 Func->setAttributes(getAttributes(Record[4]));
1929 Func->setAlignment((1 << Record[5]) >> 1);
1931 if (Record[6]-1 >= SectionTable.size())
1932 return Error(InvalidID);
1933 Func->setSection(SectionTable[Record[6]-1]);
1935 // Local linkage must have default visibility.
1936 if (!Func->hasLocalLinkage())
1937 // FIXME: Change to an error if non-default in 4.0.
1938 Func->setVisibility(GetDecodedVisibility(Record[7]));
1939 if (Record.size() > 8 && Record[8]) {
1940 if (Record[8]-1 > GCTable.size())
1941 return Error(InvalidID);
1942 Func->setGC(GCTable[Record[8]-1].c_str());
1944 bool UnnamedAddr = false;
1945 if (Record.size() > 9)
1946 UnnamedAddr = Record[9];
1947 Func->setUnnamedAddr(UnnamedAddr);
1948 if (Record.size() > 10 && Record[10] != 0)
1949 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1951 if (Record.size() > 11)
1952 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1954 UpgradeDLLImportExportLinkage(Func, Record[3]);
1956 ValueList.push_back(Func);
1958 // If this is a function with a body, remember the prototype we are
1959 // creating now, so that we can match up the body with them later.
1961 FunctionsWithBodies.push_back(Func);
1962 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1966 // ALIAS: [alias type, aliasee val#, linkage]
1967 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
1968 case bitc::MODULE_CODE_ALIAS: {
1969 if (Record.size() < 3)
1970 return Error(InvalidRecord);
1971 Type *Ty = getTypeByID(Record[0]);
1973 return Error(InvalidRecord);
1974 auto *PTy = dyn_cast<PointerType>(Ty);
1976 return Error(InvalidTypeForValue);
1979 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1980 GetDecodedLinkage(Record[2]), "", TheModule);
1981 // Old bitcode files didn't have visibility field.
1982 // Local linkage must have default visibility.
1983 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
1984 // FIXME: Change to an error if non-default in 4.0.
1985 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1986 if (Record.size() > 4)
1987 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
1989 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
1990 if (Record.size() > 5)
1991 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
1992 if (Record.size() > 6)
1993 NewGA->setUnnamedAddr(Record[6]);
1994 ValueList.push_back(NewGA);
1995 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1998 /// MODULE_CODE_PURGEVALS: [numvals]
1999 case bitc::MODULE_CODE_PURGEVALS:
2000 // Trim down the value list to the specified size.
2001 if (Record.size() < 1 || Record[0] > ValueList.size())
2002 return Error(InvalidRecord);
2003 ValueList.shrinkTo(Record[0]);
2010 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2011 TheModule = nullptr;
2013 if (error_code EC = InitStream())
2016 // Sniff for the signature.
2017 if (Stream.Read(8) != 'B' ||
2018 Stream.Read(8) != 'C' ||
2019 Stream.Read(4) != 0x0 ||
2020 Stream.Read(4) != 0xC ||
2021 Stream.Read(4) != 0xE ||
2022 Stream.Read(4) != 0xD)
2023 return Error(InvalidBitcodeSignature);
2025 // We expect a number of well-defined blocks, though we don't necessarily
2026 // need to understand them all.
2028 if (Stream.AtEndOfStream())
2029 return error_code();
2031 BitstreamEntry Entry =
2032 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2034 switch (Entry.Kind) {
2035 case BitstreamEntry::Error:
2036 return Error(MalformedBlock);
2037 case BitstreamEntry::EndBlock:
2038 return error_code();
2040 case BitstreamEntry::SubBlock:
2042 case bitc::BLOCKINFO_BLOCK_ID:
2043 if (Stream.ReadBlockInfoBlock())
2044 return Error(MalformedBlock);
2046 case bitc::MODULE_BLOCK_ID:
2047 // Reject multiple MODULE_BLOCK's in a single bitstream.
2049 return Error(InvalidMultipleBlocks);
2051 if (error_code EC = ParseModule(false))
2054 return error_code();
2057 if (Stream.SkipBlock())
2058 return Error(InvalidRecord);
2062 case BitstreamEntry::Record:
2063 // There should be no records in the top-level of blocks.
2065 // The ranlib in Xcode 4 will align archive members by appending newlines
2066 // to the end of them. If this file size is a multiple of 4 but not 8, we
2067 // have to read and ignore these final 4 bytes :-(
2068 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2069 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2070 Stream.AtEndOfStream())
2071 return error_code();
2073 return Error(InvalidRecord);
2078 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2079 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2080 return Error(InvalidRecord);
2082 SmallVector<uint64_t, 64> Record;
2084 // Read all the records for this module.
2086 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2088 switch (Entry.Kind) {
2089 case BitstreamEntry::SubBlock: // Handled for us already.
2090 case BitstreamEntry::Error:
2091 return Error(MalformedBlock);
2092 case BitstreamEntry::EndBlock:
2093 return error_code();
2094 case BitstreamEntry::Record:
2095 // The interesting case.
2100 switch (Stream.readRecord(Entry.ID, Record)) {
2101 default: break; // Default behavior, ignore unknown content.
2102 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2104 if (ConvertToString(Record, 0, S))
2105 return Error(InvalidRecord);
2114 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2115 if (error_code EC = InitStream())
2118 // Sniff for the signature.
2119 if (Stream.Read(8) != 'B' ||
2120 Stream.Read(8) != 'C' ||
2121 Stream.Read(4) != 0x0 ||
2122 Stream.Read(4) != 0xC ||
2123 Stream.Read(4) != 0xE ||
2124 Stream.Read(4) != 0xD)
2125 return Error(InvalidBitcodeSignature);
2127 // We expect a number of well-defined blocks, though we don't necessarily
2128 // need to understand them all.
2130 BitstreamEntry Entry = Stream.advance();
2132 switch (Entry.Kind) {
2133 case BitstreamEntry::Error:
2134 return Error(MalformedBlock);
2135 case BitstreamEntry::EndBlock:
2136 return error_code();
2138 case BitstreamEntry::SubBlock:
2139 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2140 return ParseModuleTriple(Triple);
2142 // Ignore other sub-blocks.
2143 if (Stream.SkipBlock())
2144 return Error(MalformedBlock);
2147 case BitstreamEntry::Record:
2148 Stream.skipRecord(Entry.ID);
2154 /// ParseMetadataAttachment - Parse metadata attachments.
2155 error_code BitcodeReader::ParseMetadataAttachment() {
2156 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2157 return Error(InvalidRecord);
2159 SmallVector<uint64_t, 64> Record;
2161 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2163 switch (Entry.Kind) {
2164 case BitstreamEntry::SubBlock: // Handled for us already.
2165 case BitstreamEntry::Error:
2166 return Error(MalformedBlock);
2167 case BitstreamEntry::EndBlock:
2168 return error_code();
2169 case BitstreamEntry::Record:
2170 // The interesting case.
2174 // Read a metadata attachment record.
2176 switch (Stream.readRecord(Entry.ID, Record)) {
2177 default: // Default behavior: ignore.
2179 case bitc::METADATA_ATTACHMENT: {
2180 unsigned RecordLength = Record.size();
2181 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2182 return Error(InvalidRecord);
2183 Instruction *Inst = InstructionList[Record[0]];
2184 for (unsigned i = 1; i != RecordLength; i = i+2) {
2185 unsigned Kind = Record[i];
2186 DenseMap<unsigned, unsigned>::iterator I =
2187 MDKindMap.find(Kind);
2188 if (I == MDKindMap.end())
2189 return Error(InvalidID);
2190 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2191 Inst->setMetadata(I->second, cast<MDNode>(Node));
2192 if (I->second == LLVMContext::MD_tbaa)
2193 InstsWithTBAATag.push_back(Inst);
2201 /// ParseFunctionBody - Lazily parse the specified function body block.
2202 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2203 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2204 return Error(InvalidRecord);
2206 InstructionList.clear();
2207 unsigned ModuleValueListSize = ValueList.size();
2208 unsigned ModuleMDValueListSize = MDValueList.size();
2210 // Add all the function arguments to the value table.
2211 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2212 ValueList.push_back(I);
2214 unsigned NextValueNo = ValueList.size();
2215 BasicBlock *CurBB = nullptr;
2216 unsigned CurBBNo = 0;
2220 // Read all the records.
2221 SmallVector<uint64_t, 64> Record;
2223 BitstreamEntry Entry = Stream.advance();
2225 switch (Entry.Kind) {
2226 case BitstreamEntry::Error:
2227 return Error(MalformedBlock);
2228 case BitstreamEntry::EndBlock:
2229 goto OutOfRecordLoop;
2231 case BitstreamEntry::SubBlock:
2233 default: // Skip unknown content.
2234 if (Stream.SkipBlock())
2235 return Error(InvalidRecord);
2237 case bitc::CONSTANTS_BLOCK_ID:
2238 if (error_code EC = ParseConstants())
2240 NextValueNo = ValueList.size();
2242 case bitc::VALUE_SYMTAB_BLOCK_ID:
2243 if (error_code EC = ParseValueSymbolTable())
2246 case bitc::METADATA_ATTACHMENT_ID:
2247 if (error_code EC = ParseMetadataAttachment())
2250 case bitc::METADATA_BLOCK_ID:
2251 if (error_code EC = ParseMetadata())
2257 case BitstreamEntry::Record:
2258 // The interesting case.
2264 Instruction *I = nullptr;
2265 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2267 default: // Default behavior: reject
2268 return Error(InvalidValue);
2269 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2270 if (Record.size() < 1 || Record[0] == 0)
2271 return Error(InvalidRecord);
2272 // Create all the basic blocks for the function.
2273 FunctionBBs.resize(Record[0]);
2274 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2275 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2276 CurBB = FunctionBBs[0];
2279 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2280 // This record indicates that the last instruction is at the same
2281 // location as the previous instruction with a location.
2284 // Get the last instruction emitted.
2285 if (CurBB && !CurBB->empty())
2287 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2288 !FunctionBBs[CurBBNo-1]->empty())
2289 I = &FunctionBBs[CurBBNo-1]->back();
2292 return Error(InvalidRecord);
2293 I->setDebugLoc(LastLoc);
2297 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2298 I = nullptr; // Get the last instruction emitted.
2299 if (CurBB && !CurBB->empty())
2301 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2302 !FunctionBBs[CurBBNo-1]->empty())
2303 I = &FunctionBBs[CurBBNo-1]->back();
2304 if (!I || Record.size() < 4)
2305 return Error(InvalidRecord);
2307 unsigned Line = Record[0], Col = Record[1];
2308 unsigned ScopeID = Record[2], IAID = Record[3];
2310 MDNode *Scope = nullptr, *IA = nullptr;
2311 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2312 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2313 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2314 I->setDebugLoc(LastLoc);
2319 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2322 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2323 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2324 OpNum+1 > Record.size())
2325 return Error(InvalidRecord);
2327 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2329 return Error(InvalidRecord);
2330 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2331 InstructionList.push_back(I);
2332 if (OpNum < Record.size()) {
2333 if (Opc == Instruction::Add ||
2334 Opc == Instruction::Sub ||
2335 Opc == Instruction::Mul ||
2336 Opc == Instruction::Shl) {
2337 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2338 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2339 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2340 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2341 } else if (Opc == Instruction::SDiv ||
2342 Opc == Instruction::UDiv ||
2343 Opc == Instruction::LShr ||
2344 Opc == Instruction::AShr) {
2345 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2346 cast<BinaryOperator>(I)->setIsExact(true);
2347 } else if (isa<FPMathOperator>(I)) {
2349 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2350 FMF.setUnsafeAlgebra();
2351 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2353 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2355 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2356 FMF.setNoSignedZeros();
2357 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2358 FMF.setAllowReciprocal();
2360 I->setFastMathFlags(FMF);
2366 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2369 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2370 OpNum+2 != Record.size())
2371 return Error(InvalidRecord);
2373 Type *ResTy = getTypeByID(Record[OpNum]);
2374 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2375 if (Opc == -1 || !ResTy)
2376 return Error(InvalidRecord);
2377 Instruction *Temp = nullptr;
2378 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2380 InstructionList.push_back(Temp);
2381 CurBB->getInstList().push_back(Temp);
2384 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2386 InstructionList.push_back(I);
2389 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2390 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2393 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2394 return Error(InvalidRecord);
2396 SmallVector<Value*, 16> GEPIdx;
2397 while (OpNum != Record.size()) {
2399 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2400 return Error(InvalidRecord);
2401 GEPIdx.push_back(Op);
2404 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2405 InstructionList.push_back(I);
2406 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2407 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2411 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2412 // EXTRACTVAL: [opty, opval, n x indices]
2415 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2416 return Error(InvalidRecord);
2418 SmallVector<unsigned, 4> EXTRACTVALIdx;
2419 for (unsigned RecSize = Record.size();
2420 OpNum != RecSize; ++OpNum) {
2421 uint64_t Index = Record[OpNum];
2422 if ((unsigned)Index != Index)
2423 return Error(InvalidValue);
2424 EXTRACTVALIdx.push_back((unsigned)Index);
2427 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2428 InstructionList.push_back(I);
2432 case bitc::FUNC_CODE_INST_INSERTVAL: {
2433 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2436 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2437 return Error(InvalidRecord);
2439 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2440 return Error(InvalidRecord);
2442 SmallVector<unsigned, 4> INSERTVALIdx;
2443 for (unsigned RecSize = Record.size();
2444 OpNum != RecSize; ++OpNum) {
2445 uint64_t Index = Record[OpNum];
2446 if ((unsigned)Index != Index)
2447 return Error(InvalidValue);
2448 INSERTVALIdx.push_back((unsigned)Index);
2451 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2452 InstructionList.push_back(I);
2456 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2457 // obsolete form of select
2458 // handles select i1 ... in old bitcode
2460 Value *TrueVal, *FalseVal, *Cond;
2461 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2462 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2463 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2464 return Error(InvalidRecord);
2466 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2467 InstructionList.push_back(I);
2471 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2472 // new form of select
2473 // handles select i1 or select [N x i1]
2475 Value *TrueVal, *FalseVal, *Cond;
2476 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2477 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2478 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2479 return Error(InvalidRecord);
2481 // select condition can be either i1 or [N x i1]
2482 if (VectorType* vector_type =
2483 dyn_cast<VectorType>(Cond->getType())) {
2485 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2486 return Error(InvalidTypeForValue);
2489 if (Cond->getType() != Type::getInt1Ty(Context))
2490 return Error(InvalidTypeForValue);
2493 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2494 InstructionList.push_back(I);
2498 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2501 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2502 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2503 return Error(InvalidRecord);
2504 I = ExtractElementInst::Create(Vec, Idx);
2505 InstructionList.push_back(I);
2509 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2511 Value *Vec, *Elt, *Idx;
2512 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2513 popValue(Record, OpNum, NextValueNo,
2514 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2515 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2516 return Error(InvalidRecord);
2517 I = InsertElementInst::Create(Vec, Elt, Idx);
2518 InstructionList.push_back(I);
2522 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2524 Value *Vec1, *Vec2, *Mask;
2525 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2526 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2527 return Error(InvalidRecord);
2529 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2530 return Error(InvalidRecord);
2531 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2532 InstructionList.push_back(I);
2536 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2537 // Old form of ICmp/FCmp returning bool
2538 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2539 // both legal on vectors but had different behaviour.
2540 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2541 // FCmp/ICmp returning bool or vector of bool
2545 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2546 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2547 OpNum+1 != Record.size())
2548 return Error(InvalidRecord);
2550 if (LHS->getType()->isFPOrFPVectorTy())
2551 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2553 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2554 InstructionList.push_back(I);
2558 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2560 unsigned Size = Record.size();
2562 I = ReturnInst::Create(Context);
2563 InstructionList.push_back(I);
2568 Value *Op = nullptr;
2569 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2570 return Error(InvalidRecord);
2571 if (OpNum != Record.size())
2572 return Error(InvalidRecord);
2574 I = ReturnInst::Create(Context, Op);
2575 InstructionList.push_back(I);
2578 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2579 if (Record.size() != 1 && Record.size() != 3)
2580 return Error(InvalidRecord);
2581 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2583 return Error(InvalidRecord);
2585 if (Record.size() == 1) {
2586 I = BranchInst::Create(TrueDest);
2587 InstructionList.push_back(I);
2590 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2591 Value *Cond = getValue(Record, 2, NextValueNo,
2592 Type::getInt1Ty(Context));
2593 if (!FalseDest || !Cond)
2594 return Error(InvalidRecord);
2595 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2596 InstructionList.push_back(I);
2600 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2602 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2603 // "New" SwitchInst format with case ranges. The changes to write this
2604 // format were reverted but we still recognize bitcode that uses it.
2605 // Hopefully someday we will have support for case ranges and can use
2606 // this format again.
2608 Type *OpTy = getTypeByID(Record[1]);
2609 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2611 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2612 BasicBlock *Default = getBasicBlock(Record[3]);
2613 if (!OpTy || !Cond || !Default)
2614 return Error(InvalidRecord);
2616 unsigned NumCases = Record[4];
2618 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2619 InstructionList.push_back(SI);
2621 unsigned CurIdx = 5;
2622 for (unsigned i = 0; i != NumCases; ++i) {
2623 SmallVector<ConstantInt*, 1> CaseVals;
2624 unsigned NumItems = Record[CurIdx++];
2625 for (unsigned ci = 0; ci != NumItems; ++ci) {
2626 bool isSingleNumber = Record[CurIdx++];
2629 unsigned ActiveWords = 1;
2630 if (ValueBitWidth > 64)
2631 ActiveWords = Record[CurIdx++];
2632 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2634 CurIdx += ActiveWords;
2636 if (!isSingleNumber) {
2638 if (ValueBitWidth > 64)
2639 ActiveWords = Record[CurIdx++];
2641 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2643 CurIdx += ActiveWords;
2645 // FIXME: It is not clear whether values in the range should be
2646 // compared as signed or unsigned values. The partially
2647 // implemented changes that used this format in the past used
2648 // unsigned comparisons.
2649 for ( ; Low.ule(High); ++Low)
2650 CaseVals.push_back(ConstantInt::get(Context, Low));
2652 CaseVals.push_back(ConstantInt::get(Context, Low));
2654 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2655 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2656 cve = CaseVals.end(); cvi != cve; ++cvi)
2657 SI->addCase(*cvi, DestBB);
2663 // Old SwitchInst format without case ranges.
2665 if (Record.size() < 3 || (Record.size() & 1) == 0)
2666 return Error(InvalidRecord);
2667 Type *OpTy = getTypeByID(Record[0]);
2668 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2669 BasicBlock *Default = getBasicBlock(Record[2]);
2670 if (!OpTy || !Cond || !Default)
2671 return Error(InvalidRecord);
2672 unsigned NumCases = (Record.size()-3)/2;
2673 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2674 InstructionList.push_back(SI);
2675 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2676 ConstantInt *CaseVal =
2677 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2678 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2679 if (!CaseVal || !DestBB) {
2681 return Error(InvalidRecord);
2683 SI->addCase(CaseVal, DestBB);
2688 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2689 if (Record.size() < 2)
2690 return Error(InvalidRecord);
2691 Type *OpTy = getTypeByID(Record[0]);
2692 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2693 if (!OpTy || !Address)
2694 return Error(InvalidRecord);
2695 unsigned NumDests = Record.size()-2;
2696 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2697 InstructionList.push_back(IBI);
2698 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2699 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2700 IBI->addDestination(DestBB);
2703 return Error(InvalidRecord);
2710 case bitc::FUNC_CODE_INST_INVOKE: {
2711 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2712 if (Record.size() < 4)
2713 return Error(InvalidRecord);
2714 AttributeSet PAL = getAttributes(Record[0]);
2715 unsigned CCInfo = Record[1];
2716 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2717 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2721 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2722 return Error(InvalidRecord);
2724 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2725 FunctionType *FTy = !CalleeTy ? nullptr :
2726 dyn_cast<FunctionType>(CalleeTy->getElementType());
2728 // Check that the right number of fixed parameters are here.
2729 if (!FTy || !NormalBB || !UnwindBB ||
2730 Record.size() < OpNum+FTy->getNumParams())
2731 return Error(InvalidRecord);
2733 SmallVector<Value*, 16> Ops;
2734 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2735 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2736 FTy->getParamType(i)));
2738 return Error(InvalidRecord);
2741 if (!FTy->isVarArg()) {
2742 if (Record.size() != OpNum)
2743 return Error(InvalidRecord);
2745 // Read type/value pairs for varargs params.
2746 while (OpNum != Record.size()) {
2748 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2749 return Error(InvalidRecord);
2754 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2755 InstructionList.push_back(I);
2756 cast<InvokeInst>(I)->setCallingConv(
2757 static_cast<CallingConv::ID>(CCInfo));
2758 cast<InvokeInst>(I)->setAttributes(PAL);
2761 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2763 Value *Val = nullptr;
2764 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2765 return Error(InvalidRecord);
2766 I = ResumeInst::Create(Val);
2767 InstructionList.push_back(I);
2770 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2771 I = new UnreachableInst(Context);
2772 InstructionList.push_back(I);
2774 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2775 if (Record.size() < 1 || ((Record.size()-1)&1))
2776 return Error(InvalidRecord);
2777 Type *Ty = getTypeByID(Record[0]);
2779 return Error(InvalidRecord);
2781 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2782 InstructionList.push_back(PN);
2784 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2786 // With the new function encoding, it is possible that operands have
2787 // negative IDs (for forward references). Use a signed VBR
2788 // representation to keep the encoding small.
2790 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2792 V = getValue(Record, 1+i, NextValueNo, Ty);
2793 BasicBlock *BB = getBasicBlock(Record[2+i]);
2795 return Error(InvalidRecord);
2796 PN->addIncoming(V, BB);
2802 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2803 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2805 if (Record.size() < 4)
2806 return Error(InvalidRecord);
2807 Type *Ty = getTypeByID(Record[Idx++]);
2809 return Error(InvalidRecord);
2810 Value *PersFn = nullptr;
2811 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2812 return Error(InvalidRecord);
2814 bool IsCleanup = !!Record[Idx++];
2815 unsigned NumClauses = Record[Idx++];
2816 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2817 LP->setCleanup(IsCleanup);
2818 for (unsigned J = 0; J != NumClauses; ++J) {
2819 LandingPadInst::ClauseType CT =
2820 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2823 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2825 return Error(InvalidRecord);
2828 assert((CT != LandingPadInst::Catch ||
2829 !isa<ArrayType>(Val->getType())) &&
2830 "Catch clause has a invalid type!");
2831 assert((CT != LandingPadInst::Filter ||
2832 isa<ArrayType>(Val->getType())) &&
2833 "Filter clause has invalid type!");
2834 LP->addClause(cast<Constant>(Val));
2838 InstructionList.push_back(I);
2842 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2843 if (Record.size() != 4)
2844 return Error(InvalidRecord);
2846 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2847 Type *OpTy = getTypeByID(Record[1]);
2848 Value *Size = getFnValueByID(Record[2], OpTy);
2849 unsigned Align = Record[3];
2851 return Error(InvalidRecord);
2852 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2853 InstructionList.push_back(I);
2856 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2859 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2860 OpNum+2 != Record.size())
2861 return Error(InvalidRecord);
2863 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2864 InstructionList.push_back(I);
2867 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2868 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2871 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2872 OpNum+4 != Record.size())
2873 return Error(InvalidRecord);
2876 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2877 if (Ordering == NotAtomic || Ordering == Release ||
2878 Ordering == AcquireRelease)
2879 return Error(InvalidRecord);
2880 if (Ordering != NotAtomic && Record[OpNum] == 0)
2881 return Error(InvalidRecord);
2882 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2884 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2885 Ordering, SynchScope);
2886 InstructionList.push_back(I);
2889 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2892 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2893 popValue(Record, OpNum, NextValueNo,
2894 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2895 OpNum+2 != Record.size())
2896 return Error(InvalidRecord);
2898 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2899 InstructionList.push_back(I);
2902 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2903 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2906 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2907 popValue(Record, OpNum, NextValueNo,
2908 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2909 OpNum+4 != Record.size())
2910 return Error(InvalidRecord);
2912 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2913 if (Ordering == NotAtomic || Ordering == Acquire ||
2914 Ordering == AcquireRelease)
2915 return Error(InvalidRecord);
2916 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2917 if (Ordering != NotAtomic && Record[OpNum] == 0)
2918 return Error(InvalidRecord);
2920 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2921 Ordering, SynchScope);
2922 InstructionList.push_back(I);
2925 case bitc::FUNC_CODE_INST_CMPXCHG: {
2926 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2929 Value *Ptr, *Cmp, *New;
2930 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2931 popValue(Record, OpNum, NextValueNo,
2932 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2933 popValue(Record, OpNum, NextValueNo,
2934 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2935 (OpNum + 3 != Record.size() && OpNum + 4 != Record.size()))
2936 return Error(InvalidRecord);
2937 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2938 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2939 return Error(InvalidRecord);
2940 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2942 AtomicOrdering FailureOrdering;
2943 if (Record.size() < 7)
2945 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2947 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
2949 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
2951 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2952 InstructionList.push_back(I);
2955 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2956 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2959 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2960 popValue(Record, OpNum, NextValueNo,
2961 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2962 OpNum+4 != Record.size())
2963 return Error(InvalidRecord);
2964 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2965 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2966 Operation > AtomicRMWInst::LAST_BINOP)
2967 return Error(InvalidRecord);
2968 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2969 if (Ordering == NotAtomic || Ordering == Unordered)
2970 return Error(InvalidRecord);
2971 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2972 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2973 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2974 InstructionList.push_back(I);
2977 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2978 if (2 != Record.size())
2979 return Error(InvalidRecord);
2980 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2981 if (Ordering == NotAtomic || Ordering == Unordered ||
2982 Ordering == Monotonic)
2983 return Error(InvalidRecord);
2984 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2985 I = new FenceInst(Context, Ordering, SynchScope);
2986 InstructionList.push_back(I);
2989 case bitc::FUNC_CODE_INST_CALL: {
2990 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2991 if (Record.size() < 3)
2992 return Error(InvalidRecord);
2994 AttributeSet PAL = getAttributes(Record[0]);
2995 unsigned CCInfo = Record[1];
2999 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3000 return Error(InvalidRecord);
3002 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3003 FunctionType *FTy = nullptr;
3004 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3005 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3006 return Error(InvalidRecord);
3008 SmallVector<Value*, 16> Args;
3009 // Read the fixed params.
3010 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3011 if (FTy->getParamType(i)->isLabelTy())
3012 Args.push_back(getBasicBlock(Record[OpNum]));
3014 Args.push_back(getValue(Record, OpNum, NextValueNo,
3015 FTy->getParamType(i)));
3017 return Error(InvalidRecord);
3020 // Read type/value pairs for varargs params.
3021 if (!FTy->isVarArg()) {
3022 if (OpNum != Record.size())
3023 return Error(InvalidRecord);
3025 while (OpNum != Record.size()) {
3027 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3028 return Error(InvalidRecord);
3033 I = CallInst::Create(Callee, Args);
3034 InstructionList.push_back(I);
3035 cast<CallInst>(I)->setCallingConv(
3036 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3037 CallInst::TailCallKind TCK = CallInst::TCK_None;
3039 TCK = CallInst::TCK_Tail;
3040 if (CCInfo & (1 << 14))
3041 TCK = CallInst::TCK_MustTail;
3042 cast<CallInst>(I)->setTailCallKind(TCK);
3043 cast<CallInst>(I)->setAttributes(PAL);
3046 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3047 if (Record.size() < 3)
3048 return Error(InvalidRecord);
3049 Type *OpTy = getTypeByID(Record[0]);
3050 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3051 Type *ResTy = getTypeByID(Record[2]);
3052 if (!OpTy || !Op || !ResTy)
3053 return Error(InvalidRecord);
3054 I = new VAArgInst(Op, ResTy);
3055 InstructionList.push_back(I);
3060 // Add instruction to end of current BB. If there is no current BB, reject
3064 return Error(InvalidInstructionWithNoBB);
3066 CurBB->getInstList().push_back(I);
3068 // If this was a terminator instruction, move to the next block.
3069 if (isa<TerminatorInst>(I)) {
3071 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3074 // Non-void values get registered in the value table for future use.
3075 if (I && !I->getType()->isVoidTy())
3076 ValueList.AssignValue(I, NextValueNo++);
3081 // Check the function list for unresolved values.
3082 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3083 if (!A->getParent()) {
3084 // We found at least one unresolved value. Nuke them all to avoid leaks.
3085 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3086 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3087 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3091 return Error(NeverResolvedValueFoundInFunction);
3095 // FIXME: Check for unresolved forward-declared metadata references
3096 // and clean up leaks.
3098 // See if anything took the address of blocks in this function. If so,
3099 // resolve them now.
3100 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3101 BlockAddrFwdRefs.find(F);
3102 if (BAFRI != BlockAddrFwdRefs.end()) {
3103 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3104 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3105 unsigned BlockIdx = RefList[i].first;
3106 if (BlockIdx >= FunctionBBs.size())
3107 return Error(InvalidID);
3109 GlobalVariable *FwdRef = RefList[i].second;
3110 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3111 FwdRef->eraseFromParent();
3114 BlockAddrFwdRefs.erase(BAFRI);
3117 // Trim the value list down to the size it was before we parsed this function.
3118 ValueList.shrinkTo(ModuleValueListSize);
3119 MDValueList.shrinkTo(ModuleMDValueListSize);
3120 std::vector<BasicBlock*>().swap(FunctionBBs);
3121 return error_code();
3124 /// Find the function body in the bitcode stream
3125 error_code BitcodeReader::FindFunctionInStream(Function *F,
3126 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3127 while (DeferredFunctionInfoIterator->second == 0) {
3128 if (Stream.AtEndOfStream())
3129 return Error(CouldNotFindFunctionInStream);
3130 // ParseModule will parse the next body in the stream and set its
3131 // position in the DeferredFunctionInfo map.
3132 if (error_code EC = ParseModule(true))
3135 return error_code();
3138 //===----------------------------------------------------------------------===//
3139 // GVMaterializer implementation
3140 //===----------------------------------------------------------------------===//
3143 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3144 if (const Function *F = dyn_cast<Function>(GV)) {
3145 return F->isDeclaration() &&
3146 DeferredFunctionInfo.count(const_cast<Function*>(F));
3151 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3152 Function *F = dyn_cast<Function>(GV);
3153 // If it's not a function or is already material, ignore the request.
3154 if (!F || !F->isMaterializable())
3155 return error_code();
3157 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3158 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3159 // If its position is recorded as 0, its body is somewhere in the stream
3160 // but we haven't seen it yet.
3161 if (DFII->second == 0 && LazyStreamer)
3162 if (error_code EC = FindFunctionInStream(F, DFII))
3165 // Move the bit stream to the saved position of the deferred function body.
3166 Stream.JumpToBit(DFII->second);
3168 if (error_code EC = ParseFunctionBody(F))
3171 // Upgrade any old intrinsic calls in the function.
3172 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3173 E = UpgradedIntrinsics.end(); I != E; ++I) {
3174 if (I->first != I->second) {
3175 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3177 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3178 UpgradeIntrinsicCall(CI, I->second);
3183 return error_code();
3186 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3187 const Function *F = dyn_cast<Function>(GV);
3188 if (!F || F->isDeclaration())
3190 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3193 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3194 Function *F = dyn_cast<Function>(GV);
3195 // If this function isn't dematerializable, this is a noop.
3196 if (!F || !isDematerializable(F))
3199 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3201 // Just forget the function body, we can remat it later.
3206 error_code BitcodeReader::MaterializeModule(Module *M) {
3207 assert(M == TheModule &&
3208 "Can only Materialize the Module this BitcodeReader is attached to.");
3209 // Iterate over the module, deserializing any functions that are still on
3211 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3213 if (F->isMaterializable()) {
3214 if (error_code EC = Materialize(F))
3218 // At this point, if there are any function bodies, the current bit is
3219 // pointing to the END_BLOCK record after them. Now make sure the rest
3220 // of the bits in the module have been read.
3224 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3225 // delete the old functions to clean up. We can't do this unless the entire
3226 // module is materialized because there could always be another function body
3227 // with calls to the old function.
3228 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3229 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3230 if (I->first != I->second) {
3231 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3233 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3234 UpgradeIntrinsicCall(CI, I->second);
3236 if (!I->first->use_empty())
3237 I->first->replaceAllUsesWith(I->second);
3238 I->first->eraseFromParent();
3241 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3243 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3244 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3246 UpgradeDebugInfo(*M);
3247 return error_code();
3250 error_code BitcodeReader::InitStream() {
3252 return InitLazyStream();
3253 return InitStreamFromBuffer();
3256 error_code BitcodeReader::InitStreamFromBuffer() {
3257 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3258 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3260 if (Buffer->getBufferSize() & 3) {
3261 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3262 return Error(InvalidBitcodeSignature);
3264 return Error(BitcodeStreamInvalidSize);
3267 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3268 // The magic number is 0x0B17C0DE stored in little endian.
3269 if (isBitcodeWrapper(BufPtr, BufEnd))
3270 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3271 return Error(InvalidBitcodeWrapperHeader);
3273 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3274 Stream.init(*StreamFile);
3276 return error_code();
3279 error_code BitcodeReader::InitLazyStream() {
3280 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3282 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3283 StreamFile.reset(new BitstreamReader(Bytes));
3284 Stream.init(*StreamFile);
3286 unsigned char buf[16];
3287 if (Bytes->readBytes(0, 16, buf) == -1)
3288 return Error(BitcodeStreamInvalidSize);
3290 if (!isBitcode(buf, buf + 16))
3291 return Error(InvalidBitcodeSignature);
3293 if (isBitcodeWrapper(buf, buf + 4)) {
3294 const unsigned char *bitcodeStart = buf;
3295 const unsigned char *bitcodeEnd = buf + 16;
3296 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3297 Bytes->dropLeadingBytes(bitcodeStart - buf);
3298 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3300 return error_code();
3304 class BitcodeErrorCategoryType : public std::error_category {
3305 const char *name() const LLVM_NOEXCEPT override {
3306 return "llvm.bitcode";
3308 std::string message(int IE) const override {
3309 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3311 case BitcodeReader::BitcodeStreamInvalidSize:
3312 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3313 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3314 return "Conflicting METADATA_KIND records";
3315 case BitcodeReader::CouldNotFindFunctionInStream:
3316 return "Could not find function in stream";
3317 case BitcodeReader::ExpectedConstant:
3318 return "Expected a constant";
3319 case BitcodeReader::InsufficientFunctionProtos:
3320 return "Insufficient function protos";
3321 case BitcodeReader::InvalidBitcodeSignature:
3322 return "Invalid bitcode signature";
3323 case BitcodeReader::InvalidBitcodeWrapperHeader:
3324 return "Invalid bitcode wrapper header";
3325 case BitcodeReader::InvalidConstantReference:
3326 return "Invalid ronstant reference";
3327 case BitcodeReader::InvalidID:
3328 return "Invalid ID";
3329 case BitcodeReader::InvalidInstructionWithNoBB:
3330 return "Invalid instruction with no BB";
3331 case BitcodeReader::InvalidRecord:
3332 return "Invalid record";
3333 case BitcodeReader::InvalidTypeForValue:
3334 return "Invalid type for value";
3335 case BitcodeReader::InvalidTYPETable:
3336 return "Invalid TYPE table";
3337 case BitcodeReader::InvalidType:
3338 return "Invalid type";
3339 case BitcodeReader::MalformedBlock:
3340 return "Malformed block";
3341 case BitcodeReader::MalformedGlobalInitializerSet:
3342 return "Malformed global initializer set";
3343 case BitcodeReader::InvalidMultipleBlocks:
3344 return "Invalid multiple blocks";
3345 case BitcodeReader::NeverResolvedValueFoundInFunction:
3346 return "Never resolved value found in function";
3347 case BitcodeReader::InvalidValue:
3348 return "Invalid value";
3350 llvm_unreachable("Unknown error type!");
3355 const std::error_category &BitcodeReader::BitcodeErrorCategory() {
3356 static BitcodeErrorCategoryType O;
3360 //===----------------------------------------------------------------------===//
3361 // External interface
3362 //===----------------------------------------------------------------------===//
3364 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3366 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3367 LLVMContext &Context) {
3368 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3369 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3370 M->setMaterializer(R);
3371 if (error_code EC = R->ParseBitcodeInto(M)) {
3372 delete M; // Also deletes R.
3375 // Have the BitcodeReader dtor delete 'Buffer'.
3376 R->setBufferOwned(true);
3378 R->materializeForwardReferencedFunctions();
3384 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3385 DataStreamer *streamer,
3386 LLVMContext &Context,
3387 std::string *ErrMsg) {
3388 Module *M = new Module(name, Context);
3389 BitcodeReader *R = new BitcodeReader(streamer, Context);
3390 M->setMaterializer(R);
3391 if (error_code EC = R->ParseBitcodeInto(M)) {
3393 *ErrMsg = EC.message();
3394 delete M; // Also deletes R.
3397 R->setBufferOwned(false); // no buffer to delete
3401 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3402 LLVMContext &Context) {
3403 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3406 Module *M = ModuleOrErr.get();
3408 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3409 // there was an error.
3410 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3412 // Read in the entire module, and destroy the BitcodeReader.
3413 if (error_code EC = M->materializeAllPermanently()) {
3418 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3419 // written. We must defer until the Module has been fully materialized.
3424 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3425 LLVMContext& Context,
3426 std::string *ErrMsg) {
3427 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3428 // Don't let the BitcodeReader dtor delete 'Buffer'.
3429 R->setBufferOwned(false);
3431 std::string Triple("");
3432 if (error_code EC = R->ParseTriple(Triple))
3434 *ErrMsg = EC.message();