1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/Bitcode/LLVMBitCodes.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 void BitcodeReader::materializeForwardReferencedFunctions() {
35 while (!BlockAddrFwdRefs.empty()) {
36 Function *F = BlockAddrFwdRefs.begin()->first;
41 void BitcodeReader::FreeState() {
43 std::vector<Type*>().swap(TypeList);
47 std::vector<AttributeSet>().swap(MAttributes);
48 std::vector<BasicBlock*>().swap(FunctionBBs);
49 std::vector<Function*>().swap(FunctionsWithBodies);
50 DeferredFunctionInfo.clear();
53 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
56 //===----------------------------------------------------------------------===//
57 // Helper functions to implement forward reference resolution, etc.
58 //===----------------------------------------------------------------------===//
60 /// ConvertToString - Convert a string from a record into an std::string, return
62 template<typename StrTy>
63 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
65 if (Idx > Record.size())
68 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
69 Result += (char)Record[i];
73 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
75 default: // Map unknown/new linkages to external
76 case 0: return GlobalValue::ExternalLinkage;
77 case 1: return GlobalValue::WeakAnyLinkage;
78 case 2: return GlobalValue::AppendingLinkage;
79 case 3: return GlobalValue::InternalLinkage;
80 case 4: return GlobalValue::LinkOnceAnyLinkage;
81 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
82 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
83 case 7: return GlobalValue::ExternalWeakLinkage;
84 case 8: return GlobalValue::CommonLinkage;
85 case 9: return GlobalValue::PrivateLinkage;
86 case 10: return GlobalValue::WeakODRLinkage;
87 case 11: return GlobalValue::LinkOnceODRLinkage;
88 case 12: return GlobalValue::AvailableExternallyLinkage;
90 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
92 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
96 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
101 case 2: return GlobalValue::ProtectedVisibility;
105 static GlobalValue::DLLStorageClassTypes
106 GetDecodedDLLStorageClass(unsigned Val) {
108 default: // Map unknown values to default.
109 case 0: return GlobalValue::DefaultStorageClass;
110 case 1: return GlobalValue::DLLImportStorageClass;
111 case 2: return GlobalValue::DLLExportStorageClass;
115 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
117 case 0: return GlobalVariable::NotThreadLocal;
118 default: // Map unknown non-zero value to general dynamic.
119 case 1: return GlobalVariable::GeneralDynamicTLSModel;
120 case 2: return GlobalVariable::LocalDynamicTLSModel;
121 case 3: return GlobalVariable::InitialExecTLSModel;
122 case 4: return GlobalVariable::LocalExecTLSModel;
126 static int GetDecodedCastOpcode(unsigned Val) {
129 case bitc::CAST_TRUNC : return Instruction::Trunc;
130 case bitc::CAST_ZEXT : return Instruction::ZExt;
131 case bitc::CAST_SEXT : return Instruction::SExt;
132 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
133 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
134 case bitc::CAST_UITOFP : return Instruction::UIToFP;
135 case bitc::CAST_SITOFP : return Instruction::SIToFP;
136 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
137 case bitc::CAST_FPEXT : return Instruction::FPExt;
138 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
139 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
140 case bitc::CAST_BITCAST : return Instruction::BitCast;
141 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
144 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
147 case bitc::BINOP_ADD:
148 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
149 case bitc::BINOP_SUB:
150 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
151 case bitc::BINOP_MUL:
152 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
153 case bitc::BINOP_UDIV: return Instruction::UDiv;
154 case bitc::BINOP_SDIV:
155 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
156 case bitc::BINOP_UREM: return Instruction::URem;
157 case bitc::BINOP_SREM:
158 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
159 case bitc::BINOP_SHL: return Instruction::Shl;
160 case bitc::BINOP_LSHR: return Instruction::LShr;
161 case bitc::BINOP_ASHR: return Instruction::AShr;
162 case bitc::BINOP_AND: return Instruction::And;
163 case bitc::BINOP_OR: return Instruction::Or;
164 case bitc::BINOP_XOR: return Instruction::Xor;
168 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
170 default: return AtomicRMWInst::BAD_BINOP;
171 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
172 case bitc::RMW_ADD: return AtomicRMWInst::Add;
173 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
174 case bitc::RMW_AND: return AtomicRMWInst::And;
175 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
176 case bitc::RMW_OR: return AtomicRMWInst::Or;
177 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
178 case bitc::RMW_MAX: return AtomicRMWInst::Max;
179 case bitc::RMW_MIN: return AtomicRMWInst::Min;
180 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
181 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
185 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
187 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
188 case bitc::ORDERING_UNORDERED: return Unordered;
189 case bitc::ORDERING_MONOTONIC: return Monotonic;
190 case bitc::ORDERING_ACQUIRE: return Acquire;
191 case bitc::ORDERING_RELEASE: return Release;
192 case bitc::ORDERING_ACQREL: return AcquireRelease;
193 default: // Map unknown orderings to sequentially-consistent.
194 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
198 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
200 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
201 default: // Map unknown scopes to cross-thread.
202 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
206 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
208 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
209 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
215 /// @brief A class for maintaining the slot number definition
216 /// as a placeholder for the actual definition for forward constants defs.
217 class ConstantPlaceHolder : public ConstantExpr {
218 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
220 // allocate space for exactly one operand
221 void *operator new(size_t s) {
222 return User::operator new(s, 1);
224 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
225 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
226 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
229 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
230 static bool classof(const Value *V) {
231 return isa<ConstantExpr>(V) &&
232 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
236 /// Provide fast operand accessors
237 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
241 // FIXME: can we inherit this from ConstantExpr?
243 struct OperandTraits<ConstantPlaceHolder> :
244 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
249 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
258 WeakVH &OldV = ValuePtrs[Idx];
264 // Handle constants and non-constants (e.g. instrs) differently for
266 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
267 ResolveConstants.push_back(std::make_pair(PHC, Idx));
270 // If there was a forward reference to this value, replace it.
271 Value *PrevVal = OldV;
272 OldV->replaceAllUsesWith(V);
278 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
283 if (Value *V = ValuePtrs[Idx]) {
284 assert(Ty == V->getType() && "Type mismatch in constant table!");
285 return cast<Constant>(V);
288 // Create and return a placeholder, which will later be RAUW'd.
289 Constant *C = new ConstantPlaceHolder(Ty, Context);
294 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
298 if (Value *V = ValuePtrs[Idx]) {
299 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
303 // No type specified, must be invalid reference.
304 if (!Ty) return nullptr;
306 // Create and return a placeholder, which will later be RAUW'd.
307 Value *V = new Argument(Ty);
312 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
313 /// resolves any forward references. The idea behind this is that we sometimes
314 /// get constants (such as large arrays) which reference *many* forward ref
315 /// constants. Replacing each of these causes a lot of thrashing when
316 /// building/reuniquing the constant. Instead of doing this, we look at all the
317 /// uses and rewrite all the place holders at once for any constant that uses
319 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
320 // Sort the values by-pointer so that they are efficient to look up with a
322 std::sort(ResolveConstants.begin(), ResolveConstants.end());
324 SmallVector<Constant*, 64> NewOps;
326 while (!ResolveConstants.empty()) {
327 Value *RealVal = operator[](ResolveConstants.back().second);
328 Constant *Placeholder = ResolveConstants.back().first;
329 ResolveConstants.pop_back();
331 // Loop over all users of the placeholder, updating them to reference the
332 // new value. If they reference more than one placeholder, update them all
334 while (!Placeholder->use_empty()) {
335 auto UI = Placeholder->user_begin();
338 // If the using object isn't uniqued, just update the operands. This
339 // handles instructions and initializers for global variables.
340 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
341 UI.getUse().set(RealVal);
345 // Otherwise, we have a constant that uses the placeholder. Replace that
346 // constant with a new constant that has *all* placeholder uses updated.
347 Constant *UserC = cast<Constant>(U);
348 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
351 if (!isa<ConstantPlaceHolder>(*I)) {
352 // Not a placeholder reference.
354 } else if (*I == Placeholder) {
355 // Common case is that it just references this one placeholder.
358 // Otherwise, look up the placeholder in ResolveConstants.
359 ResolveConstantsTy::iterator It =
360 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
361 std::pair<Constant*, unsigned>(cast<Constant>(*I),
363 assert(It != ResolveConstants.end() && It->first == *I);
364 NewOp = operator[](It->second);
367 NewOps.push_back(cast<Constant>(NewOp));
370 // Make the new constant.
372 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
373 NewC = ConstantArray::get(UserCA->getType(), NewOps);
374 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
375 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
376 } else if (isa<ConstantVector>(UserC)) {
377 NewC = ConstantVector::get(NewOps);
379 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
380 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
383 UserC->replaceAllUsesWith(NewC);
384 UserC->destroyConstant();
388 // Update all ValueHandles, they should be the only users at this point.
389 Placeholder->replaceAllUsesWith(RealVal);
394 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
403 WeakVH &OldV = MDValuePtrs[Idx];
409 // If there was a forward reference to this value, replace it.
410 MDNode *PrevVal = cast<MDNode>(OldV);
411 OldV->replaceAllUsesWith(V);
412 MDNode::deleteTemporary(PrevVal);
413 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
415 MDValuePtrs[Idx] = V;
418 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
422 if (Value *V = MDValuePtrs[Idx]) {
423 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
427 // Create and return a placeholder, which will later be RAUW'd.
428 Value *V = MDNode::getTemporary(Context, None);
429 MDValuePtrs[Idx] = V;
433 Type *BitcodeReader::getTypeByID(unsigned ID) {
434 // The type table size is always specified correctly.
435 if (ID >= TypeList.size())
438 if (Type *Ty = TypeList[ID])
441 // If we have a forward reference, the only possible case is when it is to a
442 // named struct. Just create a placeholder for now.
443 return TypeList[ID] = StructType::create(Context);
447 //===----------------------------------------------------------------------===//
448 // Functions for parsing blocks from the bitcode file
449 //===----------------------------------------------------------------------===//
452 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
453 /// been decoded from the given integer. This function must stay in sync with
454 /// 'encodeLLVMAttributesForBitcode'.
455 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
456 uint64_t EncodedAttrs) {
457 // FIXME: Remove in 4.0.
459 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
460 // the bits above 31 down by 11 bits.
461 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
462 assert((!Alignment || isPowerOf2_32(Alignment)) &&
463 "Alignment must be a power of two.");
466 B.addAlignmentAttr(Alignment);
467 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
468 (EncodedAttrs & 0xffff));
471 std::error_code BitcodeReader::ParseAttributeBlock() {
472 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
473 return Error(InvalidRecord);
475 if (!MAttributes.empty())
476 return Error(InvalidMultipleBlocks);
478 SmallVector<uint64_t, 64> Record;
480 SmallVector<AttributeSet, 8> Attrs;
482 // Read all the records.
484 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
486 switch (Entry.Kind) {
487 case BitstreamEntry::SubBlock: // Handled for us already.
488 case BitstreamEntry::Error:
489 return Error(MalformedBlock);
490 case BitstreamEntry::EndBlock:
491 return std::error_code();
492 case BitstreamEntry::Record:
493 // The interesting case.
499 switch (Stream.readRecord(Entry.ID, Record)) {
500 default: // Default behavior: ignore.
502 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
503 // FIXME: Remove in 4.0.
504 if (Record.size() & 1)
505 return Error(InvalidRecord);
507 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
509 decodeLLVMAttributesForBitcode(B, Record[i+1]);
510 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
513 MAttributes.push_back(AttributeSet::get(Context, Attrs));
517 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
518 for (unsigned i = 0, e = Record.size(); i != e; ++i)
519 Attrs.push_back(MAttributeGroups[Record[i]]);
521 MAttributes.push_back(AttributeSet::get(Context, Attrs));
529 // Returns Attribute::None on unrecognized codes.
530 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
533 return Attribute::None;
534 case bitc::ATTR_KIND_ALIGNMENT:
535 return Attribute::Alignment;
536 case bitc::ATTR_KIND_ALWAYS_INLINE:
537 return Attribute::AlwaysInline;
538 case bitc::ATTR_KIND_BUILTIN:
539 return Attribute::Builtin;
540 case bitc::ATTR_KIND_BY_VAL:
541 return Attribute::ByVal;
542 case bitc::ATTR_KIND_IN_ALLOCA:
543 return Attribute::InAlloca;
544 case bitc::ATTR_KIND_COLD:
545 return Attribute::Cold;
546 case bitc::ATTR_KIND_INLINE_HINT:
547 return Attribute::InlineHint;
548 case bitc::ATTR_KIND_IN_REG:
549 return Attribute::InReg;
550 case bitc::ATTR_KIND_JUMP_TABLE:
551 return Attribute::JumpTable;
552 case bitc::ATTR_KIND_MIN_SIZE:
553 return Attribute::MinSize;
554 case bitc::ATTR_KIND_NAKED:
555 return Attribute::Naked;
556 case bitc::ATTR_KIND_NEST:
557 return Attribute::Nest;
558 case bitc::ATTR_KIND_NO_ALIAS:
559 return Attribute::NoAlias;
560 case bitc::ATTR_KIND_NO_BUILTIN:
561 return Attribute::NoBuiltin;
562 case bitc::ATTR_KIND_NO_CAPTURE:
563 return Attribute::NoCapture;
564 case bitc::ATTR_KIND_NO_DUPLICATE:
565 return Attribute::NoDuplicate;
566 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
567 return Attribute::NoImplicitFloat;
568 case bitc::ATTR_KIND_NO_INLINE:
569 return Attribute::NoInline;
570 case bitc::ATTR_KIND_NON_LAZY_BIND:
571 return Attribute::NonLazyBind;
572 case bitc::ATTR_KIND_NON_NULL:
573 return Attribute::NonNull;
574 case bitc::ATTR_KIND_NO_RED_ZONE:
575 return Attribute::NoRedZone;
576 case bitc::ATTR_KIND_NO_RETURN:
577 return Attribute::NoReturn;
578 case bitc::ATTR_KIND_NO_UNWIND:
579 return Attribute::NoUnwind;
580 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
581 return Attribute::OptimizeForSize;
582 case bitc::ATTR_KIND_OPTIMIZE_NONE:
583 return Attribute::OptimizeNone;
584 case bitc::ATTR_KIND_READ_NONE:
585 return Attribute::ReadNone;
586 case bitc::ATTR_KIND_READ_ONLY:
587 return Attribute::ReadOnly;
588 case bitc::ATTR_KIND_RETURNED:
589 return Attribute::Returned;
590 case bitc::ATTR_KIND_RETURNS_TWICE:
591 return Attribute::ReturnsTwice;
592 case bitc::ATTR_KIND_S_EXT:
593 return Attribute::SExt;
594 case bitc::ATTR_KIND_STACK_ALIGNMENT:
595 return Attribute::StackAlignment;
596 case bitc::ATTR_KIND_STACK_PROTECT:
597 return Attribute::StackProtect;
598 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
599 return Attribute::StackProtectReq;
600 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
601 return Attribute::StackProtectStrong;
602 case bitc::ATTR_KIND_STRUCT_RET:
603 return Attribute::StructRet;
604 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
605 return Attribute::SanitizeAddress;
606 case bitc::ATTR_KIND_SANITIZE_THREAD:
607 return Attribute::SanitizeThread;
608 case bitc::ATTR_KIND_SANITIZE_MEMORY:
609 return Attribute::SanitizeMemory;
610 case bitc::ATTR_KIND_UW_TABLE:
611 return Attribute::UWTable;
612 case bitc::ATTR_KIND_Z_EXT:
613 return Attribute::ZExt;
617 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
618 Attribute::AttrKind *Kind) {
619 *Kind = GetAttrFromCode(Code);
620 if (*Kind == Attribute::None)
621 return Error(InvalidValue);
622 return std::error_code();
625 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
626 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
627 return Error(InvalidRecord);
629 if (!MAttributeGroups.empty())
630 return Error(InvalidMultipleBlocks);
632 SmallVector<uint64_t, 64> Record;
634 // Read all the records.
636 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
638 switch (Entry.Kind) {
639 case BitstreamEntry::SubBlock: // Handled for us already.
640 case BitstreamEntry::Error:
641 return Error(MalformedBlock);
642 case BitstreamEntry::EndBlock:
643 return std::error_code();
644 case BitstreamEntry::Record:
645 // The interesting case.
651 switch (Stream.readRecord(Entry.ID, Record)) {
652 default: // Default behavior: ignore.
654 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
655 if (Record.size() < 3)
656 return Error(InvalidRecord);
658 uint64_t GrpID = Record[0];
659 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
662 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
663 if (Record[i] == 0) { // Enum attribute
664 Attribute::AttrKind Kind;
665 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
668 B.addAttribute(Kind);
669 } else if (Record[i] == 1) { // Align attribute
670 Attribute::AttrKind Kind;
671 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
673 if (Kind == Attribute::Alignment)
674 B.addAlignmentAttr(Record[++i]);
676 B.addStackAlignmentAttr(Record[++i]);
677 } else { // String attribute
678 assert((Record[i] == 3 || Record[i] == 4) &&
679 "Invalid attribute group entry");
680 bool HasValue = (Record[i++] == 4);
681 SmallString<64> KindStr;
682 SmallString<64> ValStr;
684 while (Record[i] != 0 && i != e)
685 KindStr += Record[i++];
686 assert(Record[i] == 0 && "Kind string not null terminated");
689 // Has a value associated with it.
690 ++i; // Skip the '0' that terminates the "kind" string.
691 while (Record[i] != 0 && i != e)
692 ValStr += Record[i++];
693 assert(Record[i] == 0 && "Value string not null terminated");
696 B.addAttribute(KindStr.str(), ValStr.str());
700 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
707 std::error_code BitcodeReader::ParseTypeTable() {
708 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
709 return Error(InvalidRecord);
711 return ParseTypeTableBody();
714 std::error_code BitcodeReader::ParseTypeTableBody() {
715 if (!TypeList.empty())
716 return Error(InvalidMultipleBlocks);
718 SmallVector<uint64_t, 64> Record;
719 unsigned NumRecords = 0;
721 SmallString<64> TypeName;
723 // Read all the records for this type table.
725 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
727 switch (Entry.Kind) {
728 case BitstreamEntry::SubBlock: // Handled for us already.
729 case BitstreamEntry::Error:
730 return Error(MalformedBlock);
731 case BitstreamEntry::EndBlock:
732 if (NumRecords != TypeList.size())
733 return Error(MalformedBlock);
734 return std::error_code();
735 case BitstreamEntry::Record:
736 // The interesting case.
742 Type *ResultTy = nullptr;
743 switch (Stream.readRecord(Entry.ID, Record)) {
745 return Error(InvalidValue);
746 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
747 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
748 // type list. This allows us to reserve space.
749 if (Record.size() < 1)
750 return Error(InvalidRecord);
751 TypeList.resize(Record[0]);
753 case bitc::TYPE_CODE_VOID: // VOID
754 ResultTy = Type::getVoidTy(Context);
756 case bitc::TYPE_CODE_HALF: // HALF
757 ResultTy = Type::getHalfTy(Context);
759 case bitc::TYPE_CODE_FLOAT: // FLOAT
760 ResultTy = Type::getFloatTy(Context);
762 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
763 ResultTy = Type::getDoubleTy(Context);
765 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
766 ResultTy = Type::getX86_FP80Ty(Context);
768 case bitc::TYPE_CODE_FP128: // FP128
769 ResultTy = Type::getFP128Ty(Context);
771 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
772 ResultTy = Type::getPPC_FP128Ty(Context);
774 case bitc::TYPE_CODE_LABEL: // LABEL
775 ResultTy = Type::getLabelTy(Context);
777 case bitc::TYPE_CODE_METADATA: // METADATA
778 ResultTy = Type::getMetadataTy(Context);
780 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
781 ResultTy = Type::getX86_MMXTy(Context);
783 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
784 if (Record.size() < 1)
785 return Error(InvalidRecord);
787 ResultTy = IntegerType::get(Context, Record[0]);
789 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
790 // [pointee type, address space]
791 if (Record.size() < 1)
792 return Error(InvalidRecord);
793 unsigned AddressSpace = 0;
794 if (Record.size() == 2)
795 AddressSpace = Record[1];
796 ResultTy = getTypeByID(Record[0]);
798 return Error(InvalidType);
799 ResultTy = PointerType::get(ResultTy, AddressSpace);
802 case bitc::TYPE_CODE_FUNCTION_OLD: {
803 // FIXME: attrid is dead, remove it in LLVM 4.0
804 // FUNCTION: [vararg, attrid, retty, paramty x N]
805 if (Record.size() < 3)
806 return Error(InvalidRecord);
807 SmallVector<Type*, 8> ArgTys;
808 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
809 if (Type *T = getTypeByID(Record[i]))
815 ResultTy = getTypeByID(Record[2]);
816 if (!ResultTy || ArgTys.size() < Record.size()-3)
817 return Error(InvalidType);
819 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
822 case bitc::TYPE_CODE_FUNCTION: {
823 // FUNCTION: [vararg, retty, paramty x N]
824 if (Record.size() < 2)
825 return Error(InvalidRecord);
826 SmallVector<Type*, 8> ArgTys;
827 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
828 if (Type *T = getTypeByID(Record[i]))
834 ResultTy = getTypeByID(Record[1]);
835 if (!ResultTy || ArgTys.size() < Record.size()-2)
836 return Error(InvalidType);
838 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
841 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
842 if (Record.size() < 1)
843 return Error(InvalidRecord);
844 SmallVector<Type*, 8> EltTys;
845 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
846 if (Type *T = getTypeByID(Record[i]))
851 if (EltTys.size() != Record.size()-1)
852 return Error(InvalidType);
853 ResultTy = StructType::get(Context, EltTys, Record[0]);
856 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
857 if (ConvertToString(Record, 0, TypeName))
858 return Error(InvalidRecord);
861 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
862 if (Record.size() < 1)
863 return Error(InvalidRecord);
865 if (NumRecords >= TypeList.size())
866 return Error(InvalidTYPETable);
868 // Check to see if this was forward referenced, if so fill in the temp.
869 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
871 Res->setName(TypeName);
872 TypeList[NumRecords] = nullptr;
873 } else // Otherwise, create a new struct.
874 Res = StructType::create(Context, TypeName);
877 SmallVector<Type*, 8> EltTys;
878 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
879 if (Type *T = getTypeByID(Record[i]))
884 if (EltTys.size() != Record.size()-1)
885 return Error(InvalidRecord);
886 Res->setBody(EltTys, Record[0]);
890 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
891 if (Record.size() != 1)
892 return Error(InvalidRecord);
894 if (NumRecords >= TypeList.size())
895 return Error(InvalidTYPETable);
897 // Check to see if this was forward referenced, if so fill in the temp.
898 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
900 Res->setName(TypeName);
901 TypeList[NumRecords] = nullptr;
902 } else // Otherwise, create a new struct with no body.
903 Res = StructType::create(Context, TypeName);
908 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
909 if (Record.size() < 2)
910 return Error(InvalidRecord);
911 if ((ResultTy = getTypeByID(Record[1])))
912 ResultTy = ArrayType::get(ResultTy, Record[0]);
914 return Error(InvalidType);
916 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
917 if (Record.size() < 2)
918 return Error(InvalidRecord);
919 if ((ResultTy = getTypeByID(Record[1])))
920 ResultTy = VectorType::get(ResultTy, Record[0]);
922 return Error(InvalidType);
926 if (NumRecords >= TypeList.size())
927 return Error(InvalidTYPETable);
928 assert(ResultTy && "Didn't read a type?");
929 assert(!TypeList[NumRecords] && "Already read type?");
930 TypeList[NumRecords++] = ResultTy;
934 std::error_code BitcodeReader::ParseValueSymbolTable() {
935 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
936 return Error(InvalidRecord);
938 SmallVector<uint64_t, 64> Record;
940 // Read all the records for this value table.
941 SmallString<128> ValueName;
943 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
945 switch (Entry.Kind) {
946 case BitstreamEntry::SubBlock: // Handled for us already.
947 case BitstreamEntry::Error:
948 return Error(MalformedBlock);
949 case BitstreamEntry::EndBlock:
950 return std::error_code();
951 case BitstreamEntry::Record:
952 // The interesting case.
958 switch (Stream.readRecord(Entry.ID, Record)) {
959 default: // Default behavior: unknown type.
961 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
962 if (ConvertToString(Record, 1, ValueName))
963 return Error(InvalidRecord);
964 unsigned ValueID = Record[0];
965 if (ValueID >= ValueList.size() || !ValueList[ValueID])
966 return Error(InvalidRecord);
967 Value *V = ValueList[ValueID];
969 V->setName(StringRef(ValueName.data(), ValueName.size()));
973 case bitc::VST_CODE_BBENTRY: {
974 if (ConvertToString(Record, 1, ValueName))
975 return Error(InvalidRecord);
976 BasicBlock *BB = getBasicBlock(Record[0]);
978 return Error(InvalidRecord);
980 BB->setName(StringRef(ValueName.data(), ValueName.size()));
988 std::error_code BitcodeReader::ParseMetadata() {
989 unsigned NextMDValueNo = MDValueList.size();
991 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
992 return Error(InvalidRecord);
994 SmallVector<uint64_t, 64> Record;
996 // Read all the records.
998 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1000 switch (Entry.Kind) {
1001 case BitstreamEntry::SubBlock: // Handled for us already.
1002 case BitstreamEntry::Error:
1003 return Error(MalformedBlock);
1004 case BitstreamEntry::EndBlock:
1005 return std::error_code();
1006 case BitstreamEntry::Record:
1007 // The interesting case.
1011 bool IsFunctionLocal = false;
1014 unsigned Code = Stream.readRecord(Entry.ID, Record);
1016 default: // Default behavior: ignore.
1018 case bitc::METADATA_NAME: {
1019 // Read name of the named metadata.
1020 SmallString<8> Name(Record.begin(), Record.end());
1022 Code = Stream.ReadCode();
1024 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1025 unsigned NextBitCode = Stream.readRecord(Code, Record);
1026 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1028 // Read named metadata elements.
1029 unsigned Size = Record.size();
1030 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1031 for (unsigned i = 0; i != Size; ++i) {
1032 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1034 return Error(InvalidRecord);
1035 NMD->addOperand(MD);
1039 case bitc::METADATA_FN_NODE:
1040 IsFunctionLocal = true;
1042 case bitc::METADATA_NODE: {
1043 if (Record.size() % 2 == 1)
1044 return Error(InvalidRecord);
1046 unsigned Size = Record.size();
1047 SmallVector<Value*, 8> Elts;
1048 for (unsigned i = 0; i != Size; i += 2) {
1049 Type *Ty = getTypeByID(Record[i]);
1051 return Error(InvalidRecord);
1052 if (Ty->isMetadataTy())
1053 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1054 else if (!Ty->isVoidTy())
1055 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1057 Elts.push_back(nullptr);
1059 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1060 IsFunctionLocal = false;
1061 MDValueList.AssignValue(V, NextMDValueNo++);
1064 case bitc::METADATA_STRING: {
1065 SmallString<8> String(Record.begin(), Record.end());
1066 Value *V = MDString::get(Context, String);
1067 MDValueList.AssignValue(V, NextMDValueNo++);
1070 case bitc::METADATA_KIND: {
1071 if (Record.size() < 2)
1072 return Error(InvalidRecord);
1074 unsigned Kind = Record[0];
1075 SmallString<8> Name(Record.begin()+1, Record.end());
1077 unsigned NewKind = TheModule->getMDKindID(Name.str());
1078 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1079 return Error(ConflictingMETADATA_KINDRecords);
1086 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1087 /// the LSB for dense VBR encoding.
1088 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1093 // There is no such thing as -0 with integers. "-0" really means MININT.
1097 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1098 /// values and aliases that we can.
1099 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1100 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1101 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1102 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1104 GlobalInitWorklist.swap(GlobalInits);
1105 AliasInitWorklist.swap(AliasInits);
1106 FunctionPrefixWorklist.swap(FunctionPrefixes);
1108 while (!GlobalInitWorklist.empty()) {
1109 unsigned ValID = GlobalInitWorklist.back().second;
1110 if (ValID >= ValueList.size()) {
1111 // Not ready to resolve this yet, it requires something later in the file.
1112 GlobalInits.push_back(GlobalInitWorklist.back());
1114 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1115 GlobalInitWorklist.back().first->setInitializer(C);
1117 return Error(ExpectedConstant);
1119 GlobalInitWorklist.pop_back();
1122 while (!AliasInitWorklist.empty()) {
1123 unsigned ValID = AliasInitWorklist.back().second;
1124 if (ValID >= ValueList.size()) {
1125 AliasInits.push_back(AliasInitWorklist.back());
1127 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1128 AliasInitWorklist.back().first->setAliasee(C);
1130 return Error(ExpectedConstant);
1132 AliasInitWorklist.pop_back();
1135 while (!FunctionPrefixWorklist.empty()) {
1136 unsigned ValID = FunctionPrefixWorklist.back().second;
1137 if (ValID >= ValueList.size()) {
1138 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1140 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1141 FunctionPrefixWorklist.back().first->setPrefixData(C);
1143 return Error(ExpectedConstant);
1145 FunctionPrefixWorklist.pop_back();
1148 return std::error_code();
1151 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1152 SmallVector<uint64_t, 8> Words(Vals.size());
1153 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1154 BitcodeReader::decodeSignRotatedValue);
1156 return APInt(TypeBits, Words);
1159 std::error_code BitcodeReader::ParseConstants() {
1160 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1161 return Error(InvalidRecord);
1163 SmallVector<uint64_t, 64> Record;
1165 // Read all the records for this value table.
1166 Type *CurTy = Type::getInt32Ty(Context);
1167 unsigned NextCstNo = ValueList.size();
1169 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1171 switch (Entry.Kind) {
1172 case BitstreamEntry::SubBlock: // Handled for us already.
1173 case BitstreamEntry::Error:
1174 return Error(MalformedBlock);
1175 case BitstreamEntry::EndBlock:
1176 if (NextCstNo != ValueList.size())
1177 return Error(InvalidConstantReference);
1179 // Once all the constants have been read, go through and resolve forward
1181 ValueList.ResolveConstantForwardRefs();
1182 return std::error_code();
1183 case BitstreamEntry::Record:
1184 // The interesting case.
1191 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1193 default: // Default behavior: unknown constant
1194 case bitc::CST_CODE_UNDEF: // UNDEF
1195 V = UndefValue::get(CurTy);
1197 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1199 return Error(InvalidRecord);
1200 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1201 return Error(InvalidRecord);
1202 CurTy = TypeList[Record[0]];
1203 continue; // Skip the ValueList manipulation.
1204 case bitc::CST_CODE_NULL: // NULL
1205 V = Constant::getNullValue(CurTy);
1207 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1208 if (!CurTy->isIntegerTy() || Record.empty())
1209 return Error(InvalidRecord);
1210 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1212 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1213 if (!CurTy->isIntegerTy() || Record.empty())
1214 return Error(InvalidRecord);
1216 APInt VInt = ReadWideAPInt(Record,
1217 cast<IntegerType>(CurTy)->getBitWidth());
1218 V = ConstantInt::get(Context, VInt);
1222 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1224 return Error(InvalidRecord);
1225 if (CurTy->isHalfTy())
1226 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1227 APInt(16, (uint16_t)Record[0])));
1228 else if (CurTy->isFloatTy())
1229 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1230 APInt(32, (uint32_t)Record[0])));
1231 else if (CurTy->isDoubleTy())
1232 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1233 APInt(64, Record[0])));
1234 else if (CurTy->isX86_FP80Ty()) {
1235 // Bits are not stored the same way as a normal i80 APInt, compensate.
1236 uint64_t Rearrange[2];
1237 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1238 Rearrange[1] = Record[0] >> 48;
1239 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1240 APInt(80, Rearrange)));
1241 } else if (CurTy->isFP128Ty())
1242 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1243 APInt(128, Record)));
1244 else if (CurTy->isPPC_FP128Ty())
1245 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1246 APInt(128, Record)));
1248 V = UndefValue::get(CurTy);
1252 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1254 return Error(InvalidRecord);
1256 unsigned Size = Record.size();
1257 SmallVector<Constant*, 16> Elts;
1259 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1260 for (unsigned i = 0; i != Size; ++i)
1261 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1262 STy->getElementType(i)));
1263 V = ConstantStruct::get(STy, Elts);
1264 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1265 Type *EltTy = ATy->getElementType();
1266 for (unsigned i = 0; i != Size; ++i)
1267 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1268 V = ConstantArray::get(ATy, Elts);
1269 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1270 Type *EltTy = VTy->getElementType();
1271 for (unsigned i = 0; i != Size; ++i)
1272 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1273 V = ConstantVector::get(Elts);
1275 V = UndefValue::get(CurTy);
1279 case bitc::CST_CODE_STRING: // STRING: [values]
1280 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1282 return Error(InvalidRecord);
1284 SmallString<16> Elts(Record.begin(), Record.end());
1285 V = ConstantDataArray::getString(Context, Elts,
1286 BitCode == bitc::CST_CODE_CSTRING);
1289 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1291 return Error(InvalidRecord);
1293 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1294 unsigned Size = Record.size();
1296 if (EltTy->isIntegerTy(8)) {
1297 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1298 if (isa<VectorType>(CurTy))
1299 V = ConstantDataVector::get(Context, Elts);
1301 V = ConstantDataArray::get(Context, Elts);
1302 } else if (EltTy->isIntegerTy(16)) {
1303 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1304 if (isa<VectorType>(CurTy))
1305 V = ConstantDataVector::get(Context, Elts);
1307 V = ConstantDataArray::get(Context, Elts);
1308 } else if (EltTy->isIntegerTy(32)) {
1309 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1310 if (isa<VectorType>(CurTy))
1311 V = ConstantDataVector::get(Context, Elts);
1313 V = ConstantDataArray::get(Context, Elts);
1314 } else if (EltTy->isIntegerTy(64)) {
1315 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1316 if (isa<VectorType>(CurTy))
1317 V = ConstantDataVector::get(Context, Elts);
1319 V = ConstantDataArray::get(Context, Elts);
1320 } else if (EltTy->isFloatTy()) {
1321 SmallVector<float, 16> Elts(Size);
1322 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1323 if (isa<VectorType>(CurTy))
1324 V = ConstantDataVector::get(Context, Elts);
1326 V = ConstantDataArray::get(Context, Elts);
1327 } else if (EltTy->isDoubleTy()) {
1328 SmallVector<double, 16> Elts(Size);
1329 std::transform(Record.begin(), Record.end(), Elts.begin(),
1331 if (isa<VectorType>(CurTy))
1332 V = ConstantDataVector::get(Context, Elts);
1334 V = ConstantDataArray::get(Context, Elts);
1336 return Error(InvalidTypeForValue);
1341 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1342 if (Record.size() < 3)
1343 return Error(InvalidRecord);
1344 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1346 V = UndefValue::get(CurTy); // Unknown binop.
1348 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1349 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1351 if (Record.size() >= 4) {
1352 if (Opc == Instruction::Add ||
1353 Opc == Instruction::Sub ||
1354 Opc == Instruction::Mul ||
1355 Opc == Instruction::Shl) {
1356 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1357 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1358 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1359 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1360 } else if (Opc == Instruction::SDiv ||
1361 Opc == Instruction::UDiv ||
1362 Opc == Instruction::LShr ||
1363 Opc == Instruction::AShr) {
1364 if (Record[3] & (1 << bitc::PEO_EXACT))
1365 Flags |= SDivOperator::IsExact;
1368 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1372 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1373 if (Record.size() < 3)
1374 return Error(InvalidRecord);
1375 int Opc = GetDecodedCastOpcode(Record[0]);
1377 V = UndefValue::get(CurTy); // Unknown cast.
1379 Type *OpTy = getTypeByID(Record[1]);
1381 return Error(InvalidRecord);
1382 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1383 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1384 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1388 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1389 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1390 if (Record.size() & 1)
1391 return Error(InvalidRecord);
1392 SmallVector<Constant*, 16> Elts;
1393 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1394 Type *ElTy = getTypeByID(Record[i]);
1396 return Error(InvalidRecord);
1397 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1399 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1400 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1402 bitc::CST_CODE_CE_INBOUNDS_GEP);
1405 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1406 if (Record.size() < 3)
1407 return Error(InvalidRecord);
1409 Type *SelectorTy = Type::getInt1Ty(Context);
1411 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1412 // vector. Otherwise, it must be a single bit.
1413 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1414 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1415 VTy->getNumElements());
1417 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1419 ValueList.getConstantFwdRef(Record[1],CurTy),
1420 ValueList.getConstantFwdRef(Record[2],CurTy));
1423 case bitc::CST_CODE_CE_EXTRACTELT
1424 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1425 if (Record.size() < 3)
1426 return Error(InvalidRecord);
1428 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1430 return Error(InvalidRecord);
1431 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1432 Constant *Op1 = nullptr;
1433 if (Record.size() == 4) {
1434 Type *IdxTy = getTypeByID(Record[2]);
1436 return Error(InvalidRecord);
1437 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1438 } else // TODO: Remove with llvm 4.0
1439 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1441 return Error(InvalidRecord);
1442 V = ConstantExpr::getExtractElement(Op0, Op1);
1445 case bitc::CST_CODE_CE_INSERTELT
1446 : { // CE_INSERTELT: [opval, opval, opty, opval]
1447 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1448 if (Record.size() < 3 || !OpTy)
1449 return Error(InvalidRecord);
1450 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1451 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1452 OpTy->getElementType());
1453 Constant *Op2 = nullptr;
1454 if (Record.size() == 4) {
1455 Type *IdxTy = getTypeByID(Record[2]);
1457 return Error(InvalidRecord);
1458 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1459 } else // TODO: Remove with llvm 4.0
1460 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1462 return Error(InvalidRecord);
1463 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1466 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1467 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1468 if (Record.size() < 3 || !OpTy)
1469 return Error(InvalidRecord);
1470 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1471 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1472 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1473 OpTy->getNumElements());
1474 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1475 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1478 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1479 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1481 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1482 if (Record.size() < 4 || !RTy || !OpTy)
1483 return Error(InvalidRecord);
1484 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1485 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1486 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1487 RTy->getNumElements());
1488 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1489 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1492 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1493 if (Record.size() < 4)
1494 return Error(InvalidRecord);
1495 Type *OpTy = getTypeByID(Record[0]);
1497 return Error(InvalidRecord);
1498 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1499 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1501 if (OpTy->isFPOrFPVectorTy())
1502 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1504 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1507 // This maintains backward compatibility, pre-asm dialect keywords.
1508 // FIXME: Remove with the 4.0 release.
1509 case bitc::CST_CODE_INLINEASM_OLD: {
1510 if (Record.size() < 2)
1511 return Error(InvalidRecord);
1512 std::string AsmStr, ConstrStr;
1513 bool HasSideEffects = Record[0] & 1;
1514 bool IsAlignStack = Record[0] >> 1;
1515 unsigned AsmStrSize = Record[1];
1516 if (2+AsmStrSize >= Record.size())
1517 return Error(InvalidRecord);
1518 unsigned ConstStrSize = Record[2+AsmStrSize];
1519 if (3+AsmStrSize+ConstStrSize > Record.size())
1520 return Error(InvalidRecord);
1522 for (unsigned i = 0; i != AsmStrSize; ++i)
1523 AsmStr += (char)Record[2+i];
1524 for (unsigned i = 0; i != ConstStrSize; ++i)
1525 ConstrStr += (char)Record[3+AsmStrSize+i];
1526 PointerType *PTy = cast<PointerType>(CurTy);
1527 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1528 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1531 // This version adds support for the asm dialect keywords (e.g.,
1533 case bitc::CST_CODE_INLINEASM: {
1534 if (Record.size() < 2)
1535 return Error(InvalidRecord);
1536 std::string AsmStr, ConstrStr;
1537 bool HasSideEffects = Record[0] & 1;
1538 bool IsAlignStack = (Record[0] >> 1) & 1;
1539 unsigned AsmDialect = Record[0] >> 2;
1540 unsigned AsmStrSize = Record[1];
1541 if (2+AsmStrSize >= Record.size())
1542 return Error(InvalidRecord);
1543 unsigned ConstStrSize = Record[2+AsmStrSize];
1544 if (3+AsmStrSize+ConstStrSize > Record.size())
1545 return Error(InvalidRecord);
1547 for (unsigned i = 0; i != AsmStrSize; ++i)
1548 AsmStr += (char)Record[2+i];
1549 for (unsigned i = 0; i != ConstStrSize; ++i)
1550 ConstrStr += (char)Record[3+AsmStrSize+i];
1551 PointerType *PTy = cast<PointerType>(CurTy);
1552 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1553 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1554 InlineAsm::AsmDialect(AsmDialect));
1557 case bitc::CST_CODE_BLOCKADDRESS:{
1558 if (Record.size() < 3)
1559 return Error(InvalidRecord);
1560 Type *FnTy = getTypeByID(Record[0]);
1562 return Error(InvalidRecord);
1564 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1566 return Error(InvalidRecord);
1568 // If the function is already parsed we can insert the block address right
1571 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1572 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1574 return Error(InvalidID);
1577 V = BlockAddress::get(Fn, BBI);
1579 // Otherwise insert a placeholder and remember it so it can be inserted
1580 // when the function is parsed.
1581 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1582 Type::getInt8Ty(Context),
1583 false, GlobalValue::InternalLinkage,
1585 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1592 ValueList.AssignValue(V, NextCstNo);
1597 std::error_code BitcodeReader::ParseUseLists() {
1598 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1599 return Error(InvalidRecord);
1601 SmallVector<uint64_t, 64> Record;
1603 // Read all the records.
1605 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1607 switch (Entry.Kind) {
1608 case BitstreamEntry::SubBlock: // Handled for us already.
1609 case BitstreamEntry::Error:
1610 return Error(MalformedBlock);
1611 case BitstreamEntry::EndBlock:
1612 return std::error_code();
1613 case BitstreamEntry::Record:
1614 // The interesting case.
1618 // Read a use list record.
1620 switch (Stream.readRecord(Entry.ID, Record)) {
1621 default: // Default behavior: unknown type.
1623 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1624 unsigned RecordLength = Record.size();
1625 if (RecordLength < 1)
1626 return Error(InvalidRecord);
1627 UseListRecords.push_back(Record);
1634 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1635 /// remember where it is and then skip it. This lets us lazily deserialize the
1637 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1638 // Get the function we are talking about.
1639 if (FunctionsWithBodies.empty())
1640 return Error(InsufficientFunctionProtos);
1642 Function *Fn = FunctionsWithBodies.back();
1643 FunctionsWithBodies.pop_back();
1645 // Save the current stream state.
1646 uint64_t CurBit = Stream.GetCurrentBitNo();
1647 DeferredFunctionInfo[Fn] = CurBit;
1649 // Skip over the function block for now.
1650 if (Stream.SkipBlock())
1651 return Error(InvalidRecord);
1652 return std::error_code();
1655 std::error_code BitcodeReader::GlobalCleanup() {
1656 // Patch the initializers for globals and aliases up.
1657 ResolveGlobalAndAliasInits();
1658 if (!GlobalInits.empty() || !AliasInits.empty())
1659 return Error(MalformedGlobalInitializerSet);
1661 // Look for intrinsic functions which need to be upgraded at some point
1662 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1665 if (UpgradeIntrinsicFunction(FI, NewFn))
1666 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1669 // Look for global variables which need to be renamed.
1670 for (Module::global_iterator
1671 GI = TheModule->global_begin(), GE = TheModule->global_end();
1673 GlobalVariable *GV = GI++;
1674 UpgradeGlobalVariable(GV);
1677 // Force deallocation of memory for these vectors to favor the client that
1678 // want lazy deserialization.
1679 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1680 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1681 return std::error_code();
1684 std::error_code BitcodeReader::ParseModule(bool Resume) {
1686 Stream.JumpToBit(NextUnreadBit);
1687 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1688 return Error(InvalidRecord);
1690 SmallVector<uint64_t, 64> Record;
1691 std::vector<std::string> SectionTable;
1692 std::vector<std::string> GCTable;
1694 // Read all the records for this module.
1696 BitstreamEntry Entry = Stream.advance();
1698 switch (Entry.Kind) {
1699 case BitstreamEntry::Error:
1700 return Error(MalformedBlock);
1701 case BitstreamEntry::EndBlock:
1702 return GlobalCleanup();
1704 case BitstreamEntry::SubBlock:
1706 default: // Skip unknown content.
1707 if (Stream.SkipBlock())
1708 return Error(InvalidRecord);
1710 case bitc::BLOCKINFO_BLOCK_ID:
1711 if (Stream.ReadBlockInfoBlock())
1712 return Error(MalformedBlock);
1714 case bitc::PARAMATTR_BLOCK_ID:
1715 if (std::error_code EC = ParseAttributeBlock())
1718 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1719 if (std::error_code EC = ParseAttributeGroupBlock())
1722 case bitc::TYPE_BLOCK_ID_NEW:
1723 if (std::error_code EC = ParseTypeTable())
1726 case bitc::VALUE_SYMTAB_BLOCK_ID:
1727 if (std::error_code EC = ParseValueSymbolTable())
1729 SeenValueSymbolTable = true;
1731 case bitc::CONSTANTS_BLOCK_ID:
1732 if (std::error_code EC = ParseConstants())
1734 if (std::error_code EC = ResolveGlobalAndAliasInits())
1737 case bitc::METADATA_BLOCK_ID:
1738 if (std::error_code EC = ParseMetadata())
1741 case bitc::FUNCTION_BLOCK_ID:
1742 // If this is the first function body we've seen, reverse the
1743 // FunctionsWithBodies list.
1744 if (!SeenFirstFunctionBody) {
1745 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1746 if (std::error_code EC = GlobalCleanup())
1748 SeenFirstFunctionBody = true;
1751 if (std::error_code EC = RememberAndSkipFunctionBody())
1753 // For streaming bitcode, suspend parsing when we reach the function
1754 // bodies. Subsequent materialization calls will resume it when
1755 // necessary. For streaming, the function bodies must be at the end of
1756 // the bitcode. If the bitcode file is old, the symbol table will be
1757 // at the end instead and will not have been seen yet. In this case,
1758 // just finish the parse now.
1759 if (LazyStreamer && SeenValueSymbolTable) {
1760 NextUnreadBit = Stream.GetCurrentBitNo();
1761 return std::error_code();
1764 case bitc::USELIST_BLOCK_ID:
1765 if (std::error_code EC = ParseUseLists())
1771 case BitstreamEntry::Record:
1772 // The interesting case.
1778 switch (Stream.readRecord(Entry.ID, Record)) {
1779 default: break; // Default behavior, ignore unknown content.
1780 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1781 if (Record.size() < 1)
1782 return Error(InvalidRecord);
1783 // Only version #0 and #1 are supported so far.
1784 unsigned module_version = Record[0];
1785 switch (module_version) {
1787 return Error(InvalidValue);
1789 UseRelativeIDs = false;
1792 UseRelativeIDs = true;
1797 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1799 if (ConvertToString(Record, 0, S))
1800 return Error(InvalidRecord);
1801 TheModule->setTargetTriple(S);
1804 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1806 if (ConvertToString(Record, 0, S))
1807 return Error(InvalidRecord);
1808 TheModule->setDataLayout(S);
1811 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1813 if (ConvertToString(Record, 0, S))
1814 return Error(InvalidRecord);
1815 TheModule->setModuleInlineAsm(S);
1818 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1819 // FIXME: Remove in 4.0.
1821 if (ConvertToString(Record, 0, S))
1822 return Error(InvalidRecord);
1826 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1828 if (ConvertToString(Record, 0, S))
1829 return Error(InvalidRecord);
1830 SectionTable.push_back(S);
1833 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1835 if (ConvertToString(Record, 0, S))
1836 return Error(InvalidRecord);
1837 GCTable.push_back(S);
1840 // GLOBALVAR: [pointer type, isconst, initid,
1841 // linkage, alignment, section, visibility, threadlocal,
1842 // unnamed_addr, dllstorageclass]
1843 case bitc::MODULE_CODE_GLOBALVAR: {
1844 if (Record.size() < 6)
1845 return Error(InvalidRecord);
1846 Type *Ty = getTypeByID(Record[0]);
1848 return Error(InvalidRecord);
1849 if (!Ty->isPointerTy())
1850 return Error(InvalidTypeForValue);
1851 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1852 Ty = cast<PointerType>(Ty)->getElementType();
1854 bool isConstant = Record[1];
1855 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1856 unsigned Alignment = (1 << Record[4]) >> 1;
1857 std::string Section;
1859 if (Record[5]-1 >= SectionTable.size())
1860 return Error(InvalidID);
1861 Section = SectionTable[Record[5]-1];
1863 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1864 // Local linkage must have default visibility.
1865 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1866 // FIXME: Change to an error if non-default in 4.0.
1867 Visibility = GetDecodedVisibility(Record[6]);
1869 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1870 if (Record.size() > 7)
1871 TLM = GetDecodedThreadLocalMode(Record[7]);
1873 bool UnnamedAddr = false;
1874 if (Record.size() > 8)
1875 UnnamedAddr = Record[8];
1877 bool ExternallyInitialized = false;
1878 if (Record.size() > 9)
1879 ExternallyInitialized = Record[9];
1881 GlobalVariable *NewGV =
1882 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1883 TLM, AddressSpace, ExternallyInitialized);
1884 NewGV->setAlignment(Alignment);
1885 if (!Section.empty())
1886 NewGV->setSection(Section);
1887 NewGV->setVisibility(Visibility);
1888 NewGV->setUnnamedAddr(UnnamedAddr);
1890 if (Record.size() > 10)
1891 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1893 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1895 ValueList.push_back(NewGV);
1897 // Remember which value to use for the global initializer.
1898 if (unsigned InitID = Record[2])
1899 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1902 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1903 // alignment, section, visibility, gc, unnamed_addr,
1905 case bitc::MODULE_CODE_FUNCTION: {
1906 if (Record.size() < 8)
1907 return Error(InvalidRecord);
1908 Type *Ty = getTypeByID(Record[0]);
1910 return Error(InvalidRecord);
1911 if (!Ty->isPointerTy())
1912 return Error(InvalidTypeForValue);
1914 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1916 return Error(InvalidTypeForValue);
1918 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1921 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1922 bool isProto = Record[2];
1923 Func->setLinkage(GetDecodedLinkage(Record[3]));
1924 Func->setAttributes(getAttributes(Record[4]));
1926 Func->setAlignment((1 << Record[5]) >> 1);
1928 if (Record[6]-1 >= SectionTable.size())
1929 return Error(InvalidID);
1930 Func->setSection(SectionTable[Record[6]-1]);
1932 // Local linkage must have default visibility.
1933 if (!Func->hasLocalLinkage())
1934 // FIXME: Change to an error if non-default in 4.0.
1935 Func->setVisibility(GetDecodedVisibility(Record[7]));
1936 if (Record.size() > 8 && Record[8]) {
1937 if (Record[8]-1 > GCTable.size())
1938 return Error(InvalidID);
1939 Func->setGC(GCTable[Record[8]-1].c_str());
1941 bool UnnamedAddr = false;
1942 if (Record.size() > 9)
1943 UnnamedAddr = Record[9];
1944 Func->setUnnamedAddr(UnnamedAddr);
1945 if (Record.size() > 10 && Record[10] != 0)
1946 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1948 if (Record.size() > 11)
1949 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1951 UpgradeDLLImportExportLinkage(Func, Record[3]);
1953 ValueList.push_back(Func);
1955 // If this is a function with a body, remember the prototype we are
1956 // creating now, so that we can match up the body with them later.
1958 FunctionsWithBodies.push_back(Func);
1959 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1963 // ALIAS: [alias type, aliasee val#, linkage]
1964 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
1965 case bitc::MODULE_CODE_ALIAS: {
1966 if (Record.size() < 3)
1967 return Error(InvalidRecord);
1968 Type *Ty = getTypeByID(Record[0]);
1970 return Error(InvalidRecord);
1971 auto *PTy = dyn_cast<PointerType>(Ty);
1973 return Error(InvalidTypeForValue);
1976 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1977 GetDecodedLinkage(Record[2]), "", TheModule);
1978 // Old bitcode files didn't have visibility field.
1979 // Local linkage must have default visibility.
1980 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
1981 // FIXME: Change to an error if non-default in 4.0.
1982 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1983 if (Record.size() > 4)
1984 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
1986 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
1987 if (Record.size() > 5)
1988 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
1989 if (Record.size() > 6)
1990 NewGA->setUnnamedAddr(Record[6]);
1991 ValueList.push_back(NewGA);
1992 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1995 /// MODULE_CODE_PURGEVALS: [numvals]
1996 case bitc::MODULE_CODE_PURGEVALS:
1997 // Trim down the value list to the specified size.
1998 if (Record.size() < 1 || Record[0] > ValueList.size())
1999 return Error(InvalidRecord);
2000 ValueList.shrinkTo(Record[0]);
2007 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2008 TheModule = nullptr;
2010 if (std::error_code EC = InitStream())
2013 // Sniff for the signature.
2014 if (Stream.Read(8) != 'B' ||
2015 Stream.Read(8) != 'C' ||
2016 Stream.Read(4) != 0x0 ||
2017 Stream.Read(4) != 0xC ||
2018 Stream.Read(4) != 0xE ||
2019 Stream.Read(4) != 0xD)
2020 return Error(InvalidBitcodeSignature);
2022 // We expect a number of well-defined blocks, though we don't necessarily
2023 // need to understand them all.
2025 if (Stream.AtEndOfStream())
2026 return std::error_code();
2028 BitstreamEntry Entry =
2029 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2031 switch (Entry.Kind) {
2032 case BitstreamEntry::Error:
2033 return Error(MalformedBlock);
2034 case BitstreamEntry::EndBlock:
2035 return std::error_code();
2037 case BitstreamEntry::SubBlock:
2039 case bitc::BLOCKINFO_BLOCK_ID:
2040 if (Stream.ReadBlockInfoBlock())
2041 return Error(MalformedBlock);
2043 case bitc::MODULE_BLOCK_ID:
2044 // Reject multiple MODULE_BLOCK's in a single bitstream.
2046 return Error(InvalidMultipleBlocks);
2048 if (std::error_code EC = ParseModule(false))
2051 return std::error_code();
2054 if (Stream.SkipBlock())
2055 return Error(InvalidRecord);
2059 case BitstreamEntry::Record:
2060 // There should be no records in the top-level of blocks.
2062 // The ranlib in Xcode 4 will align archive members by appending newlines
2063 // to the end of them. If this file size is a multiple of 4 but not 8, we
2064 // have to read and ignore these final 4 bytes :-(
2065 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2066 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2067 Stream.AtEndOfStream())
2068 return std::error_code();
2070 return Error(InvalidRecord);
2075 std::error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2076 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2077 return Error(InvalidRecord);
2079 SmallVector<uint64_t, 64> Record;
2081 // Read all the records for this module.
2083 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2085 switch (Entry.Kind) {
2086 case BitstreamEntry::SubBlock: // Handled for us already.
2087 case BitstreamEntry::Error:
2088 return Error(MalformedBlock);
2089 case BitstreamEntry::EndBlock:
2090 return std::error_code();
2091 case BitstreamEntry::Record:
2092 // The interesting case.
2097 switch (Stream.readRecord(Entry.ID, Record)) {
2098 default: break; // Default behavior, ignore unknown content.
2099 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2101 if (ConvertToString(Record, 0, S))
2102 return Error(InvalidRecord);
2111 std::error_code BitcodeReader::ParseTriple(std::string &Triple) {
2112 if (std::error_code EC = InitStream())
2115 // Sniff for the signature.
2116 if (Stream.Read(8) != 'B' ||
2117 Stream.Read(8) != 'C' ||
2118 Stream.Read(4) != 0x0 ||
2119 Stream.Read(4) != 0xC ||
2120 Stream.Read(4) != 0xE ||
2121 Stream.Read(4) != 0xD)
2122 return Error(InvalidBitcodeSignature);
2124 // We expect a number of well-defined blocks, though we don't necessarily
2125 // need to understand them all.
2127 BitstreamEntry Entry = Stream.advance();
2129 switch (Entry.Kind) {
2130 case BitstreamEntry::Error:
2131 return Error(MalformedBlock);
2132 case BitstreamEntry::EndBlock:
2133 return std::error_code();
2135 case BitstreamEntry::SubBlock:
2136 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2137 return ParseModuleTriple(Triple);
2139 // Ignore other sub-blocks.
2140 if (Stream.SkipBlock())
2141 return Error(MalformedBlock);
2144 case BitstreamEntry::Record:
2145 Stream.skipRecord(Entry.ID);
2151 /// ParseMetadataAttachment - Parse metadata attachments.
2152 std::error_code BitcodeReader::ParseMetadataAttachment() {
2153 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2154 return Error(InvalidRecord);
2156 SmallVector<uint64_t, 64> Record;
2158 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2160 switch (Entry.Kind) {
2161 case BitstreamEntry::SubBlock: // Handled for us already.
2162 case BitstreamEntry::Error:
2163 return Error(MalformedBlock);
2164 case BitstreamEntry::EndBlock:
2165 return std::error_code();
2166 case BitstreamEntry::Record:
2167 // The interesting case.
2171 // Read a metadata attachment record.
2173 switch (Stream.readRecord(Entry.ID, Record)) {
2174 default: // Default behavior: ignore.
2176 case bitc::METADATA_ATTACHMENT: {
2177 unsigned RecordLength = Record.size();
2178 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2179 return Error(InvalidRecord);
2180 Instruction *Inst = InstructionList[Record[0]];
2181 for (unsigned i = 1; i != RecordLength; i = i+2) {
2182 unsigned Kind = Record[i];
2183 DenseMap<unsigned, unsigned>::iterator I =
2184 MDKindMap.find(Kind);
2185 if (I == MDKindMap.end())
2186 return Error(InvalidID);
2187 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2188 Inst->setMetadata(I->second, cast<MDNode>(Node));
2189 if (I->second == LLVMContext::MD_tbaa)
2190 InstsWithTBAATag.push_back(Inst);
2198 /// ParseFunctionBody - Lazily parse the specified function body block.
2199 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2200 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2201 return Error(InvalidRecord);
2203 InstructionList.clear();
2204 unsigned ModuleValueListSize = ValueList.size();
2205 unsigned ModuleMDValueListSize = MDValueList.size();
2207 // Add all the function arguments to the value table.
2208 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2209 ValueList.push_back(I);
2211 unsigned NextValueNo = ValueList.size();
2212 BasicBlock *CurBB = nullptr;
2213 unsigned CurBBNo = 0;
2217 // Read all the records.
2218 SmallVector<uint64_t, 64> Record;
2220 BitstreamEntry Entry = Stream.advance();
2222 switch (Entry.Kind) {
2223 case BitstreamEntry::Error:
2224 return Error(MalformedBlock);
2225 case BitstreamEntry::EndBlock:
2226 goto OutOfRecordLoop;
2228 case BitstreamEntry::SubBlock:
2230 default: // Skip unknown content.
2231 if (Stream.SkipBlock())
2232 return Error(InvalidRecord);
2234 case bitc::CONSTANTS_BLOCK_ID:
2235 if (std::error_code EC = ParseConstants())
2237 NextValueNo = ValueList.size();
2239 case bitc::VALUE_SYMTAB_BLOCK_ID:
2240 if (std::error_code EC = ParseValueSymbolTable())
2243 case bitc::METADATA_ATTACHMENT_ID:
2244 if (std::error_code EC = ParseMetadataAttachment())
2247 case bitc::METADATA_BLOCK_ID:
2248 if (std::error_code EC = ParseMetadata())
2254 case BitstreamEntry::Record:
2255 // The interesting case.
2261 Instruction *I = nullptr;
2262 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2264 default: // Default behavior: reject
2265 return Error(InvalidValue);
2266 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2267 if (Record.size() < 1 || Record[0] == 0)
2268 return Error(InvalidRecord);
2269 // Create all the basic blocks for the function.
2270 FunctionBBs.resize(Record[0]);
2271 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2272 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2273 CurBB = FunctionBBs[0];
2276 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2277 // This record indicates that the last instruction is at the same
2278 // location as the previous instruction with a location.
2281 // Get the last instruction emitted.
2282 if (CurBB && !CurBB->empty())
2284 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2285 !FunctionBBs[CurBBNo-1]->empty())
2286 I = &FunctionBBs[CurBBNo-1]->back();
2289 return Error(InvalidRecord);
2290 I->setDebugLoc(LastLoc);
2294 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2295 I = nullptr; // Get the last instruction emitted.
2296 if (CurBB && !CurBB->empty())
2298 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2299 !FunctionBBs[CurBBNo-1]->empty())
2300 I = &FunctionBBs[CurBBNo-1]->back();
2301 if (!I || Record.size() < 4)
2302 return Error(InvalidRecord);
2304 unsigned Line = Record[0], Col = Record[1];
2305 unsigned ScopeID = Record[2], IAID = Record[3];
2307 MDNode *Scope = nullptr, *IA = nullptr;
2308 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2309 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2310 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2311 I->setDebugLoc(LastLoc);
2316 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2319 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2320 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2321 OpNum+1 > Record.size())
2322 return Error(InvalidRecord);
2324 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2326 return Error(InvalidRecord);
2327 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2328 InstructionList.push_back(I);
2329 if (OpNum < Record.size()) {
2330 if (Opc == Instruction::Add ||
2331 Opc == Instruction::Sub ||
2332 Opc == Instruction::Mul ||
2333 Opc == Instruction::Shl) {
2334 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2335 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2336 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2337 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2338 } else if (Opc == Instruction::SDiv ||
2339 Opc == Instruction::UDiv ||
2340 Opc == Instruction::LShr ||
2341 Opc == Instruction::AShr) {
2342 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2343 cast<BinaryOperator>(I)->setIsExact(true);
2344 } else if (isa<FPMathOperator>(I)) {
2346 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2347 FMF.setUnsafeAlgebra();
2348 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2350 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2352 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2353 FMF.setNoSignedZeros();
2354 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2355 FMF.setAllowReciprocal();
2357 I->setFastMathFlags(FMF);
2363 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2366 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2367 OpNum+2 != Record.size())
2368 return Error(InvalidRecord);
2370 Type *ResTy = getTypeByID(Record[OpNum]);
2371 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2372 if (Opc == -1 || !ResTy)
2373 return Error(InvalidRecord);
2374 Instruction *Temp = nullptr;
2375 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2377 InstructionList.push_back(Temp);
2378 CurBB->getInstList().push_back(Temp);
2381 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2383 InstructionList.push_back(I);
2386 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2387 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2390 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2391 return Error(InvalidRecord);
2393 SmallVector<Value*, 16> GEPIdx;
2394 while (OpNum != Record.size()) {
2396 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2397 return Error(InvalidRecord);
2398 GEPIdx.push_back(Op);
2401 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2402 InstructionList.push_back(I);
2403 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2404 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2408 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2409 // EXTRACTVAL: [opty, opval, n x indices]
2412 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2413 return Error(InvalidRecord);
2415 SmallVector<unsigned, 4> EXTRACTVALIdx;
2416 for (unsigned RecSize = Record.size();
2417 OpNum != RecSize; ++OpNum) {
2418 uint64_t Index = Record[OpNum];
2419 if ((unsigned)Index != Index)
2420 return Error(InvalidValue);
2421 EXTRACTVALIdx.push_back((unsigned)Index);
2424 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2425 InstructionList.push_back(I);
2429 case bitc::FUNC_CODE_INST_INSERTVAL: {
2430 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2433 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2434 return Error(InvalidRecord);
2436 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2437 return Error(InvalidRecord);
2439 SmallVector<unsigned, 4> INSERTVALIdx;
2440 for (unsigned RecSize = Record.size();
2441 OpNum != RecSize; ++OpNum) {
2442 uint64_t Index = Record[OpNum];
2443 if ((unsigned)Index != Index)
2444 return Error(InvalidValue);
2445 INSERTVALIdx.push_back((unsigned)Index);
2448 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2449 InstructionList.push_back(I);
2453 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2454 // obsolete form of select
2455 // handles select i1 ... in old bitcode
2457 Value *TrueVal, *FalseVal, *Cond;
2458 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2459 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2460 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2461 return Error(InvalidRecord);
2463 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2464 InstructionList.push_back(I);
2468 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2469 // new form of select
2470 // handles select i1 or select [N x i1]
2472 Value *TrueVal, *FalseVal, *Cond;
2473 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2474 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2475 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2476 return Error(InvalidRecord);
2478 // select condition can be either i1 or [N x i1]
2479 if (VectorType* vector_type =
2480 dyn_cast<VectorType>(Cond->getType())) {
2482 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2483 return Error(InvalidTypeForValue);
2486 if (Cond->getType() != Type::getInt1Ty(Context))
2487 return Error(InvalidTypeForValue);
2490 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2491 InstructionList.push_back(I);
2495 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2498 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2499 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2500 return Error(InvalidRecord);
2501 I = ExtractElementInst::Create(Vec, Idx);
2502 InstructionList.push_back(I);
2506 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2508 Value *Vec, *Elt, *Idx;
2509 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2510 popValue(Record, OpNum, NextValueNo,
2511 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2512 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2513 return Error(InvalidRecord);
2514 I = InsertElementInst::Create(Vec, Elt, Idx);
2515 InstructionList.push_back(I);
2519 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2521 Value *Vec1, *Vec2, *Mask;
2522 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2523 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2524 return Error(InvalidRecord);
2526 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2527 return Error(InvalidRecord);
2528 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2529 InstructionList.push_back(I);
2533 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2534 // Old form of ICmp/FCmp returning bool
2535 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2536 // both legal on vectors but had different behaviour.
2537 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2538 // FCmp/ICmp returning bool or vector of bool
2542 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2543 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2544 OpNum+1 != Record.size())
2545 return Error(InvalidRecord);
2547 if (LHS->getType()->isFPOrFPVectorTy())
2548 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2550 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2551 InstructionList.push_back(I);
2555 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2557 unsigned Size = Record.size();
2559 I = ReturnInst::Create(Context);
2560 InstructionList.push_back(I);
2565 Value *Op = nullptr;
2566 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2567 return Error(InvalidRecord);
2568 if (OpNum != Record.size())
2569 return Error(InvalidRecord);
2571 I = ReturnInst::Create(Context, Op);
2572 InstructionList.push_back(I);
2575 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2576 if (Record.size() != 1 && Record.size() != 3)
2577 return Error(InvalidRecord);
2578 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2580 return Error(InvalidRecord);
2582 if (Record.size() == 1) {
2583 I = BranchInst::Create(TrueDest);
2584 InstructionList.push_back(I);
2587 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2588 Value *Cond = getValue(Record, 2, NextValueNo,
2589 Type::getInt1Ty(Context));
2590 if (!FalseDest || !Cond)
2591 return Error(InvalidRecord);
2592 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2593 InstructionList.push_back(I);
2597 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2599 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2600 // "New" SwitchInst format with case ranges. The changes to write this
2601 // format were reverted but we still recognize bitcode that uses it.
2602 // Hopefully someday we will have support for case ranges and can use
2603 // this format again.
2605 Type *OpTy = getTypeByID(Record[1]);
2606 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2608 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2609 BasicBlock *Default = getBasicBlock(Record[3]);
2610 if (!OpTy || !Cond || !Default)
2611 return Error(InvalidRecord);
2613 unsigned NumCases = Record[4];
2615 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2616 InstructionList.push_back(SI);
2618 unsigned CurIdx = 5;
2619 for (unsigned i = 0; i != NumCases; ++i) {
2620 SmallVector<ConstantInt*, 1> CaseVals;
2621 unsigned NumItems = Record[CurIdx++];
2622 for (unsigned ci = 0; ci != NumItems; ++ci) {
2623 bool isSingleNumber = Record[CurIdx++];
2626 unsigned ActiveWords = 1;
2627 if (ValueBitWidth > 64)
2628 ActiveWords = Record[CurIdx++];
2629 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2631 CurIdx += ActiveWords;
2633 if (!isSingleNumber) {
2635 if (ValueBitWidth > 64)
2636 ActiveWords = Record[CurIdx++];
2638 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2640 CurIdx += ActiveWords;
2642 // FIXME: It is not clear whether values in the range should be
2643 // compared as signed or unsigned values. The partially
2644 // implemented changes that used this format in the past used
2645 // unsigned comparisons.
2646 for ( ; Low.ule(High); ++Low)
2647 CaseVals.push_back(ConstantInt::get(Context, Low));
2649 CaseVals.push_back(ConstantInt::get(Context, Low));
2651 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2652 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2653 cve = CaseVals.end(); cvi != cve; ++cvi)
2654 SI->addCase(*cvi, DestBB);
2660 // Old SwitchInst format without case ranges.
2662 if (Record.size() < 3 || (Record.size() & 1) == 0)
2663 return Error(InvalidRecord);
2664 Type *OpTy = getTypeByID(Record[0]);
2665 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2666 BasicBlock *Default = getBasicBlock(Record[2]);
2667 if (!OpTy || !Cond || !Default)
2668 return Error(InvalidRecord);
2669 unsigned NumCases = (Record.size()-3)/2;
2670 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2671 InstructionList.push_back(SI);
2672 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2673 ConstantInt *CaseVal =
2674 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2675 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2676 if (!CaseVal || !DestBB) {
2678 return Error(InvalidRecord);
2680 SI->addCase(CaseVal, DestBB);
2685 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2686 if (Record.size() < 2)
2687 return Error(InvalidRecord);
2688 Type *OpTy = getTypeByID(Record[0]);
2689 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2690 if (!OpTy || !Address)
2691 return Error(InvalidRecord);
2692 unsigned NumDests = Record.size()-2;
2693 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2694 InstructionList.push_back(IBI);
2695 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2696 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2697 IBI->addDestination(DestBB);
2700 return Error(InvalidRecord);
2707 case bitc::FUNC_CODE_INST_INVOKE: {
2708 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2709 if (Record.size() < 4)
2710 return Error(InvalidRecord);
2711 AttributeSet PAL = getAttributes(Record[0]);
2712 unsigned CCInfo = Record[1];
2713 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2714 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2718 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2719 return Error(InvalidRecord);
2721 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2722 FunctionType *FTy = !CalleeTy ? nullptr :
2723 dyn_cast<FunctionType>(CalleeTy->getElementType());
2725 // Check that the right number of fixed parameters are here.
2726 if (!FTy || !NormalBB || !UnwindBB ||
2727 Record.size() < OpNum+FTy->getNumParams())
2728 return Error(InvalidRecord);
2730 SmallVector<Value*, 16> Ops;
2731 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2732 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2733 FTy->getParamType(i)));
2735 return Error(InvalidRecord);
2738 if (!FTy->isVarArg()) {
2739 if (Record.size() != OpNum)
2740 return Error(InvalidRecord);
2742 // Read type/value pairs for varargs params.
2743 while (OpNum != Record.size()) {
2745 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2746 return Error(InvalidRecord);
2751 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2752 InstructionList.push_back(I);
2753 cast<InvokeInst>(I)->setCallingConv(
2754 static_cast<CallingConv::ID>(CCInfo));
2755 cast<InvokeInst>(I)->setAttributes(PAL);
2758 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2760 Value *Val = nullptr;
2761 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2762 return Error(InvalidRecord);
2763 I = ResumeInst::Create(Val);
2764 InstructionList.push_back(I);
2767 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2768 I = new UnreachableInst(Context);
2769 InstructionList.push_back(I);
2771 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2772 if (Record.size() < 1 || ((Record.size()-1)&1))
2773 return Error(InvalidRecord);
2774 Type *Ty = getTypeByID(Record[0]);
2776 return Error(InvalidRecord);
2778 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2779 InstructionList.push_back(PN);
2781 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2783 // With the new function encoding, it is possible that operands have
2784 // negative IDs (for forward references). Use a signed VBR
2785 // representation to keep the encoding small.
2787 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2789 V = getValue(Record, 1+i, NextValueNo, Ty);
2790 BasicBlock *BB = getBasicBlock(Record[2+i]);
2792 return Error(InvalidRecord);
2793 PN->addIncoming(V, BB);
2799 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2800 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2802 if (Record.size() < 4)
2803 return Error(InvalidRecord);
2804 Type *Ty = getTypeByID(Record[Idx++]);
2806 return Error(InvalidRecord);
2807 Value *PersFn = nullptr;
2808 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2809 return Error(InvalidRecord);
2811 bool IsCleanup = !!Record[Idx++];
2812 unsigned NumClauses = Record[Idx++];
2813 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2814 LP->setCleanup(IsCleanup);
2815 for (unsigned J = 0; J != NumClauses; ++J) {
2816 LandingPadInst::ClauseType CT =
2817 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2820 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2822 return Error(InvalidRecord);
2825 assert((CT != LandingPadInst::Catch ||
2826 !isa<ArrayType>(Val->getType())) &&
2827 "Catch clause has a invalid type!");
2828 assert((CT != LandingPadInst::Filter ||
2829 isa<ArrayType>(Val->getType())) &&
2830 "Filter clause has invalid type!");
2831 LP->addClause(cast<Constant>(Val));
2835 InstructionList.push_back(I);
2839 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2840 if (Record.size() != 4)
2841 return Error(InvalidRecord);
2843 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2844 Type *OpTy = getTypeByID(Record[1]);
2845 Value *Size = getFnValueByID(Record[2], OpTy);
2846 unsigned Align = Record[3];
2848 return Error(InvalidRecord);
2849 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2850 InstructionList.push_back(I);
2853 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2856 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2857 OpNum+2 != Record.size())
2858 return Error(InvalidRecord);
2860 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2861 InstructionList.push_back(I);
2864 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2865 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2868 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2869 OpNum+4 != Record.size())
2870 return Error(InvalidRecord);
2873 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2874 if (Ordering == NotAtomic || Ordering == Release ||
2875 Ordering == AcquireRelease)
2876 return Error(InvalidRecord);
2877 if (Ordering != NotAtomic && Record[OpNum] == 0)
2878 return Error(InvalidRecord);
2879 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2881 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2882 Ordering, SynchScope);
2883 InstructionList.push_back(I);
2886 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2889 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2890 popValue(Record, OpNum, NextValueNo,
2891 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2892 OpNum+2 != Record.size())
2893 return Error(InvalidRecord);
2895 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2896 InstructionList.push_back(I);
2899 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2900 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2903 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2904 popValue(Record, OpNum, NextValueNo,
2905 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2906 OpNum+4 != Record.size())
2907 return Error(InvalidRecord);
2909 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2910 if (Ordering == NotAtomic || Ordering == Acquire ||
2911 Ordering == AcquireRelease)
2912 return Error(InvalidRecord);
2913 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2914 if (Ordering != NotAtomic && Record[OpNum] == 0)
2915 return Error(InvalidRecord);
2917 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2918 Ordering, SynchScope);
2919 InstructionList.push_back(I);
2922 case bitc::FUNC_CODE_INST_CMPXCHG: {
2923 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
2924 // failureordering?, isweak?]
2926 Value *Ptr, *Cmp, *New;
2927 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2928 popValue(Record, OpNum, NextValueNo,
2929 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2930 popValue(Record, OpNum, NextValueNo,
2931 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2932 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
2933 return Error(InvalidRecord);
2934 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
2935 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
2936 return Error(InvalidRecord);
2937 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2939 AtomicOrdering FailureOrdering;
2940 if (Record.size() < 7)
2942 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
2944 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
2946 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
2948 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2950 if (Record.size() < 8) {
2951 // Before weak cmpxchgs existed, the instruction simply returned the
2952 // value loaded from memory, so bitcode files from that era will be
2953 // expecting the first component of a modern cmpxchg.
2954 CurBB->getInstList().push_back(I);
2955 I = ExtractValueInst::Create(I, 0);
2957 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
2960 InstructionList.push_back(I);
2963 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2964 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2967 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2968 popValue(Record, OpNum, NextValueNo,
2969 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2970 OpNum+4 != Record.size())
2971 return Error(InvalidRecord);
2972 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2973 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2974 Operation > AtomicRMWInst::LAST_BINOP)
2975 return Error(InvalidRecord);
2976 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2977 if (Ordering == NotAtomic || Ordering == Unordered)
2978 return Error(InvalidRecord);
2979 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2980 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2981 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2982 InstructionList.push_back(I);
2985 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2986 if (2 != Record.size())
2987 return Error(InvalidRecord);
2988 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2989 if (Ordering == NotAtomic || Ordering == Unordered ||
2990 Ordering == Monotonic)
2991 return Error(InvalidRecord);
2992 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2993 I = new FenceInst(Context, Ordering, SynchScope);
2994 InstructionList.push_back(I);
2997 case bitc::FUNC_CODE_INST_CALL: {
2998 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2999 if (Record.size() < 3)
3000 return Error(InvalidRecord);
3002 AttributeSet PAL = getAttributes(Record[0]);
3003 unsigned CCInfo = Record[1];
3007 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3008 return Error(InvalidRecord);
3010 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3011 FunctionType *FTy = nullptr;
3012 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3013 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3014 return Error(InvalidRecord);
3016 SmallVector<Value*, 16> Args;
3017 // Read the fixed params.
3018 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3019 if (FTy->getParamType(i)->isLabelTy())
3020 Args.push_back(getBasicBlock(Record[OpNum]));
3022 Args.push_back(getValue(Record, OpNum, NextValueNo,
3023 FTy->getParamType(i)));
3025 return Error(InvalidRecord);
3028 // Read type/value pairs for varargs params.
3029 if (!FTy->isVarArg()) {
3030 if (OpNum != Record.size())
3031 return Error(InvalidRecord);
3033 while (OpNum != Record.size()) {
3035 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3036 return Error(InvalidRecord);
3041 I = CallInst::Create(Callee, Args);
3042 InstructionList.push_back(I);
3043 cast<CallInst>(I)->setCallingConv(
3044 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3045 CallInst::TailCallKind TCK = CallInst::TCK_None;
3047 TCK = CallInst::TCK_Tail;
3048 if (CCInfo & (1 << 14))
3049 TCK = CallInst::TCK_MustTail;
3050 cast<CallInst>(I)->setTailCallKind(TCK);
3051 cast<CallInst>(I)->setAttributes(PAL);
3054 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3055 if (Record.size() < 3)
3056 return Error(InvalidRecord);
3057 Type *OpTy = getTypeByID(Record[0]);
3058 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3059 Type *ResTy = getTypeByID(Record[2]);
3060 if (!OpTy || !Op || !ResTy)
3061 return Error(InvalidRecord);
3062 I = new VAArgInst(Op, ResTy);
3063 InstructionList.push_back(I);
3068 // Add instruction to end of current BB. If there is no current BB, reject
3072 return Error(InvalidInstructionWithNoBB);
3074 CurBB->getInstList().push_back(I);
3076 // If this was a terminator instruction, move to the next block.
3077 if (isa<TerminatorInst>(I)) {
3079 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3082 // Non-void values get registered in the value table for future use.
3083 if (I && !I->getType()->isVoidTy())
3084 ValueList.AssignValue(I, NextValueNo++);
3089 // Check the function list for unresolved values.
3090 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3091 if (!A->getParent()) {
3092 // We found at least one unresolved value. Nuke them all to avoid leaks.
3093 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3094 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3095 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3099 return Error(NeverResolvedValueFoundInFunction);
3103 // FIXME: Check for unresolved forward-declared metadata references
3104 // and clean up leaks.
3106 // See if anything took the address of blocks in this function. If so,
3107 // resolve them now.
3108 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3109 BlockAddrFwdRefs.find(F);
3110 if (BAFRI != BlockAddrFwdRefs.end()) {
3111 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3112 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3113 unsigned BlockIdx = RefList[i].first;
3114 if (BlockIdx >= FunctionBBs.size())
3115 return Error(InvalidID);
3117 GlobalVariable *FwdRef = RefList[i].second;
3118 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3119 FwdRef->eraseFromParent();
3122 BlockAddrFwdRefs.erase(BAFRI);
3125 // Trim the value list down to the size it was before we parsed this function.
3126 ValueList.shrinkTo(ModuleValueListSize);
3127 MDValueList.shrinkTo(ModuleMDValueListSize);
3128 std::vector<BasicBlock*>().swap(FunctionBBs);
3129 return std::error_code();
3132 /// Find the function body in the bitcode stream
3133 std::error_code BitcodeReader::FindFunctionInStream(
3135 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3136 while (DeferredFunctionInfoIterator->second == 0) {
3137 if (Stream.AtEndOfStream())
3138 return Error(CouldNotFindFunctionInStream);
3139 // ParseModule will parse the next body in the stream and set its
3140 // position in the DeferredFunctionInfo map.
3141 if (std::error_code EC = ParseModule(true))
3144 return std::error_code();
3147 //===----------------------------------------------------------------------===//
3148 // GVMaterializer implementation
3149 //===----------------------------------------------------------------------===//
3151 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3153 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3154 if (const Function *F = dyn_cast<Function>(GV)) {
3155 return F->isDeclaration() &&
3156 DeferredFunctionInfo.count(const_cast<Function*>(F));
3161 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
3162 Function *F = dyn_cast<Function>(GV);
3163 // If it's not a function or is already material, ignore the request.
3164 if (!F || !F->isMaterializable())
3165 return std::error_code();
3167 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3168 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3169 // If its position is recorded as 0, its body is somewhere in the stream
3170 // but we haven't seen it yet.
3171 if (DFII->second == 0 && LazyStreamer)
3172 if (std::error_code EC = FindFunctionInStream(F, DFII))
3175 // Move the bit stream to the saved position of the deferred function body.
3176 Stream.JumpToBit(DFII->second);
3178 if (std::error_code EC = ParseFunctionBody(F))
3181 // Upgrade any old intrinsic calls in the function.
3182 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3183 E = UpgradedIntrinsics.end(); I != E; ++I) {
3184 if (I->first != I->second) {
3185 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3187 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3188 UpgradeIntrinsicCall(CI, I->second);
3193 return std::error_code();
3196 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3197 const Function *F = dyn_cast<Function>(GV);
3198 if (!F || F->isDeclaration())
3200 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3203 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3204 Function *F = dyn_cast<Function>(GV);
3205 // If this function isn't dematerializable, this is a noop.
3206 if (!F || !isDematerializable(F))
3209 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3211 // Just forget the function body, we can remat it later.
3215 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3216 assert(M == TheModule &&
3217 "Can only Materialize the Module this BitcodeReader is attached to.");
3218 // Iterate over the module, deserializing any functions that are still on
3220 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3222 if (F->isMaterializable()) {
3223 if (std::error_code EC = Materialize(F))
3227 // At this point, if there are any function bodies, the current bit is
3228 // pointing to the END_BLOCK record after them. Now make sure the rest
3229 // of the bits in the module have been read.
3233 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3234 // delete the old functions to clean up. We can't do this unless the entire
3235 // module is materialized because there could always be another function body
3236 // with calls to the old function.
3237 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3238 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3239 if (I->first != I->second) {
3240 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3242 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3243 UpgradeIntrinsicCall(CI, I->second);
3245 if (!I->first->use_empty())
3246 I->first->replaceAllUsesWith(I->second);
3247 I->first->eraseFromParent();
3250 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3252 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3253 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3255 UpgradeDebugInfo(*M);
3256 return std::error_code();
3259 std::error_code BitcodeReader::InitStream() {
3261 return InitLazyStream();
3262 return InitStreamFromBuffer();
3265 std::error_code BitcodeReader::InitStreamFromBuffer() {
3266 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3267 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3269 if (Buffer->getBufferSize() & 3) {
3270 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3271 return Error(InvalidBitcodeSignature);
3273 return Error(BitcodeStreamInvalidSize);
3276 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3277 // The magic number is 0x0B17C0DE stored in little endian.
3278 if (isBitcodeWrapper(BufPtr, BufEnd))
3279 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3280 return Error(InvalidBitcodeWrapperHeader);
3282 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3283 Stream.init(*StreamFile);
3285 return std::error_code();
3288 std::error_code BitcodeReader::InitLazyStream() {
3289 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3291 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3292 StreamFile.reset(new BitstreamReader(Bytes));
3293 Stream.init(*StreamFile);
3295 unsigned char buf[16];
3296 if (Bytes->readBytes(0, 16, buf) == -1)
3297 return Error(BitcodeStreamInvalidSize);
3299 if (!isBitcode(buf, buf + 16))
3300 return Error(InvalidBitcodeSignature);
3302 if (isBitcodeWrapper(buf, buf + 4)) {
3303 const unsigned char *bitcodeStart = buf;
3304 const unsigned char *bitcodeEnd = buf + 16;
3305 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3306 Bytes->dropLeadingBytes(bitcodeStart - buf);
3307 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3309 return std::error_code();
3313 class BitcodeErrorCategoryType : public std::error_category {
3314 const char *name() const LLVM_NOEXCEPT override {
3315 return "llvm.bitcode";
3317 std::string message(int IE) const override {
3318 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3320 case BitcodeReader::BitcodeStreamInvalidSize:
3321 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3322 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3323 return "Conflicting METADATA_KIND records";
3324 case BitcodeReader::CouldNotFindFunctionInStream:
3325 return "Could not find function in stream";
3326 case BitcodeReader::ExpectedConstant:
3327 return "Expected a constant";
3328 case BitcodeReader::InsufficientFunctionProtos:
3329 return "Insufficient function protos";
3330 case BitcodeReader::InvalidBitcodeSignature:
3331 return "Invalid bitcode signature";
3332 case BitcodeReader::InvalidBitcodeWrapperHeader:
3333 return "Invalid bitcode wrapper header";
3334 case BitcodeReader::InvalidConstantReference:
3335 return "Invalid ronstant reference";
3336 case BitcodeReader::InvalidID:
3337 return "Invalid ID";
3338 case BitcodeReader::InvalidInstructionWithNoBB:
3339 return "Invalid instruction with no BB";
3340 case BitcodeReader::InvalidRecord:
3341 return "Invalid record";
3342 case BitcodeReader::InvalidTypeForValue:
3343 return "Invalid type for value";
3344 case BitcodeReader::InvalidTYPETable:
3345 return "Invalid TYPE table";
3346 case BitcodeReader::InvalidType:
3347 return "Invalid type";
3348 case BitcodeReader::MalformedBlock:
3349 return "Malformed block";
3350 case BitcodeReader::MalformedGlobalInitializerSet:
3351 return "Malformed global initializer set";
3352 case BitcodeReader::InvalidMultipleBlocks:
3353 return "Invalid multiple blocks";
3354 case BitcodeReader::NeverResolvedValueFoundInFunction:
3355 return "Never resolved value found in function";
3356 case BitcodeReader::InvalidValue:
3357 return "Invalid value";
3359 llvm_unreachable("Unknown error type!");
3364 const std::error_category &BitcodeReader::BitcodeErrorCategory() {
3365 static BitcodeErrorCategoryType O;
3369 //===----------------------------------------------------------------------===//
3370 // External interface
3371 //===----------------------------------------------------------------------===//
3373 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3375 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3376 LLVMContext &Context) {
3377 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3378 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3379 M->setMaterializer(R);
3380 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3381 R->releaseBuffer(); // Never take ownership on error.
3382 delete M; // Also deletes R.
3386 R->materializeForwardReferencedFunctions();
3392 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3393 DataStreamer *streamer,
3394 LLVMContext &Context,
3395 std::string *ErrMsg) {
3396 Module *M = new Module(name, Context);
3397 BitcodeReader *R = new BitcodeReader(streamer, Context);
3398 M->setMaterializer(R);
3399 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3401 *ErrMsg = EC.message();
3402 delete M; // Also deletes R.
3408 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3409 LLVMContext &Context) {
3410 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3413 Module *M = ModuleOrErr.get();
3414 // Read in the entire module, and destroy the BitcodeReader.
3415 if (std::error_code EC = M->materializeAllPermanently(true)) {
3420 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3421 // written. We must defer until the Module has been fully materialized.
3426 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3427 LLVMContext& Context,
3428 std::string *ErrMsg) {
3429 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3431 std::string Triple("");
3432 if (std::error_code EC = R->ParseTriple(Triple))
3434 *ErrMsg = EC.message();