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/DataStream.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/OperandTraits.h"
31 void BitcodeReader::materializeForwardReferencedFunctions() {
32 while (!BlockAddrFwdRefs.empty()) {
33 Function *F = BlockAddrFwdRefs.begin()->first;
38 void BitcodeReader::FreeState() {
42 std::vector<Type*>().swap(TypeList);
46 std::vector<AttrListPtr>().swap(MAttributes);
47 std::vector<BasicBlock*>().swap(FunctionBBs);
48 std::vector<Function*>().swap(FunctionsWithBodies);
49 DeferredFunctionInfo.clear();
53 //===----------------------------------------------------------------------===//
54 // Helper functions to implement forward reference resolution, etc.
55 //===----------------------------------------------------------------------===//
57 /// ConvertToString - Convert a string from a record into an std::string, return
59 template<typename StrTy>
60 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
62 if (Idx > Record.size())
65 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
66 Result += (char)Record[i];
70 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
72 default: // Map unknown/new linkages to external
73 case 0: return GlobalValue::ExternalLinkage;
74 case 1: return GlobalValue::WeakAnyLinkage;
75 case 2: return GlobalValue::AppendingLinkage;
76 case 3: return GlobalValue::InternalLinkage;
77 case 4: return GlobalValue::LinkOnceAnyLinkage;
78 case 5: return GlobalValue::DLLImportLinkage;
79 case 6: return GlobalValue::DLLExportLinkage;
80 case 7: return GlobalValue::ExternalWeakLinkage;
81 case 8: return GlobalValue::CommonLinkage;
82 case 9: return GlobalValue::PrivateLinkage;
83 case 10: return GlobalValue::WeakODRLinkage;
84 case 11: return GlobalValue::LinkOnceODRLinkage;
85 case 12: return GlobalValue::AvailableExternallyLinkage;
86 case 13: return GlobalValue::LinkerPrivateLinkage;
87 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
88 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
92 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
94 default: // Map unknown visibilities to default.
95 case 0: return GlobalValue::DefaultVisibility;
96 case 1: return GlobalValue::HiddenVisibility;
97 case 2: return GlobalValue::ProtectedVisibility;
101 static int GetDecodedCastOpcode(unsigned Val) {
104 case bitc::CAST_TRUNC : return Instruction::Trunc;
105 case bitc::CAST_ZEXT : return Instruction::ZExt;
106 case bitc::CAST_SEXT : return Instruction::SExt;
107 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
108 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
109 case bitc::CAST_UITOFP : return Instruction::UIToFP;
110 case bitc::CAST_SITOFP : return Instruction::SIToFP;
111 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
112 case bitc::CAST_FPEXT : return Instruction::FPExt;
113 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
114 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
115 case bitc::CAST_BITCAST : return Instruction::BitCast;
118 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
121 case bitc::BINOP_ADD:
122 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
123 case bitc::BINOP_SUB:
124 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
125 case bitc::BINOP_MUL:
126 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
127 case bitc::BINOP_UDIV: return Instruction::UDiv;
128 case bitc::BINOP_SDIV:
129 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
130 case bitc::BINOP_UREM: return Instruction::URem;
131 case bitc::BINOP_SREM:
132 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
133 case bitc::BINOP_SHL: return Instruction::Shl;
134 case bitc::BINOP_LSHR: return Instruction::LShr;
135 case bitc::BINOP_ASHR: return Instruction::AShr;
136 case bitc::BINOP_AND: return Instruction::And;
137 case bitc::BINOP_OR: return Instruction::Or;
138 case bitc::BINOP_XOR: return Instruction::Xor;
142 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
144 default: return AtomicRMWInst::BAD_BINOP;
145 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
146 case bitc::RMW_ADD: return AtomicRMWInst::Add;
147 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
148 case bitc::RMW_AND: return AtomicRMWInst::And;
149 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
150 case bitc::RMW_OR: return AtomicRMWInst::Or;
151 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
152 case bitc::RMW_MAX: return AtomicRMWInst::Max;
153 case bitc::RMW_MIN: return AtomicRMWInst::Min;
154 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
155 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
159 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
161 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
162 case bitc::ORDERING_UNORDERED: return Unordered;
163 case bitc::ORDERING_MONOTONIC: return Monotonic;
164 case bitc::ORDERING_ACQUIRE: return Acquire;
165 case bitc::ORDERING_RELEASE: return Release;
166 case bitc::ORDERING_ACQREL: return AcquireRelease;
167 default: // Map unknown orderings to sequentially-consistent.
168 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
172 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
174 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
175 default: // Map unknown scopes to cross-thread.
176 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
182 /// @brief A class for maintaining the slot number definition
183 /// as a placeholder for the actual definition for forward constants defs.
184 class ConstantPlaceHolder : public ConstantExpr {
185 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
187 // allocate space for exactly one operand
188 void *operator new(size_t s) {
189 return User::operator new(s, 1);
191 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
192 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
193 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
196 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
197 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
198 static bool classof(const Value *V) {
199 return isa<ConstantExpr>(V) &&
200 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
204 /// Provide fast operand accessors
205 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
209 // FIXME: can we inherit this from ConstantExpr?
211 struct OperandTraits<ConstantPlaceHolder> :
212 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
217 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
226 WeakVH &OldV = ValuePtrs[Idx];
232 // Handle constants and non-constants (e.g. instrs) differently for
234 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
235 ResolveConstants.push_back(std::make_pair(PHC, Idx));
238 // If there was a forward reference to this value, replace it.
239 Value *PrevVal = OldV;
240 OldV->replaceAllUsesWith(V);
246 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
251 if (Value *V = ValuePtrs[Idx]) {
252 assert(Ty == V->getType() && "Type mismatch in constant table!");
253 return cast<Constant>(V);
256 // Create and return a placeholder, which will later be RAUW'd.
257 Constant *C = new ConstantPlaceHolder(Ty, Context);
262 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
266 if (Value *V = ValuePtrs[Idx]) {
267 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
271 // No type specified, must be invalid reference.
272 if (Ty == 0) return 0;
274 // Create and return a placeholder, which will later be RAUW'd.
275 Value *V = new Argument(Ty);
280 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
281 /// resolves any forward references. The idea behind this is that we sometimes
282 /// get constants (such as large arrays) which reference *many* forward ref
283 /// constants. Replacing each of these causes a lot of thrashing when
284 /// building/reuniquing the constant. Instead of doing this, we look at all the
285 /// uses and rewrite all the place holders at once for any constant that uses
287 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
288 // Sort the values by-pointer so that they are efficient to look up with a
290 std::sort(ResolveConstants.begin(), ResolveConstants.end());
292 SmallVector<Constant*, 64> NewOps;
294 while (!ResolveConstants.empty()) {
295 Value *RealVal = operator[](ResolveConstants.back().second);
296 Constant *Placeholder = ResolveConstants.back().first;
297 ResolveConstants.pop_back();
299 // Loop over all users of the placeholder, updating them to reference the
300 // new value. If they reference more than one placeholder, update them all
302 while (!Placeholder->use_empty()) {
303 Value::use_iterator UI = Placeholder->use_begin();
306 // If the using object isn't uniqued, just update the operands. This
307 // handles instructions and initializers for global variables.
308 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
309 UI.getUse().set(RealVal);
313 // Otherwise, we have a constant that uses the placeholder. Replace that
314 // constant with a new constant that has *all* placeholder uses updated.
315 Constant *UserC = cast<Constant>(U);
316 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
319 if (!isa<ConstantPlaceHolder>(*I)) {
320 // Not a placeholder reference.
322 } else if (*I == Placeholder) {
323 // Common case is that it just references this one placeholder.
326 // Otherwise, look up the placeholder in ResolveConstants.
327 ResolveConstantsTy::iterator It =
328 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
329 std::pair<Constant*, unsigned>(cast<Constant>(*I),
331 assert(It != ResolveConstants.end() && It->first == *I);
332 NewOp = operator[](It->second);
335 NewOps.push_back(cast<Constant>(NewOp));
338 // Make the new constant.
340 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
341 NewC = ConstantArray::get(UserCA->getType(), NewOps);
342 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
343 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
344 } else if (isa<ConstantVector>(UserC)) {
345 NewC = ConstantVector::get(NewOps);
347 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
348 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
351 UserC->replaceAllUsesWith(NewC);
352 UserC->destroyConstant();
356 // Update all ValueHandles, they should be the only users at this point.
357 Placeholder->replaceAllUsesWith(RealVal);
362 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
371 WeakVH &OldV = MDValuePtrs[Idx];
377 // If there was a forward reference to this value, replace it.
378 MDNode *PrevVal = cast<MDNode>(OldV);
379 OldV->replaceAllUsesWith(V);
380 MDNode::deleteTemporary(PrevVal);
381 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
383 MDValuePtrs[Idx] = V;
386 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
390 if (Value *V = MDValuePtrs[Idx]) {
391 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
395 // Create and return a placeholder, which will later be RAUW'd.
396 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
397 MDValuePtrs[Idx] = V;
401 Type *BitcodeReader::getTypeByID(unsigned ID) {
402 // The type table size is always specified correctly.
403 if (ID >= TypeList.size())
406 if (Type *Ty = TypeList[ID])
409 // If we have a forward reference, the only possible case is when it is to a
410 // named struct. Just create a placeholder for now.
411 return TypeList[ID] = StructType::create(Context);
415 //===----------------------------------------------------------------------===//
416 // Functions for parsing blocks from the bitcode file
417 //===----------------------------------------------------------------------===//
419 bool BitcodeReader::ParseAttributeBlock() {
420 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
421 return Error("Malformed block record");
423 if (!MAttributes.empty())
424 return Error("Multiple PARAMATTR blocks found!");
426 SmallVector<uint64_t, 64> Record;
428 SmallVector<AttributeWithIndex, 8> Attrs;
430 // Read all the records.
432 unsigned Code = Stream.ReadCode();
433 if (Code == bitc::END_BLOCK) {
434 if (Stream.ReadBlockEnd())
435 return Error("Error at end of PARAMATTR block");
439 if (Code == bitc::ENTER_SUBBLOCK) {
440 // No known subblocks, always skip them.
441 Stream.ReadSubBlockID();
442 if (Stream.SkipBlock())
443 return Error("Malformed block record");
447 if (Code == bitc::DEFINE_ABBREV) {
448 Stream.ReadAbbrevRecord();
454 switch (Stream.ReadRecord(Code, Record)) {
455 default: // Default behavior: ignore.
457 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
458 if (Record.size() & 1)
459 return Error("Invalid ENTRY record");
461 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
462 // FIXME: remove in LLVM 3.0
463 // The alignment is stored as a 16-bit raw value from bits 31--16.
464 // We shift the bits above 31 down by 11 bits.
466 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
467 if (Alignment && !isPowerOf2_32(Alignment))
468 return Error("Alignment is not a power of two.");
470 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
472 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
474 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
476 Record[i+1] = ReconstitutedAttr.Raw();
479 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
480 if (Attributes(Record[i+1]) != Attribute::None)
481 Attrs.push_back(AttributeWithIndex::get(Record[i],
482 Attributes(Record[i+1])));
485 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
493 bool BitcodeReader::ParseTypeTable() {
494 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
495 return Error("Malformed block record");
497 return ParseTypeTableBody();
500 bool BitcodeReader::ParseTypeTableBody() {
501 if (!TypeList.empty())
502 return Error("Multiple TYPE_BLOCKs found!");
504 SmallVector<uint64_t, 64> Record;
505 unsigned NumRecords = 0;
507 SmallString<64> TypeName;
509 // Read all the records for this type table.
511 unsigned Code = Stream.ReadCode();
512 if (Code == bitc::END_BLOCK) {
513 if (NumRecords != TypeList.size())
514 return Error("Invalid type forward reference in TYPE_BLOCK");
515 if (Stream.ReadBlockEnd())
516 return Error("Error at end of type table block");
520 if (Code == bitc::ENTER_SUBBLOCK) {
521 // No known subblocks, always skip them.
522 Stream.ReadSubBlockID();
523 if (Stream.SkipBlock())
524 return Error("Malformed block record");
528 if (Code == bitc::DEFINE_ABBREV) {
529 Stream.ReadAbbrevRecord();
536 switch (Stream.ReadRecord(Code, Record)) {
537 default: return Error("unknown type in type table");
538 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
539 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
540 // type list. This allows us to reserve space.
541 if (Record.size() < 1)
542 return Error("Invalid TYPE_CODE_NUMENTRY record");
543 TypeList.resize(Record[0]);
545 case bitc::TYPE_CODE_VOID: // VOID
546 ResultTy = Type::getVoidTy(Context);
548 case bitc::TYPE_CODE_HALF: // HALF
549 ResultTy = Type::getHalfTy(Context);
551 case bitc::TYPE_CODE_FLOAT: // FLOAT
552 ResultTy = Type::getFloatTy(Context);
554 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
555 ResultTy = Type::getDoubleTy(Context);
557 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
558 ResultTy = Type::getX86_FP80Ty(Context);
560 case bitc::TYPE_CODE_FP128: // FP128
561 ResultTy = Type::getFP128Ty(Context);
563 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
564 ResultTy = Type::getPPC_FP128Ty(Context);
566 case bitc::TYPE_CODE_LABEL: // LABEL
567 ResultTy = Type::getLabelTy(Context);
569 case bitc::TYPE_CODE_METADATA: // METADATA
570 ResultTy = Type::getMetadataTy(Context);
572 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
573 ResultTy = Type::getX86_MMXTy(Context);
575 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
576 if (Record.size() < 1)
577 return Error("Invalid Integer type record");
579 ResultTy = IntegerType::get(Context, Record[0]);
581 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
582 // [pointee type, address space]
583 if (Record.size() < 1)
584 return Error("Invalid POINTER type record");
585 unsigned AddressSpace = 0;
586 if (Record.size() == 2)
587 AddressSpace = Record[1];
588 ResultTy = getTypeByID(Record[0]);
589 if (ResultTy == 0) return Error("invalid element type in pointer type");
590 ResultTy = PointerType::get(ResultTy, AddressSpace);
593 case bitc::TYPE_CODE_FUNCTION: {
594 // FUNCTION: [vararg, retty, paramty x N]
595 if (Record.size() < 2)
596 return Error("Invalid FUNCTION type record");
597 SmallVector<Type*, 8> ArgTys;
598 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
599 if (Type *T = getTypeByID(Record[i]))
605 ResultTy = getTypeByID(Record[1]);
606 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
607 return Error("invalid type in function type");
609 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
612 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
613 if (Record.size() < 1)
614 return Error("Invalid STRUCT type record");
615 SmallVector<Type*, 8> EltTys;
616 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
617 if (Type *T = getTypeByID(Record[i]))
622 if (EltTys.size() != Record.size()-1)
623 return Error("invalid type in struct type");
624 ResultTy = StructType::get(Context, EltTys, Record[0]);
627 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
628 if (ConvertToString(Record, 0, TypeName))
629 return Error("Invalid STRUCT_NAME record");
632 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
633 if (Record.size() < 1)
634 return Error("Invalid STRUCT type record");
636 if (NumRecords >= TypeList.size())
637 return Error("invalid TYPE table");
639 // Check to see if this was forward referenced, if so fill in the temp.
640 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
642 Res->setName(TypeName);
643 TypeList[NumRecords] = 0;
644 } else // Otherwise, create a new struct.
645 Res = StructType::create(Context, TypeName);
648 SmallVector<Type*, 8> EltTys;
649 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
650 if (Type *T = getTypeByID(Record[i]))
655 if (EltTys.size() != Record.size()-1)
656 return Error("invalid STRUCT type record");
657 Res->setBody(EltTys, Record[0]);
661 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
662 if (Record.size() != 1)
663 return Error("Invalid OPAQUE type record");
665 if (NumRecords >= TypeList.size())
666 return Error("invalid TYPE table");
668 // Check to see if this was forward referenced, if so fill in the temp.
669 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
671 Res->setName(TypeName);
672 TypeList[NumRecords] = 0;
673 } else // Otherwise, create a new struct with no body.
674 Res = StructType::create(Context, TypeName);
679 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
680 if (Record.size() < 2)
681 return Error("Invalid ARRAY type record");
682 if ((ResultTy = getTypeByID(Record[1])))
683 ResultTy = ArrayType::get(ResultTy, Record[0]);
685 return Error("Invalid ARRAY type element");
687 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
688 if (Record.size() < 2)
689 return Error("Invalid VECTOR type record");
690 if ((ResultTy = getTypeByID(Record[1])))
691 ResultTy = VectorType::get(ResultTy, Record[0]);
693 return Error("Invalid ARRAY type element");
697 if (NumRecords >= TypeList.size())
698 return Error("invalid TYPE table");
699 assert(ResultTy && "Didn't read a type?");
700 assert(TypeList[NumRecords] == 0 && "Already read type?");
701 TypeList[NumRecords++] = ResultTy;
705 bool BitcodeReader::ParseValueSymbolTable() {
706 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
707 return Error("Malformed block record");
709 SmallVector<uint64_t, 64> Record;
711 // Read all the records for this value table.
712 SmallString<128> ValueName;
714 unsigned Code = Stream.ReadCode();
715 if (Code == bitc::END_BLOCK) {
716 if (Stream.ReadBlockEnd())
717 return Error("Error at end of value symbol table block");
720 if (Code == bitc::ENTER_SUBBLOCK) {
721 // No known subblocks, always skip them.
722 Stream.ReadSubBlockID();
723 if (Stream.SkipBlock())
724 return Error("Malformed block record");
728 if (Code == bitc::DEFINE_ABBREV) {
729 Stream.ReadAbbrevRecord();
735 switch (Stream.ReadRecord(Code, Record)) {
736 default: // Default behavior: unknown type.
738 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
739 if (ConvertToString(Record, 1, ValueName))
740 return Error("Invalid VST_ENTRY record");
741 unsigned ValueID = Record[0];
742 if (ValueID >= ValueList.size())
743 return Error("Invalid Value ID in VST_ENTRY record");
744 Value *V = ValueList[ValueID];
746 V->setName(StringRef(ValueName.data(), ValueName.size()));
750 case bitc::VST_CODE_BBENTRY: {
751 if (ConvertToString(Record, 1, ValueName))
752 return Error("Invalid VST_BBENTRY record");
753 BasicBlock *BB = getBasicBlock(Record[0]);
755 return Error("Invalid BB ID in VST_BBENTRY record");
757 BB->setName(StringRef(ValueName.data(), ValueName.size()));
765 bool BitcodeReader::ParseMetadata() {
766 unsigned NextMDValueNo = MDValueList.size();
768 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
769 return Error("Malformed block record");
771 SmallVector<uint64_t, 64> Record;
773 // Read all the records.
775 unsigned Code = Stream.ReadCode();
776 if (Code == bitc::END_BLOCK) {
777 if (Stream.ReadBlockEnd())
778 return Error("Error at end of PARAMATTR block");
782 if (Code == bitc::ENTER_SUBBLOCK) {
783 // No known subblocks, always skip them.
784 Stream.ReadSubBlockID();
785 if (Stream.SkipBlock())
786 return Error("Malformed block record");
790 if (Code == bitc::DEFINE_ABBREV) {
791 Stream.ReadAbbrevRecord();
795 bool IsFunctionLocal = false;
798 Code = Stream.ReadRecord(Code, Record);
800 default: // Default behavior: ignore.
802 case bitc::METADATA_NAME: {
803 // Read named of the named metadata.
804 unsigned NameLength = Record.size();
806 Name.resize(NameLength);
807 for (unsigned i = 0; i != NameLength; ++i)
810 Code = Stream.ReadCode();
812 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
813 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
814 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
816 // Read named metadata elements.
817 unsigned Size = Record.size();
818 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
819 for (unsigned i = 0; i != Size; ++i) {
820 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
822 return Error("Malformed metadata record");
827 case bitc::METADATA_FN_NODE:
828 IsFunctionLocal = true;
830 case bitc::METADATA_NODE: {
831 if (Record.size() % 2 == 1)
832 return Error("Invalid METADATA_NODE record");
834 unsigned Size = Record.size();
835 SmallVector<Value*, 8> Elts;
836 for (unsigned i = 0; i != Size; i += 2) {
837 Type *Ty = getTypeByID(Record[i]);
838 if (!Ty) return Error("Invalid METADATA_NODE record");
839 if (Ty->isMetadataTy())
840 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
841 else if (!Ty->isVoidTy())
842 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
844 Elts.push_back(NULL);
846 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
847 IsFunctionLocal = false;
848 MDValueList.AssignValue(V, NextMDValueNo++);
851 case bitc::METADATA_STRING: {
852 unsigned MDStringLength = Record.size();
853 SmallString<8> String;
854 String.resize(MDStringLength);
855 for (unsigned i = 0; i != MDStringLength; ++i)
856 String[i] = Record[i];
857 Value *V = MDString::get(Context,
858 StringRef(String.data(), String.size()));
859 MDValueList.AssignValue(V, NextMDValueNo++);
862 case bitc::METADATA_KIND: {
863 unsigned RecordLength = Record.size();
864 if (Record.empty() || RecordLength < 2)
865 return Error("Invalid METADATA_KIND record");
867 Name.resize(RecordLength-1);
868 unsigned Kind = Record[0];
869 for (unsigned i = 1; i != RecordLength; ++i)
870 Name[i-1] = Record[i];
872 unsigned NewKind = TheModule->getMDKindID(Name.str());
873 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
874 return Error("Conflicting METADATA_KIND records");
881 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
882 /// the LSB for dense VBR encoding.
883 static uint64_t DecodeSignRotatedValue(uint64_t V) {
888 // There is no such thing as -0 with integers. "-0" really means MININT.
892 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
893 /// values and aliases that we can.
894 bool BitcodeReader::ResolveGlobalAndAliasInits() {
895 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
896 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
898 GlobalInitWorklist.swap(GlobalInits);
899 AliasInitWorklist.swap(AliasInits);
901 while (!GlobalInitWorklist.empty()) {
902 unsigned ValID = GlobalInitWorklist.back().second;
903 if (ValID >= ValueList.size()) {
904 // Not ready to resolve this yet, it requires something later in the file.
905 GlobalInits.push_back(GlobalInitWorklist.back());
907 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
908 GlobalInitWorklist.back().first->setInitializer(C);
910 return Error("Global variable initializer is not a constant!");
912 GlobalInitWorklist.pop_back();
915 while (!AliasInitWorklist.empty()) {
916 unsigned ValID = AliasInitWorklist.back().second;
917 if (ValID >= ValueList.size()) {
918 AliasInits.push_back(AliasInitWorklist.back());
920 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
921 AliasInitWorklist.back().first->setAliasee(C);
923 return Error("Alias initializer is not a constant!");
925 AliasInitWorklist.pop_back();
930 bool BitcodeReader::ParseConstants() {
931 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
932 return Error("Malformed block record");
934 SmallVector<uint64_t, 64> Record;
936 // Read all the records for this value table.
937 Type *CurTy = Type::getInt32Ty(Context);
938 unsigned NextCstNo = ValueList.size();
940 unsigned Code = Stream.ReadCode();
941 if (Code == bitc::END_BLOCK)
944 if (Code == bitc::ENTER_SUBBLOCK) {
945 // No known subblocks, always skip them.
946 Stream.ReadSubBlockID();
947 if (Stream.SkipBlock())
948 return Error("Malformed block record");
952 if (Code == bitc::DEFINE_ABBREV) {
953 Stream.ReadAbbrevRecord();
960 unsigned BitCode = Stream.ReadRecord(Code, Record);
962 default: // Default behavior: unknown constant
963 case bitc::CST_CODE_UNDEF: // UNDEF
964 V = UndefValue::get(CurTy);
966 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
968 return Error("Malformed CST_SETTYPE record");
969 if (Record[0] >= TypeList.size())
970 return Error("Invalid Type ID in CST_SETTYPE record");
971 CurTy = TypeList[Record[0]];
972 continue; // Skip the ValueList manipulation.
973 case bitc::CST_CODE_NULL: // NULL
974 V = Constant::getNullValue(CurTy);
976 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
977 if (!CurTy->isIntegerTy() || Record.empty())
978 return Error("Invalid CST_INTEGER record");
979 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
981 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
982 if (!CurTy->isIntegerTy() || Record.empty())
983 return Error("Invalid WIDE_INTEGER record");
985 unsigned NumWords = Record.size();
986 SmallVector<uint64_t, 8> Words;
987 Words.resize(NumWords);
988 for (unsigned i = 0; i != NumWords; ++i)
989 Words[i] = DecodeSignRotatedValue(Record[i]);
990 V = ConstantInt::get(Context,
991 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
995 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
997 return Error("Invalid FLOAT record");
998 if (CurTy->isHalfTy())
999 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1000 else if (CurTy->isFloatTy())
1001 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1002 else if (CurTy->isDoubleTy())
1003 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1004 else if (CurTy->isX86_FP80Ty()) {
1005 // Bits are not stored the same way as a normal i80 APInt, compensate.
1006 uint64_t Rearrange[2];
1007 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1008 Rearrange[1] = Record[0] >> 48;
1009 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1010 } else if (CurTy->isFP128Ty())
1011 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1012 else if (CurTy->isPPC_FP128Ty())
1013 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1015 V = UndefValue::get(CurTy);
1019 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1021 return Error("Invalid CST_AGGREGATE record");
1023 unsigned Size = Record.size();
1024 SmallVector<Constant*, 16> Elts;
1026 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1027 for (unsigned i = 0; i != Size; ++i)
1028 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1029 STy->getElementType(i)));
1030 V = ConstantStruct::get(STy, Elts);
1031 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1032 Type *EltTy = ATy->getElementType();
1033 for (unsigned i = 0; i != Size; ++i)
1034 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1035 V = ConstantArray::get(ATy, Elts);
1036 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1037 Type *EltTy = VTy->getElementType();
1038 for (unsigned i = 0; i != Size; ++i)
1039 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1040 V = ConstantVector::get(Elts);
1042 V = UndefValue::get(CurTy);
1046 case bitc::CST_CODE_STRING: // STRING: [values]
1047 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1049 return Error("Invalid CST_STRING record");
1051 unsigned Size = Record.size();
1052 SmallString<16> Elts;
1053 for (unsigned i = 0; i != Size; ++i)
1054 Elts.push_back(Record[i]);
1055 V = ConstantDataArray::getString(Context, Elts,
1056 BitCode == bitc::CST_CODE_CSTRING);
1059 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1061 return Error("Invalid CST_DATA record");
1063 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1064 unsigned Size = Record.size();
1066 if (EltTy->isIntegerTy(8)) {
1067 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1068 if (isa<VectorType>(CurTy))
1069 V = ConstantDataVector::get(Context, Elts);
1071 V = ConstantDataArray::get(Context, Elts);
1072 } else if (EltTy->isIntegerTy(16)) {
1073 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1074 if (isa<VectorType>(CurTy))
1075 V = ConstantDataVector::get(Context, Elts);
1077 V = ConstantDataArray::get(Context, Elts);
1078 } else if (EltTy->isIntegerTy(32)) {
1079 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1080 if (isa<VectorType>(CurTy))
1081 V = ConstantDataVector::get(Context, Elts);
1083 V = ConstantDataArray::get(Context, Elts);
1084 } else if (EltTy->isIntegerTy(64)) {
1085 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1086 if (isa<VectorType>(CurTy))
1087 V = ConstantDataVector::get(Context, Elts);
1089 V = ConstantDataArray::get(Context, Elts);
1090 } else if (EltTy->isFloatTy()) {
1091 SmallVector<float, 16> Elts;
1092 for (unsigned i = 0; i != Size; ++i) {
1093 union { uint32_t I; float F; };
1097 if (isa<VectorType>(CurTy))
1098 V = ConstantDataVector::get(Context, Elts);
1100 V = ConstantDataArray::get(Context, Elts);
1101 } else if (EltTy->isDoubleTy()) {
1102 SmallVector<double, 16> Elts;
1103 for (unsigned i = 0; i != Size; ++i) {
1104 union { uint64_t I; double F; };
1108 if (isa<VectorType>(CurTy))
1109 V = ConstantDataVector::get(Context, Elts);
1111 V = ConstantDataArray::get(Context, Elts);
1113 return Error("Unknown element type in CE_DATA");
1118 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1119 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1120 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1122 V = UndefValue::get(CurTy); // Unknown binop.
1124 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1125 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1127 if (Record.size() >= 4) {
1128 if (Opc == Instruction::Add ||
1129 Opc == Instruction::Sub ||
1130 Opc == Instruction::Mul ||
1131 Opc == Instruction::Shl) {
1132 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1133 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1134 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1135 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1136 } else if (Opc == Instruction::SDiv ||
1137 Opc == Instruction::UDiv ||
1138 Opc == Instruction::LShr ||
1139 Opc == Instruction::AShr) {
1140 if (Record[3] & (1 << bitc::PEO_EXACT))
1141 Flags |= SDivOperator::IsExact;
1144 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1148 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1149 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1150 int Opc = GetDecodedCastOpcode(Record[0]);
1152 V = UndefValue::get(CurTy); // Unknown cast.
1154 Type *OpTy = getTypeByID(Record[1]);
1155 if (!OpTy) return Error("Invalid CE_CAST record");
1156 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1157 V = ConstantExpr::getCast(Opc, Op, CurTy);
1161 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1162 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1163 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1164 SmallVector<Constant*, 16> Elts;
1165 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1166 Type *ElTy = getTypeByID(Record[i]);
1167 if (!ElTy) return Error("Invalid CE_GEP record");
1168 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1170 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1171 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1173 bitc::CST_CODE_CE_INBOUNDS_GEP);
1176 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1177 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1178 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1179 Type::getInt1Ty(Context)),
1180 ValueList.getConstantFwdRef(Record[1],CurTy),
1181 ValueList.getConstantFwdRef(Record[2],CurTy));
1183 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1184 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1186 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1187 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1188 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1189 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1190 V = ConstantExpr::getExtractElement(Op0, Op1);
1193 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1194 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1195 if (Record.size() < 3 || OpTy == 0)
1196 return Error("Invalid CE_INSERTELT record");
1197 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1198 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1199 OpTy->getElementType());
1200 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1201 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1204 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1205 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1206 if (Record.size() < 3 || OpTy == 0)
1207 return Error("Invalid CE_SHUFFLEVEC record");
1208 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1209 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1210 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1211 OpTy->getNumElements());
1212 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1213 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1216 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1217 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1219 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1220 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1221 return Error("Invalid CE_SHUFVEC_EX record");
1222 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1223 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1224 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1225 RTy->getNumElements());
1226 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1227 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1230 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1231 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1232 Type *OpTy = getTypeByID(Record[0]);
1233 if (OpTy == 0) return Error("Invalid CE_CMP record");
1234 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1235 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1237 if (OpTy->isFPOrFPVectorTy())
1238 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1240 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1243 case bitc::CST_CODE_INLINEASM: {
1244 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1245 std::string AsmStr, ConstrStr;
1246 bool HasSideEffects = Record[0] & 1;
1247 bool IsAlignStack = Record[0] >> 1;
1248 unsigned AsmStrSize = Record[1];
1249 if (2+AsmStrSize >= Record.size())
1250 return Error("Invalid INLINEASM record");
1251 unsigned ConstStrSize = Record[2+AsmStrSize];
1252 if (3+AsmStrSize+ConstStrSize > Record.size())
1253 return Error("Invalid INLINEASM record");
1255 for (unsigned i = 0; i != AsmStrSize; ++i)
1256 AsmStr += (char)Record[2+i];
1257 for (unsigned i = 0; i != ConstStrSize; ++i)
1258 ConstrStr += (char)Record[3+AsmStrSize+i];
1259 PointerType *PTy = cast<PointerType>(CurTy);
1260 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1261 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1264 case bitc::CST_CODE_BLOCKADDRESS:{
1265 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1266 Type *FnTy = getTypeByID(Record[0]);
1267 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1269 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1270 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1272 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1273 Type::getInt8Ty(Context),
1274 false, GlobalValue::InternalLinkage,
1276 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1282 ValueList.AssignValue(V, NextCstNo);
1286 if (NextCstNo != ValueList.size())
1287 return Error("Invalid constant reference!");
1289 if (Stream.ReadBlockEnd())
1290 return Error("Error at end of constants block");
1292 // Once all the constants have been read, go through and resolve forward
1294 ValueList.ResolveConstantForwardRefs();
1298 bool BitcodeReader::ParseUseLists() {
1299 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1300 return Error("Malformed block record");
1302 SmallVector<uint64_t, 64> Record;
1304 // Read all the records.
1306 unsigned Code = Stream.ReadCode();
1307 if (Code == bitc::END_BLOCK) {
1308 if (Stream.ReadBlockEnd())
1309 return Error("Error at end of use-list table block");
1313 if (Code == bitc::ENTER_SUBBLOCK) {
1314 // No known subblocks, always skip them.
1315 Stream.ReadSubBlockID();
1316 if (Stream.SkipBlock())
1317 return Error("Malformed block record");
1321 if (Code == bitc::DEFINE_ABBREV) {
1322 Stream.ReadAbbrevRecord();
1326 // Read a use list record.
1328 switch (Stream.ReadRecord(Code, Record)) {
1329 default: // Default behavior: unknown type.
1331 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1332 unsigned RecordLength = Record.size();
1333 if (RecordLength < 1)
1334 return Error ("Invalid UseList reader!");
1335 UseListRecords.push_back(Record);
1342 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1343 /// remember where it is and then skip it. This lets us lazily deserialize the
1345 bool BitcodeReader::RememberAndSkipFunctionBody() {
1346 // Get the function we are talking about.
1347 if (FunctionsWithBodies.empty())
1348 return Error("Insufficient function protos");
1350 Function *Fn = FunctionsWithBodies.back();
1351 FunctionsWithBodies.pop_back();
1353 // Save the current stream state.
1354 uint64_t CurBit = Stream.GetCurrentBitNo();
1355 DeferredFunctionInfo[Fn] = CurBit;
1357 // Skip over the function block for now.
1358 if (Stream.SkipBlock())
1359 return Error("Malformed block record");
1363 bool BitcodeReader::GlobalCleanup() {
1364 // Patch the initializers for globals and aliases up.
1365 ResolveGlobalAndAliasInits();
1366 if (!GlobalInits.empty() || !AliasInits.empty())
1367 return Error("Malformed global initializer set");
1369 // Look for intrinsic functions which need to be upgraded at some point
1370 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1373 if (UpgradeIntrinsicFunction(FI, NewFn))
1374 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1377 // Look for global variables which need to be renamed.
1378 for (Module::global_iterator
1379 GI = TheModule->global_begin(), GE = TheModule->global_end();
1381 UpgradeGlobalVariable(GI);
1382 // Force deallocation of memory for these vectors to favor the client that
1383 // want lazy deserialization.
1384 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1385 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1389 bool BitcodeReader::ParseModule(bool Resume) {
1391 Stream.JumpToBit(NextUnreadBit);
1392 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1393 return Error("Malformed block record");
1395 SmallVector<uint64_t, 64> Record;
1396 std::vector<std::string> SectionTable;
1397 std::vector<std::string> GCTable;
1399 // Read all the records for this module.
1400 while (!Stream.AtEndOfStream()) {
1401 unsigned Code = Stream.ReadCode();
1402 if (Code == bitc::END_BLOCK) {
1403 if (Stream.ReadBlockEnd())
1404 return Error("Error at end of module block");
1406 return GlobalCleanup();
1409 if (Code == bitc::ENTER_SUBBLOCK) {
1410 switch (Stream.ReadSubBlockID()) {
1411 default: // Skip unknown content.
1412 if (Stream.SkipBlock())
1413 return Error("Malformed block record");
1415 case bitc::BLOCKINFO_BLOCK_ID:
1416 if (Stream.ReadBlockInfoBlock())
1417 return Error("Malformed BlockInfoBlock");
1419 case bitc::PARAMATTR_BLOCK_ID:
1420 if (ParseAttributeBlock())
1423 case bitc::TYPE_BLOCK_ID_NEW:
1424 if (ParseTypeTable())
1427 case bitc::VALUE_SYMTAB_BLOCK_ID:
1428 if (ParseValueSymbolTable())
1430 SeenValueSymbolTable = true;
1432 case bitc::CONSTANTS_BLOCK_ID:
1433 if (ParseConstants() || ResolveGlobalAndAliasInits())
1436 case bitc::METADATA_BLOCK_ID:
1437 if (ParseMetadata())
1440 case bitc::FUNCTION_BLOCK_ID:
1441 // If this is the first function body we've seen, reverse the
1442 // FunctionsWithBodies list.
1443 if (!SeenFirstFunctionBody) {
1444 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1445 if (GlobalCleanup())
1447 SeenFirstFunctionBody = true;
1450 if (RememberAndSkipFunctionBody())
1452 // For streaming bitcode, suspend parsing when we reach the function
1453 // bodies. Subsequent materialization calls will resume it when
1454 // necessary. For streaming, the function bodies must be at the end of
1455 // the bitcode. If the bitcode file is old, the symbol table will be
1456 // at the end instead and will not have been seen yet. In this case,
1457 // just finish the parse now.
1458 if (LazyStreamer && SeenValueSymbolTable) {
1459 NextUnreadBit = Stream.GetCurrentBitNo();
1463 case bitc::USELIST_BLOCK_ID:
1464 if (ParseUseLists())
1471 if (Code == bitc::DEFINE_ABBREV) {
1472 Stream.ReadAbbrevRecord();
1477 switch (Stream.ReadRecord(Code, Record)) {
1478 default: break; // Default behavior, ignore unknown content.
1479 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1480 if (Record.size() < 1)
1481 return Error("Malformed MODULE_CODE_VERSION");
1482 // Only version #0 is supported so far.
1484 return Error("Unknown bitstream version!");
1486 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1488 if (ConvertToString(Record, 0, S))
1489 return Error("Invalid MODULE_CODE_TRIPLE record");
1490 TheModule->setTargetTriple(S);
1493 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1495 if (ConvertToString(Record, 0, S))
1496 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1497 TheModule->setDataLayout(S);
1500 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1502 if (ConvertToString(Record, 0, S))
1503 return Error("Invalid MODULE_CODE_ASM record");
1504 TheModule->setModuleInlineAsm(S);
1507 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1509 if (ConvertToString(Record, 0, S))
1510 return Error("Invalid MODULE_CODE_DEPLIB record");
1511 TheModule->addLibrary(S);
1514 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1516 if (ConvertToString(Record, 0, S))
1517 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1518 SectionTable.push_back(S);
1521 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1523 if (ConvertToString(Record, 0, S))
1524 return Error("Invalid MODULE_CODE_GCNAME record");
1525 GCTable.push_back(S);
1528 // GLOBALVAR: [pointer type, isconst, initid,
1529 // linkage, alignment, section, visibility, threadlocal,
1531 case bitc::MODULE_CODE_GLOBALVAR: {
1532 if (Record.size() < 6)
1533 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1534 Type *Ty = getTypeByID(Record[0]);
1535 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1536 if (!Ty->isPointerTy())
1537 return Error("Global not a pointer type!");
1538 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1539 Ty = cast<PointerType>(Ty)->getElementType();
1541 bool isConstant = Record[1];
1542 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1543 unsigned Alignment = (1 << Record[4]) >> 1;
1544 std::string Section;
1546 if (Record[5]-1 >= SectionTable.size())
1547 return Error("Invalid section ID");
1548 Section = SectionTable[Record[5]-1];
1550 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1551 if (Record.size() > 6)
1552 Visibility = GetDecodedVisibility(Record[6]);
1553 bool isThreadLocal = false;
1554 if (Record.size() > 7)
1555 isThreadLocal = Record[7];
1557 bool UnnamedAddr = false;
1558 if (Record.size() > 8)
1559 UnnamedAddr = Record[8];
1561 GlobalVariable *NewGV =
1562 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1563 isThreadLocal, AddressSpace);
1564 NewGV->setAlignment(Alignment);
1565 if (!Section.empty())
1566 NewGV->setSection(Section);
1567 NewGV->setVisibility(Visibility);
1568 NewGV->setThreadLocal(isThreadLocal);
1569 NewGV->setUnnamedAddr(UnnamedAddr);
1571 ValueList.push_back(NewGV);
1573 // Remember which value to use for the global initializer.
1574 if (unsigned InitID = Record[2])
1575 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1578 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1579 // alignment, section, visibility, gc, unnamed_addr]
1580 case bitc::MODULE_CODE_FUNCTION: {
1581 if (Record.size() < 8)
1582 return Error("Invalid MODULE_CODE_FUNCTION record");
1583 Type *Ty = getTypeByID(Record[0]);
1584 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1585 if (!Ty->isPointerTy())
1586 return Error("Function not a pointer type!");
1588 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1590 return Error("Function not a pointer to function type!");
1592 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1595 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1596 bool isProto = Record[2];
1597 Func->setLinkage(GetDecodedLinkage(Record[3]));
1598 Func->setAttributes(getAttributes(Record[4]));
1600 Func->setAlignment((1 << Record[5]) >> 1);
1602 if (Record[6]-1 >= SectionTable.size())
1603 return Error("Invalid section ID");
1604 Func->setSection(SectionTable[Record[6]-1]);
1606 Func->setVisibility(GetDecodedVisibility(Record[7]));
1607 if (Record.size() > 8 && Record[8]) {
1608 if (Record[8]-1 > GCTable.size())
1609 return Error("Invalid GC ID");
1610 Func->setGC(GCTable[Record[8]-1].c_str());
1612 bool UnnamedAddr = false;
1613 if (Record.size() > 9)
1614 UnnamedAddr = Record[9];
1615 Func->setUnnamedAddr(UnnamedAddr);
1616 ValueList.push_back(Func);
1618 // If this is a function with a body, remember the prototype we are
1619 // creating now, so that we can match up the body with them later.
1621 FunctionsWithBodies.push_back(Func);
1622 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1626 // ALIAS: [alias type, aliasee val#, linkage]
1627 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1628 case bitc::MODULE_CODE_ALIAS: {
1629 if (Record.size() < 3)
1630 return Error("Invalid MODULE_ALIAS record");
1631 Type *Ty = getTypeByID(Record[0]);
1632 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1633 if (!Ty->isPointerTy())
1634 return Error("Function not a pointer type!");
1636 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1638 // Old bitcode files didn't have visibility field.
1639 if (Record.size() > 3)
1640 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1641 ValueList.push_back(NewGA);
1642 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1645 /// MODULE_CODE_PURGEVALS: [numvals]
1646 case bitc::MODULE_CODE_PURGEVALS:
1647 // Trim down the value list to the specified size.
1648 if (Record.size() < 1 || Record[0] > ValueList.size())
1649 return Error("Invalid MODULE_PURGEVALS record");
1650 ValueList.shrinkTo(Record[0]);
1656 return Error("Premature end of bitstream");
1659 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1662 if (InitStream()) return true;
1664 // Sniff for the signature.
1665 if (Stream.Read(8) != 'B' ||
1666 Stream.Read(8) != 'C' ||
1667 Stream.Read(4) != 0x0 ||
1668 Stream.Read(4) != 0xC ||
1669 Stream.Read(4) != 0xE ||
1670 Stream.Read(4) != 0xD)
1671 return Error("Invalid bitcode signature");
1673 // We expect a number of well-defined blocks, though we don't necessarily
1674 // need to understand them all.
1675 while (!Stream.AtEndOfStream()) {
1676 unsigned Code = Stream.ReadCode();
1678 if (Code != bitc::ENTER_SUBBLOCK) {
1680 // The ranlib in xcode 4 will align archive members by appending newlines
1681 // to the end of them. If this file size is a multiple of 4 but not 8, we
1682 // have to read and ignore these final 4 bytes :-(
1683 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1684 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1685 Stream.AtEndOfStream())
1688 return Error("Invalid record at top-level");
1691 unsigned BlockID = Stream.ReadSubBlockID();
1693 // We only know the MODULE subblock ID.
1695 case bitc::BLOCKINFO_BLOCK_ID:
1696 if (Stream.ReadBlockInfoBlock())
1697 return Error("Malformed BlockInfoBlock");
1699 case bitc::MODULE_BLOCK_ID:
1700 // Reject multiple MODULE_BLOCK's in a single bitstream.
1702 return Error("Multiple MODULE_BLOCKs in same stream");
1704 if (ParseModule(false))
1706 if (LazyStreamer) return false;
1709 if (Stream.SkipBlock())
1710 return Error("Malformed block record");
1718 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1719 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1720 return Error("Malformed block record");
1722 SmallVector<uint64_t, 64> Record;
1724 // Read all the records for this module.
1725 while (!Stream.AtEndOfStream()) {
1726 unsigned Code = Stream.ReadCode();
1727 if (Code == bitc::END_BLOCK) {
1728 if (Stream.ReadBlockEnd())
1729 return Error("Error at end of module block");
1734 if (Code == bitc::ENTER_SUBBLOCK) {
1735 switch (Stream.ReadSubBlockID()) {
1736 default: // Skip unknown content.
1737 if (Stream.SkipBlock())
1738 return Error("Malformed block record");
1744 if (Code == bitc::DEFINE_ABBREV) {
1745 Stream.ReadAbbrevRecord();
1750 switch (Stream.ReadRecord(Code, Record)) {
1751 default: break; // Default behavior, ignore unknown content.
1752 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1753 if (Record.size() < 1)
1754 return Error("Malformed MODULE_CODE_VERSION");
1755 // Only version #0 is supported so far.
1757 return Error("Unknown bitstream version!");
1759 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1761 if (ConvertToString(Record, 0, S))
1762 return Error("Invalid MODULE_CODE_TRIPLE record");
1770 return Error("Premature end of bitstream");
1773 bool BitcodeReader::ParseTriple(std::string &Triple) {
1774 if (InitStream()) return true;
1776 // Sniff for the signature.
1777 if (Stream.Read(8) != 'B' ||
1778 Stream.Read(8) != 'C' ||
1779 Stream.Read(4) != 0x0 ||
1780 Stream.Read(4) != 0xC ||
1781 Stream.Read(4) != 0xE ||
1782 Stream.Read(4) != 0xD)
1783 return Error("Invalid bitcode signature");
1785 // We expect a number of well-defined blocks, though we don't necessarily
1786 // need to understand them all.
1787 while (!Stream.AtEndOfStream()) {
1788 unsigned Code = Stream.ReadCode();
1790 if (Code != bitc::ENTER_SUBBLOCK)
1791 return Error("Invalid record at top-level");
1793 unsigned BlockID = Stream.ReadSubBlockID();
1795 // We only know the MODULE subblock ID.
1797 case bitc::MODULE_BLOCK_ID:
1798 if (ParseModuleTriple(Triple))
1802 if (Stream.SkipBlock())
1803 return Error("Malformed block record");
1811 /// ParseMetadataAttachment - Parse metadata attachments.
1812 bool BitcodeReader::ParseMetadataAttachment() {
1813 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1814 return Error("Malformed block record");
1816 SmallVector<uint64_t, 64> Record;
1818 unsigned Code = Stream.ReadCode();
1819 if (Code == bitc::END_BLOCK) {
1820 if (Stream.ReadBlockEnd())
1821 return Error("Error at end of PARAMATTR block");
1824 if (Code == bitc::DEFINE_ABBREV) {
1825 Stream.ReadAbbrevRecord();
1828 // Read a metadata attachment record.
1830 switch (Stream.ReadRecord(Code, Record)) {
1831 default: // Default behavior: ignore.
1833 case bitc::METADATA_ATTACHMENT: {
1834 unsigned RecordLength = Record.size();
1835 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1836 return Error ("Invalid METADATA_ATTACHMENT reader!");
1837 Instruction *Inst = InstructionList[Record[0]];
1838 for (unsigned i = 1; i != RecordLength; i = i+2) {
1839 unsigned Kind = Record[i];
1840 DenseMap<unsigned, unsigned>::iterator I =
1841 MDKindMap.find(Kind);
1842 if (I == MDKindMap.end())
1843 return Error("Invalid metadata kind ID");
1844 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1845 Inst->setMetadata(I->second, cast<MDNode>(Node));
1854 /// ParseFunctionBody - Lazily parse the specified function body block.
1855 bool BitcodeReader::ParseFunctionBody(Function *F) {
1856 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1857 return Error("Malformed block record");
1859 InstructionList.clear();
1860 unsigned ModuleValueListSize = ValueList.size();
1861 unsigned ModuleMDValueListSize = MDValueList.size();
1863 // Add all the function arguments to the value table.
1864 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1865 ValueList.push_back(I);
1867 unsigned NextValueNo = ValueList.size();
1868 BasicBlock *CurBB = 0;
1869 unsigned CurBBNo = 0;
1873 // Read all the records.
1874 SmallVector<uint64_t, 64> Record;
1876 unsigned Code = Stream.ReadCode();
1877 if (Code == bitc::END_BLOCK) {
1878 if (Stream.ReadBlockEnd())
1879 return Error("Error at end of function block");
1883 if (Code == bitc::ENTER_SUBBLOCK) {
1884 switch (Stream.ReadSubBlockID()) {
1885 default: // Skip unknown content.
1886 if (Stream.SkipBlock())
1887 return Error("Malformed block record");
1889 case bitc::CONSTANTS_BLOCK_ID:
1890 if (ParseConstants()) return true;
1891 NextValueNo = ValueList.size();
1893 case bitc::VALUE_SYMTAB_BLOCK_ID:
1894 if (ParseValueSymbolTable()) return true;
1896 case bitc::METADATA_ATTACHMENT_ID:
1897 if (ParseMetadataAttachment()) return true;
1899 case bitc::METADATA_BLOCK_ID:
1900 if (ParseMetadata()) return true;
1906 if (Code == bitc::DEFINE_ABBREV) {
1907 Stream.ReadAbbrevRecord();
1914 unsigned BitCode = Stream.ReadRecord(Code, Record);
1916 default: // Default behavior: reject
1917 return Error("Unknown instruction");
1918 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1919 if (Record.size() < 1 || Record[0] == 0)
1920 return Error("Invalid DECLAREBLOCKS record");
1921 // Create all the basic blocks for the function.
1922 FunctionBBs.resize(Record[0]);
1923 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1924 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1925 CurBB = FunctionBBs[0];
1928 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1929 // This record indicates that the last instruction is at the same
1930 // location as the previous instruction with a location.
1933 // Get the last instruction emitted.
1934 if (CurBB && !CurBB->empty())
1936 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1937 !FunctionBBs[CurBBNo-1]->empty())
1938 I = &FunctionBBs[CurBBNo-1]->back();
1940 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1941 I->setDebugLoc(LastLoc);
1945 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
1946 I = 0; // Get the last instruction emitted.
1947 if (CurBB && !CurBB->empty())
1949 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1950 !FunctionBBs[CurBBNo-1]->empty())
1951 I = &FunctionBBs[CurBBNo-1]->back();
1952 if (I == 0 || Record.size() < 4)
1953 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1955 unsigned Line = Record[0], Col = Record[1];
1956 unsigned ScopeID = Record[2], IAID = Record[3];
1958 MDNode *Scope = 0, *IA = 0;
1959 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1960 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1961 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1962 I->setDebugLoc(LastLoc);
1967 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1970 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1971 getValue(Record, OpNum, LHS->getType(), RHS) ||
1972 OpNum+1 > Record.size())
1973 return Error("Invalid BINOP record");
1975 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1976 if (Opc == -1) return Error("Invalid BINOP record");
1977 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1978 InstructionList.push_back(I);
1979 if (OpNum < Record.size()) {
1980 if (Opc == Instruction::Add ||
1981 Opc == Instruction::Sub ||
1982 Opc == Instruction::Mul ||
1983 Opc == Instruction::Shl) {
1984 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1985 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1986 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1987 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1988 } else if (Opc == Instruction::SDiv ||
1989 Opc == Instruction::UDiv ||
1990 Opc == Instruction::LShr ||
1991 Opc == Instruction::AShr) {
1992 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
1993 cast<BinaryOperator>(I)->setIsExact(true);
1998 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2001 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2002 OpNum+2 != Record.size())
2003 return Error("Invalid CAST record");
2005 Type *ResTy = getTypeByID(Record[OpNum]);
2006 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2007 if (Opc == -1 || ResTy == 0)
2008 return Error("Invalid CAST record");
2009 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2010 InstructionList.push_back(I);
2013 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2014 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2017 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2018 return Error("Invalid GEP record");
2020 SmallVector<Value*, 16> GEPIdx;
2021 while (OpNum != Record.size()) {
2023 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2024 return Error("Invalid GEP record");
2025 GEPIdx.push_back(Op);
2028 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2029 InstructionList.push_back(I);
2030 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2031 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2035 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2036 // EXTRACTVAL: [opty, opval, n x indices]
2039 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2040 return Error("Invalid EXTRACTVAL record");
2042 SmallVector<unsigned, 4> EXTRACTVALIdx;
2043 for (unsigned RecSize = Record.size();
2044 OpNum != RecSize; ++OpNum) {
2045 uint64_t Index = Record[OpNum];
2046 if ((unsigned)Index != Index)
2047 return Error("Invalid EXTRACTVAL index");
2048 EXTRACTVALIdx.push_back((unsigned)Index);
2051 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2052 InstructionList.push_back(I);
2056 case bitc::FUNC_CODE_INST_INSERTVAL: {
2057 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2060 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2061 return Error("Invalid INSERTVAL record");
2063 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2064 return Error("Invalid INSERTVAL record");
2066 SmallVector<unsigned, 4> INSERTVALIdx;
2067 for (unsigned RecSize = Record.size();
2068 OpNum != RecSize; ++OpNum) {
2069 uint64_t Index = Record[OpNum];
2070 if ((unsigned)Index != Index)
2071 return Error("Invalid INSERTVAL index");
2072 INSERTVALIdx.push_back((unsigned)Index);
2075 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2076 InstructionList.push_back(I);
2080 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2081 // obsolete form of select
2082 // handles select i1 ... in old bitcode
2084 Value *TrueVal, *FalseVal, *Cond;
2085 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2086 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2087 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2088 return Error("Invalid SELECT record");
2090 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2091 InstructionList.push_back(I);
2095 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2096 // new form of select
2097 // handles select i1 or select [N x i1]
2099 Value *TrueVal, *FalseVal, *Cond;
2100 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2101 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2102 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2103 return Error("Invalid SELECT record");
2105 // select condition can be either i1 or [N x i1]
2106 if (VectorType* vector_type =
2107 dyn_cast<VectorType>(Cond->getType())) {
2109 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2110 return Error("Invalid SELECT condition type");
2113 if (Cond->getType() != Type::getInt1Ty(Context))
2114 return Error("Invalid SELECT condition type");
2117 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2118 InstructionList.push_back(I);
2122 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2125 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2126 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2127 return Error("Invalid EXTRACTELT record");
2128 I = ExtractElementInst::Create(Vec, Idx);
2129 InstructionList.push_back(I);
2133 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2135 Value *Vec, *Elt, *Idx;
2136 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2137 getValue(Record, OpNum,
2138 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2139 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2140 return Error("Invalid INSERTELT record");
2141 I = InsertElementInst::Create(Vec, Elt, Idx);
2142 InstructionList.push_back(I);
2146 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2148 Value *Vec1, *Vec2, *Mask;
2149 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2150 getValue(Record, OpNum, Vec1->getType(), Vec2))
2151 return Error("Invalid SHUFFLEVEC record");
2153 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2154 return Error("Invalid SHUFFLEVEC record");
2155 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2156 InstructionList.push_back(I);
2160 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2161 // Old form of ICmp/FCmp returning bool
2162 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2163 // both legal on vectors but had different behaviour.
2164 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2165 // FCmp/ICmp returning bool or vector of bool
2169 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2170 getValue(Record, OpNum, LHS->getType(), RHS) ||
2171 OpNum+1 != Record.size())
2172 return Error("Invalid CMP record");
2174 if (LHS->getType()->isFPOrFPVectorTy())
2175 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2177 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2178 InstructionList.push_back(I);
2182 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2184 unsigned Size = Record.size();
2186 I = ReturnInst::Create(Context);
2187 InstructionList.push_back(I);
2193 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2194 return Error("Invalid RET record");
2195 if (OpNum != Record.size())
2196 return Error("Invalid RET record");
2198 I = ReturnInst::Create(Context, Op);
2199 InstructionList.push_back(I);
2202 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2203 if (Record.size() != 1 && Record.size() != 3)
2204 return Error("Invalid BR record");
2205 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2207 return Error("Invalid BR record");
2209 if (Record.size() == 1) {
2210 I = BranchInst::Create(TrueDest);
2211 InstructionList.push_back(I);
2214 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2215 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2216 if (FalseDest == 0 || Cond == 0)
2217 return Error("Invalid BR record");
2218 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2219 InstructionList.push_back(I);
2223 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2224 if (Record.size() < 3 || (Record.size() & 1) == 0)
2225 return Error("Invalid SWITCH record");
2226 Type *OpTy = getTypeByID(Record[0]);
2227 Value *Cond = getFnValueByID(Record[1], OpTy);
2228 BasicBlock *Default = getBasicBlock(Record[2]);
2229 if (OpTy == 0 || Cond == 0 || Default == 0)
2230 return Error("Invalid SWITCH record");
2231 unsigned NumCases = (Record.size()-3)/2;
2232 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2233 InstructionList.push_back(SI);
2234 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2235 ConstantInt *CaseVal =
2236 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2237 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2238 if (CaseVal == 0 || DestBB == 0) {
2240 return Error("Invalid SWITCH record!");
2242 SI->addCase(CaseVal, DestBB);
2247 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2248 if (Record.size() < 2)
2249 return Error("Invalid INDIRECTBR record");
2250 Type *OpTy = getTypeByID(Record[0]);
2251 Value *Address = getFnValueByID(Record[1], OpTy);
2252 if (OpTy == 0 || Address == 0)
2253 return Error("Invalid INDIRECTBR record");
2254 unsigned NumDests = Record.size()-2;
2255 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2256 InstructionList.push_back(IBI);
2257 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2258 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2259 IBI->addDestination(DestBB);
2262 return Error("Invalid INDIRECTBR record!");
2269 case bitc::FUNC_CODE_INST_INVOKE: {
2270 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2271 if (Record.size() < 4) return Error("Invalid INVOKE record");
2272 AttrListPtr PAL = getAttributes(Record[0]);
2273 unsigned CCInfo = Record[1];
2274 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2275 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2279 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2280 return Error("Invalid INVOKE record");
2282 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2283 FunctionType *FTy = !CalleeTy ? 0 :
2284 dyn_cast<FunctionType>(CalleeTy->getElementType());
2286 // Check that the right number of fixed parameters are here.
2287 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2288 Record.size() < OpNum+FTy->getNumParams())
2289 return Error("Invalid INVOKE record");
2291 SmallVector<Value*, 16> Ops;
2292 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2293 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2294 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2297 if (!FTy->isVarArg()) {
2298 if (Record.size() != OpNum)
2299 return Error("Invalid INVOKE record");
2301 // Read type/value pairs for varargs params.
2302 while (OpNum != Record.size()) {
2304 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2305 return Error("Invalid INVOKE record");
2310 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2311 InstructionList.push_back(I);
2312 cast<InvokeInst>(I)->setCallingConv(
2313 static_cast<CallingConv::ID>(CCInfo));
2314 cast<InvokeInst>(I)->setAttributes(PAL);
2317 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2320 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2321 return Error("Invalid RESUME record");
2322 I = ResumeInst::Create(Val);
2323 InstructionList.push_back(I);
2326 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2327 I = new UnreachableInst(Context);
2328 InstructionList.push_back(I);
2330 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2331 if (Record.size() < 1 || ((Record.size()-1)&1))
2332 return Error("Invalid PHI record");
2333 Type *Ty = getTypeByID(Record[0]);
2334 if (!Ty) return Error("Invalid PHI record");
2336 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2337 InstructionList.push_back(PN);
2339 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2340 Value *V = getFnValueByID(Record[1+i], Ty);
2341 BasicBlock *BB = getBasicBlock(Record[2+i]);
2342 if (!V || !BB) return Error("Invalid PHI record");
2343 PN->addIncoming(V, BB);
2349 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2350 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2352 if (Record.size() < 4)
2353 return Error("Invalid LANDINGPAD record");
2354 Type *Ty = getTypeByID(Record[Idx++]);
2355 if (!Ty) return Error("Invalid LANDINGPAD record");
2357 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2358 return Error("Invalid LANDINGPAD record");
2360 bool IsCleanup = !!Record[Idx++];
2361 unsigned NumClauses = Record[Idx++];
2362 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2363 LP->setCleanup(IsCleanup);
2364 for (unsigned J = 0; J != NumClauses; ++J) {
2365 LandingPadInst::ClauseType CT =
2366 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2369 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2371 return Error("Invalid LANDINGPAD record");
2374 assert((CT != LandingPadInst::Catch ||
2375 !isa<ArrayType>(Val->getType())) &&
2376 "Catch clause has a invalid type!");
2377 assert((CT != LandingPadInst::Filter ||
2378 isa<ArrayType>(Val->getType())) &&
2379 "Filter clause has invalid type!");
2384 InstructionList.push_back(I);
2388 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2389 if (Record.size() != 4)
2390 return Error("Invalid ALLOCA record");
2392 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2393 Type *OpTy = getTypeByID(Record[1]);
2394 Value *Size = getFnValueByID(Record[2], OpTy);
2395 unsigned Align = Record[3];
2396 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2397 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2398 InstructionList.push_back(I);
2401 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2404 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2405 OpNum+2 != Record.size())
2406 return Error("Invalid LOAD record");
2408 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2409 InstructionList.push_back(I);
2412 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2413 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2416 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2417 OpNum+4 != Record.size())
2418 return Error("Invalid LOADATOMIC record");
2421 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2422 if (Ordering == NotAtomic || Ordering == Release ||
2423 Ordering == AcquireRelease)
2424 return Error("Invalid LOADATOMIC record");
2425 if (Ordering != NotAtomic && Record[OpNum] == 0)
2426 return Error("Invalid LOADATOMIC record");
2427 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2429 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2430 Ordering, SynchScope);
2431 InstructionList.push_back(I);
2434 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2437 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2438 getValue(Record, OpNum,
2439 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2440 OpNum+2 != Record.size())
2441 return Error("Invalid STORE record");
2443 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2444 InstructionList.push_back(I);
2447 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2448 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2451 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2452 getValue(Record, OpNum,
2453 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2454 OpNum+4 != Record.size())
2455 return Error("Invalid STOREATOMIC record");
2457 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2458 if (Ordering == NotAtomic || Ordering == Acquire ||
2459 Ordering == AcquireRelease)
2460 return Error("Invalid STOREATOMIC record");
2461 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2462 if (Ordering != NotAtomic && Record[OpNum] == 0)
2463 return Error("Invalid STOREATOMIC record");
2465 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2466 Ordering, SynchScope);
2467 InstructionList.push_back(I);
2470 case bitc::FUNC_CODE_INST_CMPXCHG: {
2471 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2473 Value *Ptr, *Cmp, *New;
2474 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2475 getValue(Record, OpNum,
2476 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2477 getValue(Record, OpNum,
2478 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2479 OpNum+3 != Record.size())
2480 return Error("Invalid CMPXCHG record");
2481 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2482 if (Ordering == NotAtomic || Ordering == Unordered)
2483 return Error("Invalid CMPXCHG record");
2484 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2485 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2486 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2487 InstructionList.push_back(I);
2490 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2491 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2494 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2495 getValue(Record, OpNum,
2496 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2497 OpNum+4 != Record.size())
2498 return Error("Invalid ATOMICRMW record");
2499 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2500 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2501 Operation > AtomicRMWInst::LAST_BINOP)
2502 return Error("Invalid ATOMICRMW record");
2503 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2504 if (Ordering == NotAtomic || Ordering == Unordered)
2505 return Error("Invalid ATOMICRMW record");
2506 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2507 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2508 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2509 InstructionList.push_back(I);
2512 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2513 if (2 != Record.size())
2514 return Error("Invalid FENCE record");
2515 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2516 if (Ordering == NotAtomic || Ordering == Unordered ||
2517 Ordering == Monotonic)
2518 return Error("Invalid FENCE record");
2519 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2520 I = new FenceInst(Context, Ordering, SynchScope);
2521 InstructionList.push_back(I);
2524 case bitc::FUNC_CODE_INST_CALL: {
2525 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2526 if (Record.size() < 3)
2527 return Error("Invalid CALL record");
2529 AttrListPtr PAL = getAttributes(Record[0]);
2530 unsigned CCInfo = Record[1];
2534 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2535 return Error("Invalid CALL record");
2537 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2538 FunctionType *FTy = 0;
2539 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2540 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2541 return Error("Invalid CALL record");
2543 SmallVector<Value*, 16> Args;
2544 // Read the fixed params.
2545 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2546 if (FTy->getParamType(i)->isLabelTy())
2547 Args.push_back(getBasicBlock(Record[OpNum]));
2549 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2550 if (Args.back() == 0) return Error("Invalid CALL record");
2553 // Read type/value pairs for varargs params.
2554 if (!FTy->isVarArg()) {
2555 if (OpNum != Record.size())
2556 return Error("Invalid CALL record");
2558 while (OpNum != Record.size()) {
2560 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2561 return Error("Invalid CALL record");
2566 I = CallInst::Create(Callee, Args);
2567 InstructionList.push_back(I);
2568 cast<CallInst>(I)->setCallingConv(
2569 static_cast<CallingConv::ID>(CCInfo>>1));
2570 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2571 cast<CallInst>(I)->setAttributes(PAL);
2574 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2575 if (Record.size() < 3)
2576 return Error("Invalid VAARG record");
2577 Type *OpTy = getTypeByID(Record[0]);
2578 Value *Op = getFnValueByID(Record[1], OpTy);
2579 Type *ResTy = getTypeByID(Record[2]);
2580 if (!OpTy || !Op || !ResTy)
2581 return Error("Invalid VAARG record");
2582 I = new VAArgInst(Op, ResTy);
2583 InstructionList.push_back(I);
2588 // Add instruction to end of current BB. If there is no current BB, reject
2592 return Error("Invalid instruction with no BB");
2594 CurBB->getInstList().push_back(I);
2596 // If this was a terminator instruction, move to the next block.
2597 if (isa<TerminatorInst>(I)) {
2599 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2602 // Non-void values get registered in the value table for future use.
2603 if (I && !I->getType()->isVoidTy())
2604 ValueList.AssignValue(I, NextValueNo++);
2607 // Check the function list for unresolved values.
2608 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2609 if (A->getParent() == 0) {
2610 // We found at least one unresolved value. Nuke them all to avoid leaks.
2611 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2612 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2613 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2617 return Error("Never resolved value found in function!");
2621 // FIXME: Check for unresolved forward-declared metadata references
2622 // and clean up leaks.
2624 // See if anything took the address of blocks in this function. If so,
2625 // resolve them now.
2626 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2627 BlockAddrFwdRefs.find(F);
2628 if (BAFRI != BlockAddrFwdRefs.end()) {
2629 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2630 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2631 unsigned BlockIdx = RefList[i].first;
2632 if (BlockIdx >= FunctionBBs.size())
2633 return Error("Invalid blockaddress block #");
2635 GlobalVariable *FwdRef = RefList[i].second;
2636 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2637 FwdRef->eraseFromParent();
2640 BlockAddrFwdRefs.erase(BAFRI);
2643 // Trim the value list down to the size it was before we parsed this function.
2644 ValueList.shrinkTo(ModuleValueListSize);
2645 MDValueList.shrinkTo(ModuleMDValueListSize);
2646 std::vector<BasicBlock*>().swap(FunctionBBs);
2650 /// FindFunctionInStream - Find the function body in the bitcode stream
2651 bool BitcodeReader::FindFunctionInStream(Function *F,
2652 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2653 while (DeferredFunctionInfoIterator->second == 0) {
2654 if (Stream.AtEndOfStream())
2655 return Error("Could not find Function in stream");
2656 // ParseModule will parse the next body in the stream and set its
2657 // position in the DeferredFunctionInfo map.
2658 if (ParseModule(true)) return true;
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!");
2683 // If its position is recorded as 0, its body is somewhere in the stream
2684 // but we haven't seen it yet.
2685 if (DFII->second == 0)
2686 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
2688 // Move the bit stream to the saved position of the deferred function body.
2689 Stream.JumpToBit(DFII->second);
2691 if (ParseFunctionBody(F)) {
2692 if (ErrInfo) *ErrInfo = ErrorString;
2696 // Upgrade any old intrinsic calls in the function.
2697 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2698 E = UpgradedIntrinsics.end(); I != E; ++I) {
2699 if (I->first != I->second) {
2700 for (Value::use_iterator UI = I->first->use_begin(),
2701 UE = I->first->use_end(); UI != UE; ) {
2702 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2703 UpgradeIntrinsicCall(CI, I->second);
2711 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2712 const Function *F = dyn_cast<Function>(GV);
2713 if (!F || F->isDeclaration())
2715 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2718 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2719 Function *F = dyn_cast<Function>(GV);
2720 // If this function isn't dematerializable, this is a noop.
2721 if (!F || !isDematerializable(F))
2724 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2726 // Just forget the function body, we can remat it later.
2731 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2732 assert(M == TheModule &&
2733 "Can only Materialize the Module this BitcodeReader is attached to.");
2734 // Iterate over the module, deserializing any functions that are still on
2736 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2738 if (F->isMaterializable() &&
2739 Materialize(F, ErrInfo))
2742 // At this point, if there are any function bodies, the current bit is
2743 // pointing to the END_BLOCK record after them. Now make sure the rest
2744 // of the bits in the module have been read.
2748 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2749 // delete the old functions to clean up. We can't do this unless the entire
2750 // module is materialized because there could always be another function body
2751 // with calls to the old function.
2752 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2753 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2754 if (I->first != I->second) {
2755 for (Value::use_iterator UI = I->first->use_begin(),
2756 UE = I->first->use_end(); UI != UE; ) {
2757 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2758 UpgradeIntrinsicCall(CI, I->second);
2760 if (!I->first->use_empty())
2761 I->first->replaceAllUsesWith(I->second);
2762 I->first->eraseFromParent();
2765 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2770 bool BitcodeReader::InitStream() {
2771 if (LazyStreamer) return InitLazyStream();
2772 return InitStreamFromBuffer();
2775 bool BitcodeReader::InitStreamFromBuffer() {
2776 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2777 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2779 if (Buffer->getBufferSize() & 3) {
2780 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2781 return Error("Invalid bitcode signature");
2783 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2786 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2787 // The magic number is 0x0B17C0DE stored in little endian.
2788 if (isBitcodeWrapper(BufPtr, BufEnd))
2789 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2790 return Error("Invalid bitcode wrapper header");
2792 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2793 Stream.init(*StreamFile);
2798 bool BitcodeReader::InitLazyStream() {
2799 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2801 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2802 StreamFile.reset(new BitstreamReader(Bytes));
2803 Stream.init(*StreamFile);
2805 unsigned char buf[16];
2806 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2807 return Error("Bitcode stream must be at least 16 bytes in length");
2809 if (!isBitcode(buf, buf + 16))
2810 return Error("Invalid bitcode signature");
2812 if (isBitcodeWrapper(buf, buf + 4)) {
2813 const unsigned char *bitcodeStart = buf;
2814 const unsigned char *bitcodeEnd = buf + 16;
2815 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2816 Bytes->dropLeadingBytes(bitcodeStart - buf);
2817 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2822 //===----------------------------------------------------------------------===//
2823 // External interface
2824 //===----------------------------------------------------------------------===//
2826 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2828 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2829 LLVMContext& Context,
2830 std::string *ErrMsg) {
2831 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2832 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2833 M->setMaterializer(R);
2834 if (R->ParseBitcodeInto(M)) {
2836 *ErrMsg = R->getErrorString();
2838 delete M; // Also deletes R.
2841 // Have the BitcodeReader dtor delete 'Buffer'.
2842 R->setBufferOwned(true);
2844 R->materializeForwardReferencedFunctions();
2850 Module *llvm::getStreamedBitcodeModule(const std::string &name,
2851 DataStreamer *streamer,
2852 LLVMContext &Context,
2853 std::string *ErrMsg) {
2854 Module *M = new Module(name, Context);
2855 BitcodeReader *R = new BitcodeReader(streamer, Context);
2856 M->setMaterializer(R);
2857 if (R->ParseBitcodeInto(M)) {
2859 *ErrMsg = R->getErrorString();
2860 delete M; // Also deletes R.
2863 R->setBufferOwned(false); // no buffer to delete
2867 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2868 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2869 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2870 std::string *ErrMsg){
2871 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2874 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2875 // there was an error.
2876 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2878 // Read in the entire module, and destroy the BitcodeReader.
2879 if (M->MaterializeAllPermanently(ErrMsg)) {
2884 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2885 // written. We must defer until the Module has been fully materialized.
2890 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2891 LLVMContext& Context,
2892 std::string *ErrMsg) {
2893 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2894 // Don't let the BitcodeReader dtor delete 'Buffer'.
2895 R->setBufferOwned(false);
2897 std::string Triple("");
2898 if (R->ParseTriple(Triple))
2900 *ErrMsg = R->getErrorString();