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 // This header defines the BitcodeReader class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "BitcodeReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/AutoUpgrade.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/OperandTraits.h"
30 void BitcodeReader::FreeState() {
34 std::vector<Type*>().swap(TypeList);
38 std::vector<AttrListPtr>().swap(MAttributes);
39 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
45 //===----------------------------------------------------------------------===//
46 // Helper functions to implement forward reference resolution, etc.
47 //===----------------------------------------------------------------------===//
49 /// ConvertToString - Convert a string from a record into an std::string, return
51 template<typename StrTy>
52 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
54 if (Idx > Record.size())
57 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58 Result += (char)Record[i];
62 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
64 default: // Map unknown/new linkages to external
65 case 0: return GlobalValue::ExternalLinkage;
66 case 1: return GlobalValue::WeakAnyLinkage;
67 case 2: return GlobalValue::AppendingLinkage;
68 case 3: return GlobalValue::InternalLinkage;
69 case 4: return GlobalValue::LinkOnceAnyLinkage;
70 case 5: return GlobalValue::DLLImportLinkage;
71 case 6: return GlobalValue::DLLExportLinkage;
72 case 7: return GlobalValue::ExternalWeakLinkage;
73 case 8: return GlobalValue::CommonLinkage;
74 case 9: return GlobalValue::PrivateLinkage;
75 case 10: return GlobalValue::WeakODRLinkage;
76 case 11: return GlobalValue::LinkOnceODRLinkage;
77 case 12: return GlobalValue::AvailableExternallyLinkage;
78 case 13: return GlobalValue::LinkerPrivateLinkage;
79 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
80 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
84 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
86 default: // Map unknown visibilities to default.
87 case 0: return GlobalValue::DefaultVisibility;
88 case 1: return GlobalValue::HiddenVisibility;
89 case 2: return GlobalValue::ProtectedVisibility;
93 static int GetDecodedCastOpcode(unsigned Val) {
96 case bitc::CAST_TRUNC : return Instruction::Trunc;
97 case bitc::CAST_ZEXT : return Instruction::ZExt;
98 case bitc::CAST_SEXT : return Instruction::SExt;
99 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
100 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
101 case bitc::CAST_UITOFP : return Instruction::UIToFP;
102 case bitc::CAST_SITOFP : return Instruction::SIToFP;
103 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
104 case bitc::CAST_FPEXT : return Instruction::FPExt;
105 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
106 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
107 case bitc::CAST_BITCAST : return Instruction::BitCast;
110 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
113 case bitc::BINOP_ADD:
114 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
115 case bitc::BINOP_SUB:
116 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
117 case bitc::BINOP_MUL:
118 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
119 case bitc::BINOP_UDIV: return Instruction::UDiv;
120 case bitc::BINOP_SDIV:
121 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
122 case bitc::BINOP_UREM: return Instruction::URem;
123 case bitc::BINOP_SREM:
124 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
125 case bitc::BINOP_SHL: return Instruction::Shl;
126 case bitc::BINOP_LSHR: return Instruction::LShr;
127 case bitc::BINOP_ASHR: return Instruction::AShr;
128 case bitc::BINOP_AND: return Instruction::And;
129 case bitc::BINOP_OR: return Instruction::Or;
130 case bitc::BINOP_XOR: return Instruction::Xor;
134 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
136 default: return AtomicRMWInst::BAD_BINOP;
137 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
138 case bitc::RMW_ADD: return AtomicRMWInst::Add;
139 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
140 case bitc::RMW_AND: return AtomicRMWInst::And;
141 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
142 case bitc::RMW_OR: return AtomicRMWInst::Or;
143 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
144 case bitc::RMW_MAX: return AtomicRMWInst::Max;
145 case bitc::RMW_MIN: return AtomicRMWInst::Min;
146 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
147 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
151 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
153 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
154 case bitc::ORDERING_UNORDERED: return Unordered;
155 case bitc::ORDERING_MONOTONIC: return Monotonic;
156 case bitc::ORDERING_ACQUIRE: return Acquire;
157 case bitc::ORDERING_RELEASE: return Release;
158 case bitc::ORDERING_ACQREL: return AcquireRelease;
159 default: // Map unknown orderings to sequentially-consistent.
160 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
164 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
166 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
167 default: // Map unknown scopes to cross-thread.
168 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
174 /// @brief A class for maintaining the slot number definition
175 /// as a placeholder for the actual definition for forward constants defs.
176 class ConstantPlaceHolder : public ConstantExpr {
177 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
179 // allocate space for exactly one operand
180 void *operator new(size_t s) {
181 return User::operator new(s, 1);
183 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
184 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
185 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
188 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
189 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
190 static bool classof(const Value *V) {
191 return isa<ConstantExpr>(V) &&
192 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
196 /// Provide fast operand accessors
197 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
201 // FIXME: can we inherit this from ConstantExpr?
203 struct OperandTraits<ConstantPlaceHolder> :
204 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
209 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
218 WeakVH &OldV = ValuePtrs[Idx];
224 // Handle constants and non-constants (e.g. instrs) differently for
226 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
227 ResolveConstants.push_back(std::make_pair(PHC, Idx));
230 // If there was a forward reference to this value, replace it.
231 Value *PrevVal = OldV;
232 OldV->replaceAllUsesWith(V);
238 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
243 if (Value *V = ValuePtrs[Idx]) {
244 assert(Ty == V->getType() && "Type mismatch in constant table!");
245 return cast<Constant>(V);
248 // Create and return a placeholder, which will later be RAUW'd.
249 Constant *C = new ConstantPlaceHolder(Ty, Context);
254 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
258 if (Value *V = ValuePtrs[Idx]) {
259 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
263 // No type specified, must be invalid reference.
264 if (Ty == 0) return 0;
266 // Create and return a placeholder, which will later be RAUW'd.
267 Value *V = new Argument(Ty);
272 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
273 /// resolves any forward references. The idea behind this is that we sometimes
274 /// get constants (such as large arrays) which reference *many* forward ref
275 /// constants. Replacing each of these causes a lot of thrashing when
276 /// building/reuniquing the constant. Instead of doing this, we look at all the
277 /// uses and rewrite all the place holders at once for any constant that uses
279 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
280 // Sort the values by-pointer so that they are efficient to look up with a
282 std::sort(ResolveConstants.begin(), ResolveConstants.end());
284 SmallVector<Constant*, 64> NewOps;
286 while (!ResolveConstants.empty()) {
287 Value *RealVal = operator[](ResolveConstants.back().second);
288 Constant *Placeholder = ResolveConstants.back().first;
289 ResolveConstants.pop_back();
291 // Loop over all users of the placeholder, updating them to reference the
292 // new value. If they reference more than one placeholder, update them all
294 while (!Placeholder->use_empty()) {
295 Value::use_iterator UI = Placeholder->use_begin();
298 // If the using object isn't uniqued, just update the operands. This
299 // handles instructions and initializers for global variables.
300 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
301 UI.getUse().set(RealVal);
305 // Otherwise, we have a constant that uses the placeholder. Replace that
306 // constant with a new constant that has *all* placeholder uses updated.
307 Constant *UserC = cast<Constant>(U);
308 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
311 if (!isa<ConstantPlaceHolder>(*I)) {
312 // Not a placeholder reference.
314 } else if (*I == Placeholder) {
315 // Common case is that it just references this one placeholder.
318 // Otherwise, look up the placeholder in ResolveConstants.
319 ResolveConstantsTy::iterator It =
320 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
321 std::pair<Constant*, unsigned>(cast<Constant>(*I),
323 assert(It != ResolveConstants.end() && It->first == *I);
324 NewOp = operator[](It->second);
327 NewOps.push_back(cast<Constant>(NewOp));
330 // Make the new constant.
332 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
333 NewC = ConstantArray::get(UserCA->getType(), NewOps);
334 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
335 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
336 } else if (isa<ConstantVector>(UserC)) {
337 NewC = ConstantVector::get(NewOps);
339 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
340 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
343 UserC->replaceAllUsesWith(NewC);
344 UserC->destroyConstant();
348 // Update all ValueHandles, they should be the only users at this point.
349 Placeholder->replaceAllUsesWith(RealVal);
354 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
363 WeakVH &OldV = MDValuePtrs[Idx];
369 // If there was a forward reference to this value, replace it.
370 MDNode *PrevVal = cast<MDNode>(OldV);
371 OldV->replaceAllUsesWith(V);
372 MDNode::deleteTemporary(PrevVal);
373 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
375 MDValuePtrs[Idx] = V;
378 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
382 if (Value *V = MDValuePtrs[Idx]) {
383 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
387 // Create and return a placeholder, which will later be RAUW'd.
388 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
389 MDValuePtrs[Idx] = V;
393 Type *BitcodeReader::getTypeByID(unsigned ID) {
394 // The type table size is always specified correctly.
395 if (ID >= TypeList.size())
398 if (Type *Ty = TypeList[ID])
401 // If we have a forward reference, the only possible case is when it is to a
402 // named struct. Just create a placeholder for now.
403 return TypeList[ID] = StructType::create(Context);
407 //===----------------------------------------------------------------------===//
408 // Functions for parsing blocks from the bitcode file
409 //===----------------------------------------------------------------------===//
411 bool BitcodeReader::ParseAttributeBlock() {
412 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
413 return Error("Malformed block record");
415 if (!MAttributes.empty())
416 return Error("Multiple PARAMATTR blocks found!");
418 SmallVector<uint64_t, 64> Record;
420 SmallVector<AttributeWithIndex, 8> Attrs;
422 // Read all the records.
424 unsigned Code = Stream.ReadCode();
425 if (Code == bitc::END_BLOCK) {
426 if (Stream.ReadBlockEnd())
427 return Error("Error at end of PARAMATTR block");
431 if (Code == bitc::ENTER_SUBBLOCK) {
432 // No known subblocks, always skip them.
433 Stream.ReadSubBlockID();
434 if (Stream.SkipBlock())
435 return Error("Malformed block record");
439 if (Code == bitc::DEFINE_ABBREV) {
440 Stream.ReadAbbrevRecord();
446 switch (Stream.ReadRecord(Code, Record)) {
447 default: // Default behavior: ignore.
449 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
450 if (Record.size() & 1)
451 return Error("Invalid ENTRY record");
453 // FIXME : Remove this autoupgrade code in LLVM 3.0.
454 // If Function attributes are using index 0 then transfer them
455 // to index ~0. Index 0 is used for return value attributes but used to be
456 // used for function attributes.
457 Attributes RetAttribute = Attribute::None;
458 Attributes FnAttribute = Attribute::None;
459 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
460 // FIXME: remove in LLVM 3.0
461 // The alignment is stored as a 16-bit raw value from bits 31--16.
462 // We shift the bits above 31 down by 11 bits.
464 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
465 if (Alignment && !isPowerOf2_32(Alignment))
466 return Error("Alignment is not a power of two.");
468 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
470 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
471 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
472 Record[i+1] = ReconstitutedAttr;
475 RetAttribute = Record[i+1];
476 else if (Record[i] == ~0U)
477 FnAttribute = Record[i+1];
480 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
481 Attribute::ReadOnly|Attribute::ReadNone);
483 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
484 (RetAttribute & OldRetAttrs) != 0) {
485 if (FnAttribute == Attribute::None) { // add a slot so they get added.
486 Record.push_back(~0U);
490 FnAttribute |= RetAttribute & OldRetAttrs;
491 RetAttribute &= ~OldRetAttrs;
494 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
495 if (Record[i] == 0) {
496 if (RetAttribute != Attribute::None)
497 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
498 } else if (Record[i] == ~0U) {
499 if (FnAttribute != Attribute::None)
500 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
501 } else if (Record[i+1] != Attribute::None)
502 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
505 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
513 bool BitcodeReader::ParseTypeTable() {
514 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
515 return Error("Malformed block record");
517 return ParseTypeTableBody();
520 bool BitcodeReader::ParseTypeTableBody() {
521 if (!TypeList.empty())
522 return Error("Multiple TYPE_BLOCKs found!");
524 SmallVector<uint64_t, 64> Record;
525 unsigned NumRecords = 0;
527 SmallString<64> TypeName;
529 // Read all the records for this type table.
531 unsigned Code = Stream.ReadCode();
532 if (Code == bitc::END_BLOCK) {
533 if (NumRecords != TypeList.size())
534 return Error("Invalid type forward reference in TYPE_BLOCK");
535 if (Stream.ReadBlockEnd())
536 return Error("Error at end of type table block");
540 if (Code == bitc::ENTER_SUBBLOCK) {
541 // No known subblocks, always skip them.
542 Stream.ReadSubBlockID();
543 if (Stream.SkipBlock())
544 return Error("Malformed block record");
548 if (Code == bitc::DEFINE_ABBREV) {
549 Stream.ReadAbbrevRecord();
556 switch (Stream.ReadRecord(Code, Record)) {
557 default: return Error("unknown type in type table");
558 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
559 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
560 // type list. This allows us to reserve space.
561 if (Record.size() < 1)
562 return Error("Invalid TYPE_CODE_NUMENTRY record");
563 TypeList.resize(Record[0]);
565 case bitc::TYPE_CODE_VOID: // VOID
566 ResultTy = Type::getVoidTy(Context);
568 case bitc::TYPE_CODE_HALF: // HALF
569 ResultTy = Type::getHalfTy(Context);
571 case bitc::TYPE_CODE_FLOAT: // FLOAT
572 ResultTy = Type::getFloatTy(Context);
574 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
575 ResultTy = Type::getDoubleTy(Context);
577 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
578 ResultTy = Type::getX86_FP80Ty(Context);
580 case bitc::TYPE_CODE_FP128: // FP128
581 ResultTy = Type::getFP128Ty(Context);
583 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
584 ResultTy = Type::getPPC_FP128Ty(Context);
586 case bitc::TYPE_CODE_LABEL: // LABEL
587 ResultTy = Type::getLabelTy(Context);
589 case bitc::TYPE_CODE_METADATA: // METADATA
590 ResultTy = Type::getMetadataTy(Context);
592 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
593 ResultTy = Type::getX86_MMXTy(Context);
595 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
596 if (Record.size() < 1)
597 return Error("Invalid Integer type record");
599 ResultTy = IntegerType::get(Context, Record[0]);
601 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
602 // [pointee type, address space]
603 if (Record.size() < 1)
604 return Error("Invalid POINTER type record");
605 unsigned AddressSpace = 0;
606 if (Record.size() == 2)
607 AddressSpace = Record[1];
608 ResultTy = getTypeByID(Record[0]);
609 if (ResultTy == 0) return Error("invalid element type in pointer type");
610 ResultTy = PointerType::get(ResultTy, AddressSpace);
613 case bitc::TYPE_CODE_FUNCTION_OLD: {
614 // FIXME: attrid is dead, remove it in LLVM 3.0
615 // FUNCTION: [vararg, attrid, retty, paramty x N]
616 if (Record.size() < 3)
617 return Error("Invalid FUNCTION type record");
618 std::vector<Type*> ArgTys;
619 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
620 if (Type *T = getTypeByID(Record[i]))
626 ResultTy = getTypeByID(Record[2]);
627 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
628 return Error("invalid type in function type");
630 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
633 case bitc::TYPE_CODE_FUNCTION: {
634 // FUNCTION: [vararg, retty, paramty x N]
635 if (Record.size() < 2)
636 return Error("Invalid FUNCTION type record");
637 std::vector<Type*> ArgTys;
638 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
639 if (Type *T = getTypeByID(Record[i]))
645 ResultTy = getTypeByID(Record[1]);
646 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
647 return Error("invalid type in function type");
649 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
652 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
653 if (Record.size() < 1)
654 return Error("Invalid STRUCT type record");
655 std::vector<Type*> EltTys;
656 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
657 if (Type *T = getTypeByID(Record[i]))
662 if (EltTys.size() != Record.size()-1)
663 return Error("invalid type in struct type");
664 ResultTy = StructType::get(Context, EltTys, Record[0]);
667 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
668 if (ConvertToString(Record, 0, TypeName))
669 return Error("Invalid STRUCT_NAME record");
672 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
673 if (Record.size() < 1)
674 return Error("Invalid STRUCT type record");
676 if (NumRecords >= TypeList.size())
677 return Error("invalid TYPE table");
679 // Check to see if this was forward referenced, if so fill in the temp.
680 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
682 Res->setName(TypeName);
683 TypeList[NumRecords] = 0;
684 } else // Otherwise, create a new struct.
685 Res = StructType::create(Context, TypeName);
688 SmallVector<Type*, 8> EltTys;
689 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
690 if (Type *T = getTypeByID(Record[i]))
695 if (EltTys.size() != Record.size()-1)
696 return Error("invalid STRUCT type record");
697 Res->setBody(EltTys, Record[0]);
701 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
702 if (Record.size() != 1)
703 return Error("Invalid OPAQUE type record");
705 if (NumRecords >= TypeList.size())
706 return Error("invalid TYPE table");
708 // Check to see if this was forward referenced, if so fill in the temp.
709 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
711 Res->setName(TypeName);
712 TypeList[NumRecords] = 0;
713 } else // Otherwise, create a new struct with no body.
714 Res = StructType::create(Context, TypeName);
719 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
720 if (Record.size() < 2)
721 return Error("Invalid ARRAY type record");
722 if ((ResultTy = getTypeByID(Record[1])))
723 ResultTy = ArrayType::get(ResultTy, Record[0]);
725 return Error("Invalid ARRAY type element");
727 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
728 if (Record.size() < 2)
729 return Error("Invalid VECTOR type record");
730 if ((ResultTy = getTypeByID(Record[1])))
731 ResultTy = VectorType::get(ResultTy, Record[0]);
733 return Error("Invalid ARRAY type element");
737 if (NumRecords >= TypeList.size())
738 return Error("invalid TYPE table");
739 assert(ResultTy && "Didn't read a type?");
740 assert(TypeList[NumRecords] == 0 && "Already read type?");
741 TypeList[NumRecords++] = ResultTy;
745 bool BitcodeReader::ParseValueSymbolTable() {
746 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
747 return Error("Malformed block record");
749 SmallVector<uint64_t, 64> Record;
751 // Read all the records for this value table.
752 SmallString<128> ValueName;
754 unsigned Code = Stream.ReadCode();
755 if (Code == bitc::END_BLOCK) {
756 if (Stream.ReadBlockEnd())
757 return Error("Error at end of value symbol table block");
760 if (Code == bitc::ENTER_SUBBLOCK) {
761 // No known subblocks, always skip them.
762 Stream.ReadSubBlockID();
763 if (Stream.SkipBlock())
764 return Error("Malformed block record");
768 if (Code == bitc::DEFINE_ABBREV) {
769 Stream.ReadAbbrevRecord();
775 switch (Stream.ReadRecord(Code, Record)) {
776 default: // Default behavior: unknown type.
778 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
779 if (ConvertToString(Record, 1, ValueName))
780 return Error("Invalid VST_ENTRY record");
781 unsigned ValueID = Record[0];
782 if (ValueID >= ValueList.size())
783 return Error("Invalid Value ID in VST_ENTRY record");
784 Value *V = ValueList[ValueID];
786 V->setName(StringRef(ValueName.data(), ValueName.size()));
790 case bitc::VST_CODE_BBENTRY: {
791 if (ConvertToString(Record, 1, ValueName))
792 return Error("Invalid VST_BBENTRY record");
793 BasicBlock *BB = getBasicBlock(Record[0]);
795 return Error("Invalid BB ID in VST_BBENTRY record");
797 BB->setName(StringRef(ValueName.data(), ValueName.size()));
805 bool BitcodeReader::ParseMetadata() {
806 unsigned NextMDValueNo = MDValueList.size();
808 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
809 return Error("Malformed block record");
811 SmallVector<uint64_t, 64> Record;
813 // Read all the records.
815 unsigned Code = Stream.ReadCode();
816 if (Code == bitc::END_BLOCK) {
817 if (Stream.ReadBlockEnd())
818 return Error("Error at end of PARAMATTR block");
822 if (Code == bitc::ENTER_SUBBLOCK) {
823 // No known subblocks, always skip them.
824 Stream.ReadSubBlockID();
825 if (Stream.SkipBlock())
826 return Error("Malformed block record");
830 if (Code == bitc::DEFINE_ABBREV) {
831 Stream.ReadAbbrevRecord();
835 bool IsFunctionLocal = false;
838 Code = Stream.ReadRecord(Code, Record);
840 default: // Default behavior: ignore.
842 case bitc::METADATA_NAME: {
843 // Read named of the named metadata.
844 unsigned NameLength = Record.size();
846 Name.resize(NameLength);
847 for (unsigned i = 0; i != NameLength; ++i)
850 Code = Stream.ReadCode();
852 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
853 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
854 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
856 // Read named metadata elements.
857 unsigned Size = Record.size();
858 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
859 for (unsigned i = 0; i != Size; ++i) {
860 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
862 return Error("Malformed metadata record");
867 case bitc::METADATA_FN_NODE:
868 IsFunctionLocal = true;
870 case bitc::METADATA_NODE: {
871 if (Record.size() % 2 == 1)
872 return Error("Invalid METADATA_NODE record");
874 unsigned Size = Record.size();
875 SmallVector<Value*, 8> Elts;
876 for (unsigned i = 0; i != Size; i += 2) {
877 Type *Ty = getTypeByID(Record[i]);
878 if (!Ty) return Error("Invalid METADATA_NODE record");
879 if (Ty->isMetadataTy())
880 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
881 else if (!Ty->isVoidTy())
882 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
884 Elts.push_back(NULL);
886 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
887 IsFunctionLocal = false;
888 MDValueList.AssignValue(V, NextMDValueNo++);
891 case bitc::METADATA_STRING: {
892 unsigned MDStringLength = Record.size();
893 SmallString<8> String;
894 String.resize(MDStringLength);
895 for (unsigned i = 0; i != MDStringLength; ++i)
896 String[i] = Record[i];
897 Value *V = MDString::get(Context,
898 StringRef(String.data(), String.size()));
899 MDValueList.AssignValue(V, NextMDValueNo++);
902 case bitc::METADATA_KIND: {
903 unsigned RecordLength = Record.size();
904 if (Record.empty() || RecordLength < 2)
905 return Error("Invalid METADATA_KIND record");
907 Name.resize(RecordLength-1);
908 unsigned Kind = Record[0];
909 for (unsigned i = 1; i != RecordLength; ++i)
910 Name[i-1] = Record[i];
912 unsigned NewKind = TheModule->getMDKindID(Name.str());
913 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
914 return Error("Conflicting METADATA_KIND records");
921 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
922 /// the LSB for dense VBR encoding.
923 static uint64_t DecodeSignRotatedValue(uint64_t V) {
928 // There is no such thing as -0 with integers. "-0" really means MININT.
932 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
933 /// values and aliases that we can.
934 bool BitcodeReader::ResolveGlobalAndAliasInits() {
935 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
936 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
938 GlobalInitWorklist.swap(GlobalInits);
939 AliasInitWorklist.swap(AliasInits);
941 while (!GlobalInitWorklist.empty()) {
942 unsigned ValID = GlobalInitWorklist.back().second;
943 if (ValID >= ValueList.size()) {
944 // Not ready to resolve this yet, it requires something later in the file.
945 GlobalInits.push_back(GlobalInitWorklist.back());
947 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
948 GlobalInitWorklist.back().first->setInitializer(C);
950 return Error("Global variable initializer is not a constant!");
952 GlobalInitWorklist.pop_back();
955 while (!AliasInitWorklist.empty()) {
956 unsigned ValID = AliasInitWorklist.back().second;
957 if (ValID >= ValueList.size()) {
958 AliasInits.push_back(AliasInitWorklist.back());
960 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
961 AliasInitWorklist.back().first->setAliasee(C);
963 return Error("Alias initializer is not a constant!");
965 AliasInitWorklist.pop_back();
970 bool BitcodeReader::ParseConstants() {
971 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
972 return Error("Malformed block record");
974 SmallVector<uint64_t, 64> Record;
976 // Read all the records for this value table.
977 Type *CurTy = Type::getInt32Ty(Context);
978 unsigned NextCstNo = ValueList.size();
980 unsigned Code = Stream.ReadCode();
981 if (Code == bitc::END_BLOCK)
984 if (Code == bitc::ENTER_SUBBLOCK) {
985 // No known subblocks, always skip them.
986 Stream.ReadSubBlockID();
987 if (Stream.SkipBlock())
988 return Error("Malformed block record");
992 if (Code == bitc::DEFINE_ABBREV) {
993 Stream.ReadAbbrevRecord();
1000 unsigned BitCode = Stream.ReadRecord(Code, Record);
1002 default: // Default behavior: unknown constant
1003 case bitc::CST_CODE_UNDEF: // UNDEF
1004 V = UndefValue::get(CurTy);
1006 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1008 return Error("Malformed CST_SETTYPE record");
1009 if (Record[0] >= TypeList.size())
1010 return Error("Invalid Type ID in CST_SETTYPE record");
1011 CurTy = TypeList[Record[0]];
1012 continue; // Skip the ValueList manipulation.
1013 case bitc::CST_CODE_NULL: // NULL
1014 V = Constant::getNullValue(CurTy);
1016 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1017 if (!CurTy->isIntegerTy() || Record.empty())
1018 return Error("Invalid CST_INTEGER record");
1019 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
1021 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1022 if (!CurTy->isIntegerTy() || Record.empty())
1023 return Error("Invalid WIDE_INTEGER record");
1025 unsigned NumWords = Record.size();
1026 SmallVector<uint64_t, 8> Words;
1027 Words.resize(NumWords);
1028 for (unsigned i = 0; i != NumWords; ++i)
1029 Words[i] = DecodeSignRotatedValue(Record[i]);
1030 V = ConstantInt::get(Context,
1031 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
1035 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1037 return Error("Invalid FLOAT record");
1038 if (CurTy->isHalfTy())
1039 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1040 else if (CurTy->isFloatTy())
1041 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1042 else if (CurTy->isDoubleTy())
1043 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1044 else if (CurTy->isX86_FP80Ty()) {
1045 // Bits are not stored the same way as a normal i80 APInt, compensate.
1046 uint64_t Rearrange[2];
1047 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1048 Rearrange[1] = Record[0] >> 48;
1049 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1050 } else if (CurTy->isFP128Ty())
1051 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1052 else if (CurTy->isPPC_FP128Ty())
1053 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1055 V = UndefValue::get(CurTy);
1059 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1061 return Error("Invalid CST_AGGREGATE record");
1063 unsigned Size = Record.size();
1064 std::vector<Constant*> Elts;
1066 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1067 for (unsigned i = 0; i != Size; ++i)
1068 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1069 STy->getElementType(i)));
1070 V = ConstantStruct::get(STy, Elts);
1071 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1072 Type *EltTy = ATy->getElementType();
1073 for (unsigned i = 0; i != Size; ++i)
1074 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1075 V = ConstantArray::get(ATy, Elts);
1076 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1077 Type *EltTy = VTy->getElementType();
1078 for (unsigned i = 0; i != Size; ++i)
1079 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1080 V = ConstantVector::get(Elts);
1082 V = UndefValue::get(CurTy);
1086 case bitc::CST_CODE_STRING: { // STRING: [values]
1088 return Error("Invalid CST_AGGREGATE record");
1090 ArrayType *ATy = cast<ArrayType>(CurTy);
1091 Type *EltTy = ATy->getElementType();
1093 unsigned Size = Record.size();
1094 std::vector<Constant*> Elts;
1095 for (unsigned i = 0; i != Size; ++i)
1096 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1097 V = ConstantArray::get(ATy, Elts);
1100 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1102 return Error("Invalid CST_AGGREGATE record");
1104 ArrayType *ATy = cast<ArrayType>(CurTy);
1105 Type *EltTy = ATy->getElementType();
1107 unsigned Size = Record.size();
1108 std::vector<Constant*> Elts;
1109 for (unsigned i = 0; i != Size; ++i)
1110 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1111 Elts.push_back(Constant::getNullValue(EltTy));
1112 V = ConstantArray::get(ATy, Elts);
1115 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1116 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1117 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1119 V = UndefValue::get(CurTy); // Unknown binop.
1121 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1122 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1124 if (Record.size() >= 4) {
1125 if (Opc == Instruction::Add ||
1126 Opc == Instruction::Sub ||
1127 Opc == Instruction::Mul ||
1128 Opc == Instruction::Shl) {
1129 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1130 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1131 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1132 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1133 } else if (Opc == Instruction::SDiv ||
1134 Opc == Instruction::UDiv ||
1135 Opc == Instruction::LShr ||
1136 Opc == Instruction::AShr) {
1137 if (Record[3] & (1 << bitc::PEO_EXACT))
1138 Flags |= SDivOperator::IsExact;
1141 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1145 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1146 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1147 int Opc = GetDecodedCastOpcode(Record[0]);
1149 V = UndefValue::get(CurTy); // Unknown cast.
1151 Type *OpTy = getTypeByID(Record[1]);
1152 if (!OpTy) return Error("Invalid CE_CAST record");
1153 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1154 V = ConstantExpr::getCast(Opc, Op, CurTy);
1158 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1159 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1160 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1161 SmallVector<Constant*, 16> Elts;
1162 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1163 Type *ElTy = getTypeByID(Record[i]);
1164 if (!ElTy) return Error("Invalid CE_GEP record");
1165 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1167 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1168 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1170 bitc::CST_CODE_CE_INBOUNDS_GEP);
1173 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1174 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1175 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1176 Type::getInt1Ty(Context)),
1177 ValueList.getConstantFwdRef(Record[1],CurTy),
1178 ValueList.getConstantFwdRef(Record[2],CurTy));
1180 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1181 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1183 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1184 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1185 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1186 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1187 V = ConstantExpr::getExtractElement(Op0, Op1);
1190 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1191 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1192 if (Record.size() < 3 || OpTy == 0)
1193 return Error("Invalid CE_INSERTELT record");
1194 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1195 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1196 OpTy->getElementType());
1197 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1198 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1201 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1202 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1203 if (Record.size() < 3 || OpTy == 0)
1204 return Error("Invalid CE_SHUFFLEVEC record");
1205 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1206 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1207 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1208 OpTy->getNumElements());
1209 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1210 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1213 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1214 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1216 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1217 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1218 return Error("Invalid CE_SHUFVEC_EX record");
1219 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1220 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1221 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1222 RTy->getNumElements());
1223 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1224 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1227 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1228 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1229 Type *OpTy = getTypeByID(Record[0]);
1230 if (OpTy == 0) return Error("Invalid CE_CMP record");
1231 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1232 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1234 if (OpTy->isFPOrFPVectorTy())
1235 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1237 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1240 case bitc::CST_CODE_INLINEASM: {
1241 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1242 std::string AsmStr, ConstrStr;
1243 bool HasSideEffects = Record[0] & 1;
1244 bool IsAlignStack = Record[0] >> 1;
1245 unsigned AsmStrSize = Record[1];
1246 if (2+AsmStrSize >= Record.size())
1247 return Error("Invalid INLINEASM record");
1248 unsigned ConstStrSize = Record[2+AsmStrSize];
1249 if (3+AsmStrSize+ConstStrSize > Record.size())
1250 return Error("Invalid INLINEASM record");
1252 for (unsigned i = 0; i != AsmStrSize; ++i)
1253 AsmStr += (char)Record[2+i];
1254 for (unsigned i = 0; i != ConstStrSize; ++i)
1255 ConstrStr += (char)Record[3+AsmStrSize+i];
1256 PointerType *PTy = cast<PointerType>(CurTy);
1257 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1258 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1261 case bitc::CST_CODE_BLOCKADDRESS:{
1262 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1263 Type *FnTy = getTypeByID(Record[0]);
1264 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1266 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1267 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1269 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1270 Type::getInt8Ty(Context),
1271 false, GlobalValue::InternalLinkage,
1273 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1279 ValueList.AssignValue(V, NextCstNo);
1283 if (NextCstNo != ValueList.size())
1284 return Error("Invalid constant reference!");
1286 if (Stream.ReadBlockEnd())
1287 return Error("Error at end of constants block");
1289 // Once all the constants have been read, go through and resolve forward
1291 ValueList.ResolveConstantForwardRefs();
1295 bool BitcodeReader::ParseUseLists() {
1296 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1297 return Error("Malformed block record");
1299 SmallVector<uint64_t, 64> Record;
1301 // Read all the records.
1303 unsigned Code = Stream.ReadCode();
1304 if (Code == bitc::END_BLOCK) {
1305 if (Stream.ReadBlockEnd())
1306 return Error("Error at end of use-list table block");
1310 if (Code == bitc::ENTER_SUBBLOCK) {
1311 // No known subblocks, always skip them.
1312 Stream.ReadSubBlockID();
1313 if (Stream.SkipBlock())
1314 return Error("Malformed block record");
1318 if (Code == bitc::DEFINE_ABBREV) {
1319 Stream.ReadAbbrevRecord();
1323 // Read a use list record.
1325 switch (Stream.ReadRecord(Code, Record)) {
1326 default: // Default behavior: unknown type.
1328 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1329 unsigned RecordLength = Record.size();
1330 if (RecordLength < 1)
1331 return Error ("Invalid UseList reader!");
1332 UseListRecords.push_back(Record);
1339 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1340 /// remember where it is and then skip it. This lets us lazily deserialize the
1342 bool BitcodeReader::RememberAndSkipFunctionBody() {
1343 // Get the function we are talking about.
1344 if (FunctionsWithBodies.empty())
1345 return Error("Insufficient function protos");
1347 Function *Fn = FunctionsWithBodies.back();
1348 FunctionsWithBodies.pop_back();
1350 // Save the current stream state.
1351 uint64_t CurBit = Stream.GetCurrentBitNo();
1352 DeferredFunctionInfo[Fn] = CurBit;
1354 // Skip over the function block for now.
1355 if (Stream.SkipBlock())
1356 return Error("Malformed block record");
1360 bool BitcodeReader::ParseModule() {
1361 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1362 return Error("Malformed block record");
1364 SmallVector<uint64_t, 64> Record;
1365 std::vector<std::string> SectionTable;
1366 std::vector<std::string> GCTable;
1368 // Read all the records for this module.
1369 while (!Stream.AtEndOfStream()) {
1370 unsigned Code = Stream.ReadCode();
1371 if (Code == bitc::END_BLOCK) {
1372 if (Stream.ReadBlockEnd())
1373 return Error("Error at end of module block");
1375 // Patch the initializers for globals and aliases up.
1376 ResolveGlobalAndAliasInits();
1377 if (!GlobalInits.empty() || !AliasInits.empty())
1378 return Error("Malformed global initializer set");
1379 if (!FunctionsWithBodies.empty())
1380 return Error("Too few function bodies found");
1382 // Look for intrinsic functions which need to be upgraded at some point
1383 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1386 if (UpgradeIntrinsicFunction(FI, NewFn))
1387 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1390 // Look for global variables which need to be renamed.
1391 for (Module::global_iterator
1392 GI = TheModule->global_begin(), GE = TheModule->global_end();
1394 UpgradeGlobalVariable(GI);
1396 // Force deallocation of memory for these vectors to favor the client that
1397 // want lazy deserialization.
1398 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1399 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1400 std::vector<Function*>().swap(FunctionsWithBodies);
1404 if (Code == bitc::ENTER_SUBBLOCK) {
1405 switch (Stream.ReadSubBlockID()) {
1406 default: // Skip unknown content.
1407 if (Stream.SkipBlock())
1408 return Error("Malformed block record");
1410 case bitc::BLOCKINFO_BLOCK_ID:
1411 if (Stream.ReadBlockInfoBlock())
1412 return Error("Malformed BlockInfoBlock");
1414 case bitc::PARAMATTR_BLOCK_ID:
1415 if (ParseAttributeBlock())
1418 case bitc::TYPE_BLOCK_ID_NEW:
1419 if (ParseTypeTable())
1422 case bitc::VALUE_SYMTAB_BLOCK_ID:
1423 if (ParseValueSymbolTable())
1426 case bitc::CONSTANTS_BLOCK_ID:
1427 if (ParseConstants() || ResolveGlobalAndAliasInits())
1430 case bitc::METADATA_BLOCK_ID:
1431 if (ParseMetadata())
1434 case bitc::FUNCTION_BLOCK_ID:
1435 // If this is the first function body we've seen, reverse the
1436 // FunctionsWithBodies list.
1437 if (!HasReversedFunctionsWithBodies) {
1438 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1439 HasReversedFunctionsWithBodies = true;
1442 if (RememberAndSkipFunctionBody())
1445 case bitc::USELIST_BLOCK_ID:
1446 if (ParseUseLists())
1453 if (Code == bitc::DEFINE_ABBREV) {
1454 Stream.ReadAbbrevRecord();
1459 switch (Stream.ReadRecord(Code, Record)) {
1460 default: break; // Default behavior, ignore unknown content.
1461 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1462 if (Record.size() < 1)
1463 return Error("Malformed MODULE_CODE_VERSION");
1464 // Only version #0 is supported so far.
1466 return Error("Unknown bitstream version!");
1468 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1470 if (ConvertToString(Record, 0, S))
1471 return Error("Invalid MODULE_CODE_TRIPLE record");
1472 TheModule->setTargetTriple(S);
1475 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1477 if (ConvertToString(Record, 0, S))
1478 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1479 TheModule->setDataLayout(S);
1482 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1484 if (ConvertToString(Record, 0, S))
1485 return Error("Invalid MODULE_CODE_ASM record");
1486 TheModule->setModuleInlineAsm(S);
1489 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1491 if (ConvertToString(Record, 0, S))
1492 return Error("Invalid MODULE_CODE_DEPLIB record");
1493 TheModule->addLibrary(S);
1496 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1498 if (ConvertToString(Record, 0, S))
1499 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1500 SectionTable.push_back(S);
1503 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1505 if (ConvertToString(Record, 0, S))
1506 return Error("Invalid MODULE_CODE_GCNAME record");
1507 GCTable.push_back(S);
1510 // GLOBALVAR: [pointer type, isconst, initid,
1511 // linkage, alignment, section, visibility, threadlocal,
1513 case bitc::MODULE_CODE_GLOBALVAR: {
1514 if (Record.size() < 6)
1515 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1516 Type *Ty = getTypeByID(Record[0]);
1517 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1518 if (!Ty->isPointerTy())
1519 return Error("Global not a pointer type!");
1520 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1521 Ty = cast<PointerType>(Ty)->getElementType();
1523 bool isConstant = Record[1];
1524 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1525 unsigned Alignment = (1 << Record[4]) >> 1;
1526 std::string Section;
1528 if (Record[5]-1 >= SectionTable.size())
1529 return Error("Invalid section ID");
1530 Section = SectionTable[Record[5]-1];
1532 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1533 if (Record.size() > 6)
1534 Visibility = GetDecodedVisibility(Record[6]);
1535 bool isThreadLocal = false;
1536 if (Record.size() > 7)
1537 isThreadLocal = Record[7];
1539 bool UnnamedAddr = false;
1540 if (Record.size() > 8)
1541 UnnamedAddr = Record[8];
1543 GlobalVariable *NewGV =
1544 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1545 isThreadLocal, AddressSpace);
1546 NewGV->setAlignment(Alignment);
1547 if (!Section.empty())
1548 NewGV->setSection(Section);
1549 NewGV->setVisibility(Visibility);
1550 NewGV->setThreadLocal(isThreadLocal);
1551 NewGV->setUnnamedAddr(UnnamedAddr);
1553 ValueList.push_back(NewGV);
1555 // Remember which value to use for the global initializer.
1556 if (unsigned InitID = Record[2])
1557 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1560 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1561 // alignment, section, visibility, gc, unnamed_addr]
1562 case bitc::MODULE_CODE_FUNCTION: {
1563 if (Record.size() < 8)
1564 return Error("Invalid MODULE_CODE_FUNCTION record");
1565 Type *Ty = getTypeByID(Record[0]);
1566 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1567 if (!Ty->isPointerTy())
1568 return Error("Function not a pointer type!");
1570 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1572 return Error("Function not a pointer to function type!");
1574 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1577 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1578 bool isProto = Record[2];
1579 Func->setLinkage(GetDecodedLinkage(Record[3]));
1580 Func->setAttributes(getAttributes(Record[4]));
1582 Func->setAlignment((1 << Record[5]) >> 1);
1584 if (Record[6]-1 >= SectionTable.size())
1585 return Error("Invalid section ID");
1586 Func->setSection(SectionTable[Record[6]-1]);
1588 Func->setVisibility(GetDecodedVisibility(Record[7]));
1589 if (Record.size() > 8 && Record[8]) {
1590 if (Record[8]-1 > GCTable.size())
1591 return Error("Invalid GC ID");
1592 Func->setGC(GCTable[Record[8]-1].c_str());
1594 bool UnnamedAddr = false;
1595 if (Record.size() > 9)
1596 UnnamedAddr = Record[9];
1597 Func->setUnnamedAddr(UnnamedAddr);
1598 ValueList.push_back(Func);
1600 // If this is a function with a body, remember the prototype we are
1601 // creating now, so that we can match up the body with them later.
1603 FunctionsWithBodies.push_back(Func);
1606 // ALIAS: [alias type, aliasee val#, linkage]
1607 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1608 case bitc::MODULE_CODE_ALIAS: {
1609 if (Record.size() < 3)
1610 return Error("Invalid MODULE_ALIAS record");
1611 Type *Ty = getTypeByID(Record[0]);
1612 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1613 if (!Ty->isPointerTy())
1614 return Error("Function not a pointer type!");
1616 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1618 // Old bitcode files didn't have visibility field.
1619 if (Record.size() > 3)
1620 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1621 ValueList.push_back(NewGA);
1622 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1625 /// MODULE_CODE_PURGEVALS: [numvals]
1626 case bitc::MODULE_CODE_PURGEVALS:
1627 // Trim down the value list to the specified size.
1628 if (Record.size() < 1 || Record[0] > ValueList.size())
1629 return Error("Invalid MODULE_PURGEVALS record");
1630 ValueList.shrinkTo(Record[0]);
1636 return Error("Premature end of bitstream");
1639 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1642 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1643 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1645 if (Buffer->getBufferSize() & 3) {
1646 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1647 return Error("Invalid bitcode signature");
1649 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1652 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1653 // The magic number is 0x0B17C0DE stored in little endian.
1654 if (isBitcodeWrapper(BufPtr, BufEnd))
1655 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1656 return Error("Invalid bitcode wrapper header");
1658 StreamFile.init(BufPtr, BufEnd);
1659 Stream.init(StreamFile);
1661 // Sniff for the signature.
1662 if (Stream.Read(8) != 'B' ||
1663 Stream.Read(8) != 'C' ||
1664 Stream.Read(4) != 0x0 ||
1665 Stream.Read(4) != 0xC ||
1666 Stream.Read(4) != 0xE ||
1667 Stream.Read(4) != 0xD)
1668 return Error("Invalid bitcode signature");
1670 // We expect a number of well-defined blocks, though we don't necessarily
1671 // need to understand them all.
1672 while (!Stream.AtEndOfStream()) {
1673 unsigned Code = Stream.ReadCode();
1675 if (Code != bitc::ENTER_SUBBLOCK) {
1677 // The ranlib in xcode 4 will align archive members by appending newlines
1678 // to the end of them. If this file size is a multiple of 4 but not 8, we
1679 // have to read and ignore these final 4 bytes :-(
1680 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1681 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1682 Stream.AtEndOfStream())
1685 return Error("Invalid record at top-level");
1688 unsigned BlockID = Stream.ReadSubBlockID();
1690 // We only know the MODULE subblock ID.
1692 case bitc::BLOCKINFO_BLOCK_ID:
1693 if (Stream.ReadBlockInfoBlock())
1694 return Error("Malformed BlockInfoBlock");
1696 case bitc::MODULE_BLOCK_ID:
1697 // Reject multiple MODULE_BLOCK's in a single bitstream.
1699 return Error("Multiple MODULE_BLOCKs in same stream");
1705 if (Stream.SkipBlock())
1706 return Error("Malformed block record");
1714 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1715 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1716 return Error("Malformed block record");
1718 SmallVector<uint64_t, 64> Record;
1720 // Read all the records for this module.
1721 while (!Stream.AtEndOfStream()) {
1722 unsigned Code = Stream.ReadCode();
1723 if (Code == bitc::END_BLOCK) {
1724 if (Stream.ReadBlockEnd())
1725 return Error("Error at end of module block");
1730 if (Code == bitc::ENTER_SUBBLOCK) {
1731 switch (Stream.ReadSubBlockID()) {
1732 default: // Skip unknown content.
1733 if (Stream.SkipBlock())
1734 return Error("Malformed block record");
1740 if (Code == bitc::DEFINE_ABBREV) {
1741 Stream.ReadAbbrevRecord();
1746 switch (Stream.ReadRecord(Code, Record)) {
1747 default: break; // Default behavior, ignore unknown content.
1748 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1749 if (Record.size() < 1)
1750 return Error("Malformed MODULE_CODE_VERSION");
1751 // Only version #0 is supported so far.
1753 return Error("Unknown bitstream version!");
1755 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1757 if (ConvertToString(Record, 0, S))
1758 return Error("Invalid MODULE_CODE_TRIPLE record");
1766 return Error("Premature end of bitstream");
1769 bool BitcodeReader::ParseTriple(std::string &Triple) {
1770 if (Buffer->getBufferSize() & 3)
1771 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1773 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1774 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1776 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1777 // The magic number is 0x0B17C0DE stored in little endian.
1778 if (isBitcodeWrapper(BufPtr, BufEnd))
1779 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1780 return Error("Invalid bitcode wrapper header");
1782 StreamFile.init(BufPtr, BufEnd);
1783 Stream.init(StreamFile);
1785 // Sniff for the signature.
1786 if (Stream.Read(8) != 'B' ||
1787 Stream.Read(8) != 'C' ||
1788 Stream.Read(4) != 0x0 ||
1789 Stream.Read(4) != 0xC ||
1790 Stream.Read(4) != 0xE ||
1791 Stream.Read(4) != 0xD)
1792 return Error("Invalid bitcode signature");
1794 // We expect a number of well-defined blocks, though we don't necessarily
1795 // need to understand them all.
1796 while (!Stream.AtEndOfStream()) {
1797 unsigned Code = Stream.ReadCode();
1799 if (Code != bitc::ENTER_SUBBLOCK)
1800 return Error("Invalid record at top-level");
1802 unsigned BlockID = Stream.ReadSubBlockID();
1804 // We only know the MODULE subblock ID.
1806 case bitc::MODULE_BLOCK_ID:
1807 if (ParseModuleTriple(Triple))
1811 if (Stream.SkipBlock())
1812 return Error("Malformed block record");
1820 /// ParseMetadataAttachment - Parse metadata attachments.
1821 bool BitcodeReader::ParseMetadataAttachment() {
1822 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1823 return Error("Malformed block record");
1825 SmallVector<uint64_t, 64> Record;
1827 unsigned Code = Stream.ReadCode();
1828 if (Code == bitc::END_BLOCK) {
1829 if (Stream.ReadBlockEnd())
1830 return Error("Error at end of PARAMATTR block");
1833 if (Code == bitc::DEFINE_ABBREV) {
1834 Stream.ReadAbbrevRecord();
1837 // Read a metadata attachment record.
1839 switch (Stream.ReadRecord(Code, Record)) {
1840 default: // Default behavior: ignore.
1842 case bitc::METADATA_ATTACHMENT: {
1843 unsigned RecordLength = Record.size();
1844 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1845 return Error ("Invalid METADATA_ATTACHMENT reader!");
1846 Instruction *Inst = InstructionList[Record[0]];
1847 for (unsigned i = 1; i != RecordLength; i = i+2) {
1848 unsigned Kind = Record[i];
1849 DenseMap<unsigned, unsigned>::iterator I =
1850 MDKindMap.find(Kind);
1851 if (I == MDKindMap.end())
1852 return Error("Invalid metadata kind ID");
1853 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1854 Inst->setMetadata(I->second, cast<MDNode>(Node));
1863 /// ParseFunctionBody - Lazily parse the specified function body block.
1864 bool BitcodeReader::ParseFunctionBody(Function *F) {
1865 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1866 return Error("Malformed block record");
1868 InstructionList.clear();
1869 unsigned ModuleValueListSize = ValueList.size();
1870 unsigned ModuleMDValueListSize = MDValueList.size();
1872 // Add all the function arguments to the value table.
1873 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1874 ValueList.push_back(I);
1876 unsigned NextValueNo = ValueList.size();
1877 BasicBlock *CurBB = 0;
1878 unsigned CurBBNo = 0;
1882 // Read all the records.
1883 SmallVector<uint64_t, 64> Record;
1885 unsigned Code = Stream.ReadCode();
1886 if (Code == bitc::END_BLOCK) {
1887 if (Stream.ReadBlockEnd())
1888 return Error("Error at end of function block");
1892 if (Code == bitc::ENTER_SUBBLOCK) {
1893 switch (Stream.ReadSubBlockID()) {
1894 default: // Skip unknown content.
1895 if (Stream.SkipBlock())
1896 return Error("Malformed block record");
1898 case bitc::CONSTANTS_BLOCK_ID:
1899 if (ParseConstants()) return true;
1900 NextValueNo = ValueList.size();
1902 case bitc::VALUE_SYMTAB_BLOCK_ID:
1903 if (ParseValueSymbolTable()) return true;
1905 case bitc::METADATA_ATTACHMENT_ID:
1906 if (ParseMetadataAttachment()) return true;
1908 case bitc::METADATA_BLOCK_ID:
1909 if (ParseMetadata()) return true;
1915 if (Code == bitc::DEFINE_ABBREV) {
1916 Stream.ReadAbbrevRecord();
1923 unsigned BitCode = Stream.ReadRecord(Code, Record);
1925 default: // Default behavior: reject
1926 return Error("Unknown instruction");
1927 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1928 if (Record.size() < 1 || Record[0] == 0)
1929 return Error("Invalid DECLAREBLOCKS record");
1930 // Create all the basic blocks for the function.
1931 FunctionBBs.resize(Record[0]);
1932 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1933 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1934 CurBB = FunctionBBs[0];
1937 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1938 // This record indicates that the last instruction is at the same
1939 // location as the previous instruction with a location.
1942 // Get the last instruction emitted.
1943 if (CurBB && !CurBB->empty())
1945 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1946 !FunctionBBs[CurBBNo-1]->empty())
1947 I = &FunctionBBs[CurBBNo-1]->back();
1949 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1950 I->setDebugLoc(LastLoc);
1954 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
1955 I = 0; // Get the last instruction emitted.
1956 if (CurBB && !CurBB->empty())
1958 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1959 !FunctionBBs[CurBBNo-1]->empty())
1960 I = &FunctionBBs[CurBBNo-1]->back();
1961 if (I == 0 || Record.size() < 4)
1962 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1964 unsigned Line = Record[0], Col = Record[1];
1965 unsigned ScopeID = Record[2], IAID = Record[3];
1967 MDNode *Scope = 0, *IA = 0;
1968 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1969 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1970 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1971 I->setDebugLoc(LastLoc);
1976 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1979 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1980 getValue(Record, OpNum, LHS->getType(), RHS) ||
1981 OpNum+1 > Record.size())
1982 return Error("Invalid BINOP record");
1984 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1985 if (Opc == -1) return Error("Invalid BINOP record");
1986 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1987 InstructionList.push_back(I);
1988 if (OpNum < Record.size()) {
1989 if (Opc == Instruction::Add ||
1990 Opc == Instruction::Sub ||
1991 Opc == Instruction::Mul ||
1992 Opc == Instruction::Shl) {
1993 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1994 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1995 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1996 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1997 } else if (Opc == Instruction::SDiv ||
1998 Opc == Instruction::UDiv ||
1999 Opc == Instruction::LShr ||
2000 Opc == Instruction::AShr) {
2001 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2002 cast<BinaryOperator>(I)->setIsExact(true);
2007 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2010 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2011 OpNum+2 != Record.size())
2012 return Error("Invalid CAST record");
2014 Type *ResTy = getTypeByID(Record[OpNum]);
2015 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2016 if (Opc == -1 || ResTy == 0)
2017 return Error("Invalid CAST record");
2018 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2019 InstructionList.push_back(I);
2022 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2023 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2026 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2027 return Error("Invalid GEP record");
2029 SmallVector<Value*, 16> GEPIdx;
2030 while (OpNum != Record.size()) {
2032 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2033 return Error("Invalid GEP record");
2034 GEPIdx.push_back(Op);
2037 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2038 InstructionList.push_back(I);
2039 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2040 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2044 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2045 // EXTRACTVAL: [opty, opval, n x indices]
2048 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2049 return Error("Invalid EXTRACTVAL record");
2051 SmallVector<unsigned, 4> EXTRACTVALIdx;
2052 for (unsigned RecSize = Record.size();
2053 OpNum != RecSize; ++OpNum) {
2054 uint64_t Index = Record[OpNum];
2055 if ((unsigned)Index != Index)
2056 return Error("Invalid EXTRACTVAL index");
2057 EXTRACTVALIdx.push_back((unsigned)Index);
2060 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2061 InstructionList.push_back(I);
2065 case bitc::FUNC_CODE_INST_INSERTVAL: {
2066 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2069 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2070 return Error("Invalid INSERTVAL record");
2072 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2073 return Error("Invalid INSERTVAL record");
2075 SmallVector<unsigned, 4> INSERTVALIdx;
2076 for (unsigned RecSize = Record.size();
2077 OpNum != RecSize; ++OpNum) {
2078 uint64_t Index = Record[OpNum];
2079 if ((unsigned)Index != Index)
2080 return Error("Invalid INSERTVAL index");
2081 INSERTVALIdx.push_back((unsigned)Index);
2084 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2085 InstructionList.push_back(I);
2089 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2090 // obsolete form of select
2091 // handles select i1 ... in old bitcode
2093 Value *TrueVal, *FalseVal, *Cond;
2094 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2095 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2096 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2097 return Error("Invalid SELECT record");
2099 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2100 InstructionList.push_back(I);
2104 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2105 // new form of select
2106 // handles select i1 or select [N x i1]
2108 Value *TrueVal, *FalseVal, *Cond;
2109 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2110 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2111 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2112 return Error("Invalid SELECT record");
2114 // select condition can be either i1 or [N x i1]
2115 if (VectorType* vector_type =
2116 dyn_cast<VectorType>(Cond->getType())) {
2118 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2119 return Error("Invalid SELECT condition type");
2122 if (Cond->getType() != Type::getInt1Ty(Context))
2123 return Error("Invalid SELECT condition type");
2126 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2127 InstructionList.push_back(I);
2131 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2134 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2135 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2136 return Error("Invalid EXTRACTELT record");
2137 I = ExtractElementInst::Create(Vec, Idx);
2138 InstructionList.push_back(I);
2142 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2144 Value *Vec, *Elt, *Idx;
2145 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2146 getValue(Record, OpNum,
2147 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2148 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2149 return Error("Invalid INSERTELT record");
2150 I = InsertElementInst::Create(Vec, Elt, Idx);
2151 InstructionList.push_back(I);
2155 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2157 Value *Vec1, *Vec2, *Mask;
2158 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2159 getValue(Record, OpNum, Vec1->getType(), Vec2))
2160 return Error("Invalid SHUFFLEVEC record");
2162 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2163 return Error("Invalid SHUFFLEVEC record");
2164 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2165 InstructionList.push_back(I);
2169 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2170 // Old form of ICmp/FCmp returning bool
2171 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2172 // both legal on vectors but had different behaviour.
2173 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2174 // FCmp/ICmp returning bool or vector of bool
2178 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2179 getValue(Record, OpNum, LHS->getType(), RHS) ||
2180 OpNum+1 != Record.size())
2181 return Error("Invalid CMP record");
2183 if (LHS->getType()->isFPOrFPVectorTy())
2184 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2186 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2187 InstructionList.push_back(I);
2191 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2193 unsigned Size = Record.size();
2195 I = ReturnInst::Create(Context);
2196 InstructionList.push_back(I);
2202 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2203 return Error("Invalid RET record");
2204 if (OpNum != Record.size())
2205 return Error("Invalid RET record");
2207 I = ReturnInst::Create(Context, Op);
2208 InstructionList.push_back(I);
2211 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2212 if (Record.size() != 1 && Record.size() != 3)
2213 return Error("Invalid BR record");
2214 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2216 return Error("Invalid BR record");
2218 if (Record.size() == 1) {
2219 I = BranchInst::Create(TrueDest);
2220 InstructionList.push_back(I);
2223 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2224 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2225 if (FalseDest == 0 || Cond == 0)
2226 return Error("Invalid BR record");
2227 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2228 InstructionList.push_back(I);
2232 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2233 if (Record.size() < 3 || (Record.size() & 1) == 0)
2234 return Error("Invalid SWITCH record");
2235 Type *OpTy = getTypeByID(Record[0]);
2236 Value *Cond = getFnValueByID(Record[1], OpTy);
2237 BasicBlock *Default = getBasicBlock(Record[2]);
2238 if (OpTy == 0 || Cond == 0 || Default == 0)
2239 return Error("Invalid SWITCH record");
2240 unsigned NumCases = (Record.size()-3)/2;
2241 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2242 InstructionList.push_back(SI);
2243 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2244 ConstantInt *CaseVal =
2245 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2246 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2247 if (CaseVal == 0 || DestBB == 0) {
2249 return Error("Invalid SWITCH record!");
2251 SI->addCase(CaseVal, DestBB);
2256 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2257 if (Record.size() < 2)
2258 return Error("Invalid INDIRECTBR record");
2259 Type *OpTy = getTypeByID(Record[0]);
2260 Value *Address = getFnValueByID(Record[1], OpTy);
2261 if (OpTy == 0 || Address == 0)
2262 return Error("Invalid INDIRECTBR record");
2263 unsigned NumDests = Record.size()-2;
2264 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2265 InstructionList.push_back(IBI);
2266 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2267 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2268 IBI->addDestination(DestBB);
2271 return Error("Invalid INDIRECTBR record!");
2278 case bitc::FUNC_CODE_INST_INVOKE: {
2279 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2280 if (Record.size() < 4) return Error("Invalid INVOKE record");
2281 AttrListPtr PAL = getAttributes(Record[0]);
2282 unsigned CCInfo = Record[1];
2283 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2284 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2288 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2289 return Error("Invalid INVOKE record");
2291 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2292 FunctionType *FTy = !CalleeTy ? 0 :
2293 dyn_cast<FunctionType>(CalleeTy->getElementType());
2295 // Check that the right number of fixed parameters are here.
2296 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2297 Record.size() < OpNum+FTy->getNumParams())
2298 return Error("Invalid INVOKE record");
2300 SmallVector<Value*, 16> Ops;
2301 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2302 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2303 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2306 if (!FTy->isVarArg()) {
2307 if (Record.size() != OpNum)
2308 return Error("Invalid INVOKE record");
2310 // Read type/value pairs for varargs params.
2311 while (OpNum != Record.size()) {
2313 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2314 return Error("Invalid INVOKE record");
2319 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2320 InstructionList.push_back(I);
2321 cast<InvokeInst>(I)->setCallingConv(
2322 static_cast<CallingConv::ID>(CCInfo));
2323 cast<InvokeInst>(I)->setAttributes(PAL);
2326 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2329 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2330 return Error("Invalid RESUME record");
2331 I = ResumeInst::Create(Val);
2332 InstructionList.push_back(I);
2335 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2336 I = new UnwindInst(Context);
2337 InstructionList.push_back(I);
2339 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2340 I = new UnreachableInst(Context);
2341 InstructionList.push_back(I);
2343 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2344 if (Record.size() < 1 || ((Record.size()-1)&1))
2345 return Error("Invalid PHI record");
2346 Type *Ty = getTypeByID(Record[0]);
2347 if (!Ty) return Error("Invalid PHI record");
2349 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2350 InstructionList.push_back(PN);
2352 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2353 Value *V = getFnValueByID(Record[1+i], Ty);
2354 BasicBlock *BB = getBasicBlock(Record[2+i]);
2355 if (!V || !BB) return Error("Invalid PHI record");
2356 PN->addIncoming(V, BB);
2362 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2363 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2365 if (Record.size() < 4)
2366 return Error("Invalid LANDINGPAD record");
2367 Type *Ty = getTypeByID(Record[Idx++]);
2368 if (!Ty) return Error("Invalid LANDINGPAD record");
2370 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2371 return Error("Invalid LANDINGPAD record");
2373 bool IsCleanup = !!Record[Idx++];
2374 unsigned NumClauses = Record[Idx++];
2375 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2376 LP->setCleanup(IsCleanup);
2377 for (unsigned J = 0; J != NumClauses; ++J) {
2378 LandingPadInst::ClauseType CT =
2379 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2382 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2384 return Error("Invalid LANDINGPAD record");
2387 assert((CT != LandingPadInst::Catch ||
2388 !isa<ArrayType>(Val->getType())) &&
2389 "Catch clause has a invalid type!");
2390 assert((CT != LandingPadInst::Filter ||
2391 isa<ArrayType>(Val->getType())) &&
2392 "Filter clause has invalid type!");
2397 InstructionList.push_back(I);
2401 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2402 if (Record.size() != 4)
2403 return Error("Invalid ALLOCA record");
2405 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2406 Type *OpTy = getTypeByID(Record[1]);
2407 Value *Size = getFnValueByID(Record[2], OpTy);
2408 unsigned Align = Record[3];
2409 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2410 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2411 InstructionList.push_back(I);
2414 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2417 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2418 OpNum+2 != Record.size())
2419 return Error("Invalid LOAD record");
2421 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2422 InstructionList.push_back(I);
2425 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2426 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2429 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2430 OpNum+4 != Record.size())
2431 return Error("Invalid LOADATOMIC record");
2434 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2435 if (Ordering == NotAtomic || Ordering == Release ||
2436 Ordering == AcquireRelease)
2437 return Error("Invalid LOADATOMIC record");
2438 if (Ordering != NotAtomic && Record[OpNum] == 0)
2439 return Error("Invalid LOADATOMIC record");
2440 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2442 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2443 Ordering, SynchScope);
2444 InstructionList.push_back(I);
2447 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2450 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2451 getValue(Record, OpNum,
2452 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2453 OpNum+2 != Record.size())
2454 return Error("Invalid STORE record");
2456 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2457 InstructionList.push_back(I);
2460 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2461 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2464 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2465 getValue(Record, OpNum,
2466 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2467 OpNum+4 != Record.size())
2468 return Error("Invalid STOREATOMIC record");
2470 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2471 if (Ordering == NotAtomic || Ordering == Acquire ||
2472 Ordering == AcquireRelease)
2473 return Error("Invalid STOREATOMIC record");
2474 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2475 if (Ordering != NotAtomic && Record[OpNum] == 0)
2476 return Error("Invalid STOREATOMIC record");
2478 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2479 Ordering, SynchScope);
2480 InstructionList.push_back(I);
2483 case bitc::FUNC_CODE_INST_CMPXCHG: {
2484 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2486 Value *Ptr, *Cmp, *New;
2487 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2488 getValue(Record, OpNum,
2489 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2490 getValue(Record, OpNum,
2491 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2492 OpNum+3 != Record.size())
2493 return Error("Invalid CMPXCHG record");
2494 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2495 if (Ordering == NotAtomic || Ordering == Unordered)
2496 return Error("Invalid CMPXCHG record");
2497 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2498 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2499 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2500 InstructionList.push_back(I);
2503 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2504 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2507 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2508 getValue(Record, OpNum,
2509 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2510 OpNum+4 != Record.size())
2511 return Error("Invalid ATOMICRMW record");
2512 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2513 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2514 Operation > AtomicRMWInst::LAST_BINOP)
2515 return Error("Invalid ATOMICRMW record");
2516 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2517 if (Ordering == NotAtomic || Ordering == Unordered)
2518 return Error("Invalid ATOMICRMW record");
2519 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2520 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2521 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2522 InstructionList.push_back(I);
2525 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2526 if (2 != Record.size())
2527 return Error("Invalid FENCE record");
2528 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2529 if (Ordering == NotAtomic || Ordering == Unordered ||
2530 Ordering == Monotonic)
2531 return Error("Invalid FENCE record");
2532 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2533 I = new FenceInst(Context, Ordering, SynchScope);
2534 InstructionList.push_back(I);
2537 case bitc::FUNC_CODE_INST_CALL: {
2538 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2539 if (Record.size() < 3)
2540 return Error("Invalid CALL record");
2542 AttrListPtr PAL = getAttributes(Record[0]);
2543 unsigned CCInfo = Record[1];
2547 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2548 return Error("Invalid CALL record");
2550 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2551 FunctionType *FTy = 0;
2552 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2553 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2554 return Error("Invalid CALL record");
2556 SmallVector<Value*, 16> Args;
2557 // Read the fixed params.
2558 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2559 if (FTy->getParamType(i)->isLabelTy())
2560 Args.push_back(getBasicBlock(Record[OpNum]));
2562 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2563 if (Args.back() == 0) return Error("Invalid CALL record");
2566 // Read type/value pairs for varargs params.
2567 if (!FTy->isVarArg()) {
2568 if (OpNum != Record.size())
2569 return Error("Invalid CALL record");
2571 while (OpNum != Record.size()) {
2573 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2574 return Error("Invalid CALL record");
2579 I = CallInst::Create(Callee, Args);
2580 InstructionList.push_back(I);
2581 cast<CallInst>(I)->setCallingConv(
2582 static_cast<CallingConv::ID>(CCInfo>>1));
2583 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2584 cast<CallInst>(I)->setAttributes(PAL);
2587 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2588 if (Record.size() < 3)
2589 return Error("Invalid VAARG record");
2590 Type *OpTy = getTypeByID(Record[0]);
2591 Value *Op = getFnValueByID(Record[1], OpTy);
2592 Type *ResTy = getTypeByID(Record[2]);
2593 if (!OpTy || !Op || !ResTy)
2594 return Error("Invalid VAARG record");
2595 I = new VAArgInst(Op, ResTy);
2596 InstructionList.push_back(I);
2601 // Add instruction to end of current BB. If there is no current BB, reject
2605 return Error("Invalid instruction with no BB");
2607 CurBB->getInstList().push_back(I);
2609 // If this was a terminator instruction, move to the next block.
2610 if (isa<TerminatorInst>(I)) {
2612 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2615 // Non-void values get registered in the value table for future use.
2616 if (I && !I->getType()->isVoidTy())
2617 ValueList.AssignValue(I, NextValueNo++);
2620 // Check the function list for unresolved values.
2621 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2622 if (A->getParent() == 0) {
2623 // We found at least one unresolved value. Nuke them all to avoid leaks.
2624 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2625 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2626 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2630 return Error("Never resolved value found in function!");
2634 // FIXME: Check for unresolved forward-declared metadata references
2635 // and clean up leaks.
2637 // See if anything took the address of blocks in this function. If so,
2638 // resolve them now.
2639 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2640 BlockAddrFwdRefs.find(F);
2641 if (BAFRI != BlockAddrFwdRefs.end()) {
2642 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2643 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2644 unsigned BlockIdx = RefList[i].first;
2645 if (BlockIdx >= FunctionBBs.size())
2646 return Error("Invalid blockaddress block #");
2648 GlobalVariable *FwdRef = RefList[i].second;
2649 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2650 FwdRef->eraseFromParent();
2653 BlockAddrFwdRefs.erase(BAFRI);
2656 // Trim the value list down to the size it was before we parsed this function.
2657 ValueList.shrinkTo(ModuleValueListSize);
2658 MDValueList.shrinkTo(ModuleMDValueListSize);
2659 std::vector<BasicBlock*>().swap(FunctionBBs);
2663 //===----------------------------------------------------------------------===//
2664 // GVMaterializer implementation
2665 //===----------------------------------------------------------------------===//
2668 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2669 if (const Function *F = dyn_cast<Function>(GV)) {
2670 return F->isDeclaration() &&
2671 DeferredFunctionInfo.count(const_cast<Function*>(F));
2676 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2677 Function *F = dyn_cast<Function>(GV);
2678 // If it's not a function or is already material, ignore the request.
2679 if (!F || !F->isMaterializable()) return false;
2681 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2682 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2684 // Move the bit stream to the saved position of the deferred function body.
2685 Stream.JumpToBit(DFII->second);
2687 if (ParseFunctionBody(F)) {
2688 if (ErrInfo) *ErrInfo = ErrorString;
2692 // Upgrade any old intrinsic calls in the function.
2693 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2694 E = UpgradedIntrinsics.end(); I != E; ++I) {
2695 if (I->first != I->second) {
2696 for (Value::use_iterator UI = I->first->use_begin(),
2697 UE = I->first->use_end(); UI != UE; ) {
2698 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2699 UpgradeIntrinsicCall(CI, I->second);
2707 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2708 const Function *F = dyn_cast<Function>(GV);
2709 if (!F || F->isDeclaration())
2711 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2714 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2715 Function *F = dyn_cast<Function>(GV);
2716 // If this function isn't dematerializable, this is a noop.
2717 if (!F || !isDematerializable(F))
2720 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2722 // Just forget the function body, we can remat it later.
2727 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2728 assert(M == TheModule &&
2729 "Can only Materialize the Module this BitcodeReader is attached to.");
2730 // Iterate over the module, deserializing any functions that are still on
2732 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2734 if (F->isMaterializable() &&
2735 Materialize(F, ErrInfo))
2738 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2739 // delete the old functions to clean up. We can't do this unless the entire
2740 // module is materialized because there could always be another function body
2741 // with calls to the old function.
2742 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2743 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2744 if (I->first != I->second) {
2745 for (Value::use_iterator UI = I->first->use_begin(),
2746 UE = I->first->use_end(); UI != UE; ) {
2747 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2748 UpgradeIntrinsicCall(CI, I->second);
2750 if (!I->first->use_empty())
2751 I->first->replaceAllUsesWith(I->second);
2752 I->first->eraseFromParent();
2755 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2761 //===----------------------------------------------------------------------===//
2762 // External interface
2763 //===----------------------------------------------------------------------===//
2765 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2767 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2768 LLVMContext& Context,
2769 std::string *ErrMsg) {
2770 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2771 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2772 M->setMaterializer(R);
2773 if (R->ParseBitcodeInto(M)) {
2775 *ErrMsg = R->getErrorString();
2777 delete M; // Also deletes R.
2780 // Have the BitcodeReader dtor delete 'Buffer'.
2781 R->setBufferOwned(true);
2785 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2786 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2787 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2788 std::string *ErrMsg){
2789 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2792 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2793 // there was an error.
2794 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2796 // Read in the entire module, and destroy the BitcodeReader.
2797 if (M->MaterializeAllPermanently(ErrMsg)) {
2802 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2803 // written. We must defer until the Module has been fully materialized.
2808 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2809 LLVMContext& Context,
2810 std::string *ErrMsg) {
2811 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2812 // Don't let the BitcodeReader dtor delete 'Buffer'.
2813 R->setBufferOwned(false);
2815 std::string Triple("");
2816 if (R->ParseTriple(Triple))
2818 *ErrMsg = R->getErrorString();