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 // FIXME : Remove this autoupgrade code in LLVM 3.0.
462 // If Function attributes are using index 0 then transfer them
463 // to index ~0. Index 0 is used for return value attributes but used to be
464 // used for function attributes.
465 Attributes RetAttribute;
466 Attributes FnAttribute;
467 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
468 // FIXME: remove in LLVM 3.0
469 // The alignment is stored as a 16-bit raw value from bits 31--16.
470 // We shift the bits above 31 down by 11 bits.
472 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
473 if (Alignment && !isPowerOf2_32(Alignment))
474 return Error("Alignment is not a power of two.");
476 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
478 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
480 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
482 Record[i+1] = ReconstitutedAttr.Raw();
484 RetAttribute = ReconstitutedAttr;
485 else if (Record[i] == ~0U)
486 FnAttribute = ReconstitutedAttr;
489 Attributes OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
490 Attribute::ReadOnly|Attribute::ReadNone);
492 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
493 (RetAttribute & OldRetAttrs)) {
494 if (FnAttribute == Attribute::None) { // add a slot so they get added.
495 Record.push_back(~0U);
499 FnAttribute |= RetAttribute & OldRetAttrs;
500 RetAttribute &= ~OldRetAttrs;
503 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
504 if (Record[i] == 0) {
505 if (RetAttribute != Attribute::None)
506 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
507 } else if (Record[i] == ~0U) {
508 if (FnAttribute != Attribute::None)
509 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
510 } else if (Attributes(Record[i+1]) != Attribute::None)
511 Attrs.push_back(AttributeWithIndex::get(Record[i],
512 Attributes(Record[i+1])));
515 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
523 bool BitcodeReader::ParseTypeTable() {
524 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
525 return Error("Malformed block record");
527 return ParseTypeTableBody();
530 bool BitcodeReader::ParseTypeTableBody() {
531 if (!TypeList.empty())
532 return Error("Multiple TYPE_BLOCKs found!");
534 SmallVector<uint64_t, 64> Record;
535 unsigned NumRecords = 0;
537 SmallString<64> TypeName;
539 // Read all the records for this type table.
541 unsigned Code = Stream.ReadCode();
542 if (Code == bitc::END_BLOCK) {
543 if (NumRecords != TypeList.size())
544 return Error("Invalid type forward reference in TYPE_BLOCK");
545 if (Stream.ReadBlockEnd())
546 return Error("Error at end of type table block");
550 if (Code == bitc::ENTER_SUBBLOCK) {
551 // No known subblocks, always skip them.
552 Stream.ReadSubBlockID();
553 if (Stream.SkipBlock())
554 return Error("Malformed block record");
558 if (Code == bitc::DEFINE_ABBREV) {
559 Stream.ReadAbbrevRecord();
566 switch (Stream.ReadRecord(Code, Record)) {
567 default: return Error("unknown type in type table");
568 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
569 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
570 // type list. This allows us to reserve space.
571 if (Record.size() < 1)
572 return Error("Invalid TYPE_CODE_NUMENTRY record");
573 TypeList.resize(Record[0]);
575 case bitc::TYPE_CODE_VOID: // VOID
576 ResultTy = Type::getVoidTy(Context);
578 case bitc::TYPE_CODE_HALF: // HALF
579 ResultTy = Type::getHalfTy(Context);
581 case bitc::TYPE_CODE_FLOAT: // FLOAT
582 ResultTy = Type::getFloatTy(Context);
584 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
585 ResultTy = Type::getDoubleTy(Context);
587 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
588 ResultTy = Type::getX86_FP80Ty(Context);
590 case bitc::TYPE_CODE_FP128: // FP128
591 ResultTy = Type::getFP128Ty(Context);
593 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
594 ResultTy = Type::getPPC_FP128Ty(Context);
596 case bitc::TYPE_CODE_LABEL: // LABEL
597 ResultTy = Type::getLabelTy(Context);
599 case bitc::TYPE_CODE_METADATA: // METADATA
600 ResultTy = Type::getMetadataTy(Context);
602 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
603 ResultTy = Type::getX86_MMXTy(Context);
605 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
606 if (Record.size() < 1)
607 return Error("Invalid Integer type record");
609 ResultTy = IntegerType::get(Context, Record[0]);
611 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
612 // [pointee type, address space]
613 if (Record.size() < 1)
614 return Error("Invalid POINTER type record");
615 unsigned AddressSpace = 0;
616 if (Record.size() == 2)
617 AddressSpace = Record[1];
618 ResultTy = getTypeByID(Record[0]);
619 if (ResultTy == 0) return Error("invalid element type in pointer type");
620 ResultTy = PointerType::get(ResultTy, AddressSpace);
623 case bitc::TYPE_CODE_FUNCTION_OLD: {
624 // FIXME: attrid is dead, remove it in LLVM 3.0
625 // FUNCTION: [vararg, attrid, retty, paramty x N]
626 if (Record.size() < 3)
627 return Error("Invalid FUNCTION type record");
628 SmallVector<Type*, 8> ArgTys;
629 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
630 if (Type *T = getTypeByID(Record[i]))
636 ResultTy = getTypeByID(Record[2]);
637 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
638 return Error("invalid type in function type");
640 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
643 case bitc::TYPE_CODE_FUNCTION: {
644 // FUNCTION: [vararg, retty, paramty x N]
645 if (Record.size() < 2)
646 return Error("Invalid FUNCTION type record");
647 SmallVector<Type*, 8> ArgTys;
648 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
649 if (Type *T = getTypeByID(Record[i]))
655 ResultTy = getTypeByID(Record[1]);
656 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
657 return Error("invalid type in function type");
659 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
662 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
663 if (Record.size() < 1)
664 return Error("Invalid STRUCT type record");
665 SmallVector<Type*, 8> EltTys;
666 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
667 if (Type *T = getTypeByID(Record[i]))
672 if (EltTys.size() != Record.size()-1)
673 return Error("invalid type in struct type");
674 ResultTy = StructType::get(Context, EltTys, Record[0]);
677 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
678 if (ConvertToString(Record, 0, TypeName))
679 return Error("Invalid STRUCT_NAME record");
682 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
683 if (Record.size() < 1)
684 return Error("Invalid STRUCT type record");
686 if (NumRecords >= TypeList.size())
687 return Error("invalid TYPE table");
689 // Check to see if this was forward referenced, if so fill in the temp.
690 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
692 Res->setName(TypeName);
693 TypeList[NumRecords] = 0;
694 } else // Otherwise, create a new struct.
695 Res = StructType::create(Context, TypeName);
698 SmallVector<Type*, 8> EltTys;
699 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
700 if (Type *T = getTypeByID(Record[i]))
705 if (EltTys.size() != Record.size()-1)
706 return Error("invalid STRUCT type record");
707 Res->setBody(EltTys, Record[0]);
711 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
712 if (Record.size() != 1)
713 return Error("Invalid OPAQUE type record");
715 if (NumRecords >= TypeList.size())
716 return Error("invalid TYPE table");
718 // Check to see if this was forward referenced, if so fill in the temp.
719 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
721 Res->setName(TypeName);
722 TypeList[NumRecords] = 0;
723 } else // Otherwise, create a new struct with no body.
724 Res = StructType::create(Context, TypeName);
729 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
730 if (Record.size() < 2)
731 return Error("Invalid ARRAY type record");
732 if ((ResultTy = getTypeByID(Record[1])))
733 ResultTy = ArrayType::get(ResultTy, Record[0]);
735 return Error("Invalid ARRAY type element");
737 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
738 if (Record.size() < 2)
739 return Error("Invalid VECTOR type record");
740 if ((ResultTy = getTypeByID(Record[1])))
741 ResultTy = VectorType::get(ResultTy, Record[0]);
743 return Error("Invalid ARRAY type element");
747 if (NumRecords >= TypeList.size())
748 return Error("invalid TYPE table");
749 assert(ResultTy && "Didn't read a type?");
750 assert(TypeList[NumRecords] == 0 && "Already read type?");
751 TypeList[NumRecords++] = ResultTy;
755 bool BitcodeReader::ParseValueSymbolTable() {
756 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
757 return Error("Malformed block record");
759 SmallVector<uint64_t, 64> Record;
761 // Read all the records for this value table.
762 SmallString<128> ValueName;
764 unsigned Code = Stream.ReadCode();
765 if (Code == bitc::END_BLOCK) {
766 if (Stream.ReadBlockEnd())
767 return Error("Error at end of value symbol table block");
770 if (Code == bitc::ENTER_SUBBLOCK) {
771 // No known subblocks, always skip them.
772 Stream.ReadSubBlockID();
773 if (Stream.SkipBlock())
774 return Error("Malformed block record");
778 if (Code == bitc::DEFINE_ABBREV) {
779 Stream.ReadAbbrevRecord();
785 switch (Stream.ReadRecord(Code, Record)) {
786 default: // Default behavior: unknown type.
788 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
789 if (ConvertToString(Record, 1, ValueName))
790 return Error("Invalid VST_ENTRY record");
791 unsigned ValueID = Record[0];
792 if (ValueID >= ValueList.size())
793 return Error("Invalid Value ID in VST_ENTRY record");
794 Value *V = ValueList[ValueID];
796 V->setName(StringRef(ValueName.data(), ValueName.size()));
800 case bitc::VST_CODE_BBENTRY: {
801 if (ConvertToString(Record, 1, ValueName))
802 return Error("Invalid VST_BBENTRY record");
803 BasicBlock *BB = getBasicBlock(Record[0]);
805 return Error("Invalid BB ID in VST_BBENTRY record");
807 BB->setName(StringRef(ValueName.data(), ValueName.size()));
815 bool BitcodeReader::ParseMetadata() {
816 unsigned NextMDValueNo = MDValueList.size();
818 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
819 return Error("Malformed block record");
821 SmallVector<uint64_t, 64> Record;
823 // Read all the records.
825 unsigned Code = Stream.ReadCode();
826 if (Code == bitc::END_BLOCK) {
827 if (Stream.ReadBlockEnd())
828 return Error("Error at end of PARAMATTR block");
832 if (Code == bitc::ENTER_SUBBLOCK) {
833 // No known subblocks, always skip them.
834 Stream.ReadSubBlockID();
835 if (Stream.SkipBlock())
836 return Error("Malformed block record");
840 if (Code == bitc::DEFINE_ABBREV) {
841 Stream.ReadAbbrevRecord();
845 bool IsFunctionLocal = false;
848 Code = Stream.ReadRecord(Code, Record);
850 default: // Default behavior: ignore.
852 case bitc::METADATA_NAME: {
853 // Read named of the named metadata.
854 unsigned NameLength = Record.size();
856 Name.resize(NameLength);
857 for (unsigned i = 0; i != NameLength; ++i)
860 Code = Stream.ReadCode();
862 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
863 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
864 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
866 // Read named metadata elements.
867 unsigned Size = Record.size();
868 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
869 for (unsigned i = 0; i != Size; ++i) {
870 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
872 return Error("Malformed metadata record");
877 case bitc::METADATA_FN_NODE:
878 IsFunctionLocal = true;
880 case bitc::METADATA_NODE: {
881 if (Record.size() % 2 == 1)
882 return Error("Invalid METADATA_NODE record");
884 unsigned Size = Record.size();
885 SmallVector<Value*, 8> Elts;
886 for (unsigned i = 0; i != Size; i += 2) {
887 Type *Ty = getTypeByID(Record[i]);
888 if (!Ty) return Error("Invalid METADATA_NODE record");
889 if (Ty->isMetadataTy())
890 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
891 else if (!Ty->isVoidTy())
892 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
894 Elts.push_back(NULL);
896 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
897 IsFunctionLocal = false;
898 MDValueList.AssignValue(V, NextMDValueNo++);
901 case bitc::METADATA_STRING: {
902 unsigned MDStringLength = Record.size();
903 SmallString<8> String;
904 String.resize(MDStringLength);
905 for (unsigned i = 0; i != MDStringLength; ++i)
906 String[i] = Record[i];
907 Value *V = MDString::get(Context,
908 StringRef(String.data(), String.size()));
909 MDValueList.AssignValue(V, NextMDValueNo++);
912 case bitc::METADATA_KIND: {
913 unsigned RecordLength = Record.size();
914 if (Record.empty() || RecordLength < 2)
915 return Error("Invalid METADATA_KIND record");
917 Name.resize(RecordLength-1);
918 unsigned Kind = Record[0];
919 for (unsigned i = 1; i != RecordLength; ++i)
920 Name[i-1] = Record[i];
922 unsigned NewKind = TheModule->getMDKindID(Name.str());
923 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
924 return Error("Conflicting METADATA_KIND records");
931 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
932 /// the LSB for dense VBR encoding.
933 static uint64_t DecodeSignRotatedValue(uint64_t V) {
938 // There is no such thing as -0 with integers. "-0" really means MININT.
942 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
943 /// values and aliases that we can.
944 bool BitcodeReader::ResolveGlobalAndAliasInits() {
945 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
946 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
948 GlobalInitWorklist.swap(GlobalInits);
949 AliasInitWorklist.swap(AliasInits);
951 while (!GlobalInitWorklist.empty()) {
952 unsigned ValID = GlobalInitWorklist.back().second;
953 if (ValID >= ValueList.size()) {
954 // Not ready to resolve this yet, it requires something later in the file.
955 GlobalInits.push_back(GlobalInitWorklist.back());
957 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
958 GlobalInitWorklist.back().first->setInitializer(C);
960 return Error("Global variable initializer is not a constant!");
962 GlobalInitWorklist.pop_back();
965 while (!AliasInitWorklist.empty()) {
966 unsigned ValID = AliasInitWorklist.back().second;
967 if (ValID >= ValueList.size()) {
968 AliasInits.push_back(AliasInitWorklist.back());
970 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
971 AliasInitWorklist.back().first->setAliasee(C);
973 return Error("Alias initializer is not a constant!");
975 AliasInitWorklist.pop_back();
980 bool BitcodeReader::ParseConstants() {
981 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
982 return Error("Malformed block record");
984 SmallVector<uint64_t, 64> Record;
986 // Read all the records for this value table.
987 Type *CurTy = Type::getInt32Ty(Context);
988 unsigned NextCstNo = ValueList.size();
990 unsigned Code = Stream.ReadCode();
991 if (Code == bitc::END_BLOCK)
994 if (Code == bitc::ENTER_SUBBLOCK) {
995 // No known subblocks, always skip them.
996 Stream.ReadSubBlockID();
997 if (Stream.SkipBlock())
998 return Error("Malformed block record");
1002 if (Code == bitc::DEFINE_ABBREV) {
1003 Stream.ReadAbbrevRecord();
1010 unsigned BitCode = Stream.ReadRecord(Code, Record);
1012 default: // Default behavior: unknown constant
1013 case bitc::CST_CODE_UNDEF: // UNDEF
1014 V = UndefValue::get(CurTy);
1016 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1018 return Error("Malformed CST_SETTYPE record");
1019 if (Record[0] >= TypeList.size())
1020 return Error("Invalid Type ID in CST_SETTYPE record");
1021 CurTy = TypeList[Record[0]];
1022 continue; // Skip the ValueList manipulation.
1023 case bitc::CST_CODE_NULL: // NULL
1024 V = Constant::getNullValue(CurTy);
1026 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1027 if (!CurTy->isIntegerTy() || Record.empty())
1028 return Error("Invalid CST_INTEGER record");
1029 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
1031 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1032 if (!CurTy->isIntegerTy() || Record.empty())
1033 return Error("Invalid WIDE_INTEGER record");
1035 unsigned NumWords = Record.size();
1036 SmallVector<uint64_t, 8> Words;
1037 Words.resize(NumWords);
1038 for (unsigned i = 0; i != NumWords; ++i)
1039 Words[i] = DecodeSignRotatedValue(Record[i]);
1040 V = ConstantInt::get(Context,
1041 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
1045 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1047 return Error("Invalid FLOAT record");
1048 if (CurTy->isHalfTy())
1049 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1050 else if (CurTy->isFloatTy())
1051 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1052 else if (CurTy->isDoubleTy())
1053 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1054 else if (CurTy->isX86_FP80Ty()) {
1055 // Bits are not stored the same way as a normal i80 APInt, compensate.
1056 uint64_t Rearrange[2];
1057 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1058 Rearrange[1] = Record[0] >> 48;
1059 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1060 } else if (CurTy->isFP128Ty())
1061 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1062 else if (CurTy->isPPC_FP128Ty())
1063 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1065 V = UndefValue::get(CurTy);
1069 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1071 return Error("Invalid CST_AGGREGATE record");
1073 unsigned Size = Record.size();
1074 SmallVector<Constant*, 16> Elts;
1076 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1077 for (unsigned i = 0; i != Size; ++i)
1078 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1079 STy->getElementType(i)));
1080 V = ConstantStruct::get(STy, Elts);
1081 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1082 Type *EltTy = ATy->getElementType();
1083 for (unsigned i = 0; i != Size; ++i)
1084 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1085 V = ConstantArray::get(ATy, Elts);
1086 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1087 Type *EltTy = VTy->getElementType();
1088 for (unsigned i = 0; i != Size; ++i)
1089 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1090 V = ConstantVector::get(Elts);
1092 V = UndefValue::get(CurTy);
1096 case bitc::CST_CODE_STRING: // STRING: [values]
1097 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1099 return Error("Invalid CST_STRING record");
1101 unsigned Size = Record.size();
1102 SmallString<16> Elts;
1103 for (unsigned i = 0; i != Size; ++i)
1104 Elts.push_back(Record[i]);
1105 V = ConstantDataArray::getString(Context, Elts,
1106 BitCode == bitc::CST_CODE_CSTRING);
1109 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1111 return Error("Invalid CST_DATA record");
1113 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1114 unsigned Size = Record.size();
1116 if (EltTy->isIntegerTy(8)) {
1117 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1118 if (isa<VectorType>(CurTy))
1119 V = ConstantDataVector::get(Context, Elts);
1121 V = ConstantDataArray::get(Context, Elts);
1122 } else if (EltTy->isIntegerTy(16)) {
1123 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1124 if (isa<VectorType>(CurTy))
1125 V = ConstantDataVector::get(Context, Elts);
1127 V = ConstantDataArray::get(Context, Elts);
1128 } else if (EltTy->isIntegerTy(32)) {
1129 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1130 if (isa<VectorType>(CurTy))
1131 V = ConstantDataVector::get(Context, Elts);
1133 V = ConstantDataArray::get(Context, Elts);
1134 } else if (EltTy->isIntegerTy(64)) {
1135 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1136 if (isa<VectorType>(CurTy))
1137 V = ConstantDataVector::get(Context, Elts);
1139 V = ConstantDataArray::get(Context, Elts);
1140 } else if (EltTy->isFloatTy()) {
1141 SmallVector<float, 16> Elts;
1142 for (unsigned i = 0; i != Size; ++i) {
1143 union { uint32_t I; float F; };
1147 if (isa<VectorType>(CurTy))
1148 V = ConstantDataVector::get(Context, Elts);
1150 V = ConstantDataArray::get(Context, Elts);
1151 } else if (EltTy->isDoubleTy()) {
1152 SmallVector<double, 16> Elts;
1153 for (unsigned i = 0; i != Size; ++i) {
1154 union { uint64_t I; double F; };
1158 if (isa<VectorType>(CurTy))
1159 V = ConstantDataVector::get(Context, Elts);
1161 V = ConstantDataArray::get(Context, Elts);
1163 return Error("Unknown element type in CE_DATA");
1168 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1169 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1170 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1172 V = UndefValue::get(CurTy); // Unknown binop.
1174 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1175 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1177 if (Record.size() >= 4) {
1178 if (Opc == Instruction::Add ||
1179 Opc == Instruction::Sub ||
1180 Opc == Instruction::Mul ||
1181 Opc == Instruction::Shl) {
1182 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1183 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1184 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1185 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1186 } else if (Opc == Instruction::SDiv ||
1187 Opc == Instruction::UDiv ||
1188 Opc == Instruction::LShr ||
1189 Opc == Instruction::AShr) {
1190 if (Record[3] & (1 << bitc::PEO_EXACT))
1191 Flags |= SDivOperator::IsExact;
1194 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1198 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1199 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1200 int Opc = GetDecodedCastOpcode(Record[0]);
1202 V = UndefValue::get(CurTy); // Unknown cast.
1204 Type *OpTy = getTypeByID(Record[1]);
1205 if (!OpTy) return Error("Invalid CE_CAST record");
1206 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1207 V = ConstantExpr::getCast(Opc, Op, CurTy);
1211 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1212 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1213 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1214 SmallVector<Constant*, 16> Elts;
1215 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1216 Type *ElTy = getTypeByID(Record[i]);
1217 if (!ElTy) return Error("Invalid CE_GEP record");
1218 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1220 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1221 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1223 bitc::CST_CODE_CE_INBOUNDS_GEP);
1226 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1227 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1228 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1229 Type::getInt1Ty(Context)),
1230 ValueList.getConstantFwdRef(Record[1],CurTy),
1231 ValueList.getConstantFwdRef(Record[2],CurTy));
1233 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1234 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1236 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1237 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1238 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1239 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1240 V = ConstantExpr::getExtractElement(Op0, Op1);
1243 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1244 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1245 if (Record.size() < 3 || OpTy == 0)
1246 return Error("Invalid CE_INSERTELT record");
1247 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1248 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1249 OpTy->getElementType());
1250 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1251 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1254 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1255 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1256 if (Record.size() < 3 || OpTy == 0)
1257 return Error("Invalid CE_SHUFFLEVEC record");
1258 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1259 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1260 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1261 OpTy->getNumElements());
1262 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1263 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1266 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1267 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1269 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1270 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1271 return Error("Invalid CE_SHUFVEC_EX record");
1272 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1273 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1274 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1275 RTy->getNumElements());
1276 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1277 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1280 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1281 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1282 Type *OpTy = getTypeByID(Record[0]);
1283 if (OpTy == 0) return Error("Invalid CE_CMP record");
1284 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1285 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1287 if (OpTy->isFPOrFPVectorTy())
1288 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1290 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1293 case bitc::CST_CODE_INLINEASM: {
1294 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1295 std::string AsmStr, ConstrStr;
1296 bool HasSideEffects = Record[0] & 1;
1297 bool IsAlignStack = Record[0] >> 1;
1298 unsigned AsmStrSize = Record[1];
1299 if (2+AsmStrSize >= Record.size())
1300 return Error("Invalid INLINEASM record");
1301 unsigned ConstStrSize = Record[2+AsmStrSize];
1302 if (3+AsmStrSize+ConstStrSize > Record.size())
1303 return Error("Invalid INLINEASM record");
1305 for (unsigned i = 0; i != AsmStrSize; ++i)
1306 AsmStr += (char)Record[2+i];
1307 for (unsigned i = 0; i != ConstStrSize; ++i)
1308 ConstrStr += (char)Record[3+AsmStrSize+i];
1309 PointerType *PTy = cast<PointerType>(CurTy);
1310 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1311 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1314 case bitc::CST_CODE_BLOCKADDRESS:{
1315 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1316 Type *FnTy = getTypeByID(Record[0]);
1317 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1319 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1320 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1322 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1323 Type::getInt8Ty(Context),
1324 false, GlobalValue::InternalLinkage,
1326 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1332 ValueList.AssignValue(V, NextCstNo);
1336 if (NextCstNo != ValueList.size())
1337 return Error("Invalid constant reference!");
1339 if (Stream.ReadBlockEnd())
1340 return Error("Error at end of constants block");
1342 // Once all the constants have been read, go through and resolve forward
1344 ValueList.ResolveConstantForwardRefs();
1348 bool BitcodeReader::ParseUseLists() {
1349 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1350 return Error("Malformed block record");
1352 SmallVector<uint64_t, 64> Record;
1354 // Read all the records.
1356 unsigned Code = Stream.ReadCode();
1357 if (Code == bitc::END_BLOCK) {
1358 if (Stream.ReadBlockEnd())
1359 return Error("Error at end of use-list table block");
1363 if (Code == bitc::ENTER_SUBBLOCK) {
1364 // No known subblocks, always skip them.
1365 Stream.ReadSubBlockID();
1366 if (Stream.SkipBlock())
1367 return Error("Malformed block record");
1371 if (Code == bitc::DEFINE_ABBREV) {
1372 Stream.ReadAbbrevRecord();
1376 // Read a use list record.
1378 switch (Stream.ReadRecord(Code, Record)) {
1379 default: // Default behavior: unknown type.
1381 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1382 unsigned RecordLength = Record.size();
1383 if (RecordLength < 1)
1384 return Error ("Invalid UseList reader!");
1385 UseListRecords.push_back(Record);
1392 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1393 /// remember where it is and then skip it. This lets us lazily deserialize the
1395 bool BitcodeReader::RememberAndSkipFunctionBody() {
1396 // Get the function we are talking about.
1397 if (FunctionsWithBodies.empty())
1398 return Error("Insufficient function protos");
1400 Function *Fn = FunctionsWithBodies.back();
1401 FunctionsWithBodies.pop_back();
1403 // Save the current stream state.
1404 uint64_t CurBit = Stream.GetCurrentBitNo();
1405 DeferredFunctionInfo[Fn] = CurBit;
1407 // Skip over the function block for now.
1408 if (Stream.SkipBlock())
1409 return Error("Malformed block record");
1413 bool BitcodeReader::GlobalCleanup() {
1414 // Patch the initializers for globals and aliases up.
1415 ResolveGlobalAndAliasInits();
1416 if (!GlobalInits.empty() || !AliasInits.empty())
1417 return Error("Malformed global initializer set");
1419 // Look for intrinsic functions which need to be upgraded at some point
1420 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1423 if (UpgradeIntrinsicFunction(FI, NewFn))
1424 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1427 // Look for global variables which need to be renamed.
1428 for (Module::global_iterator
1429 GI = TheModule->global_begin(), GE = TheModule->global_end();
1431 UpgradeGlobalVariable(GI);
1432 // Force deallocation of memory for these vectors to favor the client that
1433 // want lazy deserialization.
1434 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1435 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1439 bool BitcodeReader::ParseModule(bool Resume) {
1441 Stream.JumpToBit(NextUnreadBit);
1442 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1443 return Error("Malformed block record");
1445 SmallVector<uint64_t, 64> Record;
1446 std::vector<std::string> SectionTable;
1447 std::vector<std::string> GCTable;
1449 // Read all the records for this module.
1450 while (!Stream.AtEndOfStream()) {
1451 unsigned Code = Stream.ReadCode();
1452 if (Code == bitc::END_BLOCK) {
1453 if (Stream.ReadBlockEnd())
1454 return Error("Error at end of module block");
1456 return GlobalCleanup();
1459 if (Code == bitc::ENTER_SUBBLOCK) {
1460 switch (Stream.ReadSubBlockID()) {
1461 default: // Skip unknown content.
1462 if (Stream.SkipBlock())
1463 return Error("Malformed block record");
1465 case bitc::BLOCKINFO_BLOCK_ID:
1466 if (Stream.ReadBlockInfoBlock())
1467 return Error("Malformed BlockInfoBlock");
1469 case bitc::PARAMATTR_BLOCK_ID:
1470 if (ParseAttributeBlock())
1473 case bitc::TYPE_BLOCK_ID_NEW:
1474 if (ParseTypeTable())
1477 case bitc::VALUE_SYMTAB_BLOCK_ID:
1478 if (ParseValueSymbolTable())
1480 SeenValueSymbolTable = true;
1482 case bitc::CONSTANTS_BLOCK_ID:
1483 if (ParseConstants() || ResolveGlobalAndAliasInits())
1486 case bitc::METADATA_BLOCK_ID:
1487 if (ParseMetadata())
1490 case bitc::FUNCTION_BLOCK_ID:
1491 // If this is the first function body we've seen, reverse the
1492 // FunctionsWithBodies list.
1493 if (!SeenFirstFunctionBody) {
1494 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1495 if (GlobalCleanup())
1497 SeenFirstFunctionBody = true;
1500 if (RememberAndSkipFunctionBody())
1502 // For streaming bitcode, suspend parsing when we reach the function
1503 // bodies. Subsequent materialization calls will resume it when
1504 // necessary. For streaming, the function bodies must be at the end of
1505 // the bitcode. If the bitcode file is old, the symbol table will be
1506 // at the end instead and will not have been seen yet. In this case,
1507 // just finish the parse now.
1508 if (LazyStreamer && SeenValueSymbolTable) {
1509 NextUnreadBit = Stream.GetCurrentBitNo();
1513 case bitc::USELIST_BLOCK_ID:
1514 if (ParseUseLists())
1521 if (Code == bitc::DEFINE_ABBREV) {
1522 Stream.ReadAbbrevRecord();
1527 switch (Stream.ReadRecord(Code, Record)) {
1528 default: break; // Default behavior, ignore unknown content.
1529 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1530 if (Record.size() < 1)
1531 return Error("Malformed MODULE_CODE_VERSION");
1532 // Only version #0 is supported so far.
1534 return Error("Unknown bitstream version!");
1536 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1538 if (ConvertToString(Record, 0, S))
1539 return Error("Invalid MODULE_CODE_TRIPLE record");
1540 TheModule->setTargetTriple(S);
1543 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1545 if (ConvertToString(Record, 0, S))
1546 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1547 TheModule->setDataLayout(S);
1550 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1552 if (ConvertToString(Record, 0, S))
1553 return Error("Invalid MODULE_CODE_ASM record");
1554 TheModule->setModuleInlineAsm(S);
1557 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1559 if (ConvertToString(Record, 0, S))
1560 return Error("Invalid MODULE_CODE_DEPLIB record");
1561 TheModule->addLibrary(S);
1564 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1566 if (ConvertToString(Record, 0, S))
1567 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1568 SectionTable.push_back(S);
1571 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1573 if (ConvertToString(Record, 0, S))
1574 return Error("Invalid MODULE_CODE_GCNAME record");
1575 GCTable.push_back(S);
1578 // GLOBALVAR: [pointer type, isconst, initid,
1579 // linkage, alignment, section, visibility, threadlocal,
1581 case bitc::MODULE_CODE_GLOBALVAR: {
1582 if (Record.size() < 6)
1583 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1584 Type *Ty = getTypeByID(Record[0]);
1585 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1586 if (!Ty->isPointerTy())
1587 return Error("Global not a pointer type!");
1588 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1589 Ty = cast<PointerType>(Ty)->getElementType();
1591 bool isConstant = Record[1];
1592 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1593 unsigned Alignment = (1 << Record[4]) >> 1;
1594 std::string Section;
1596 if (Record[5]-1 >= SectionTable.size())
1597 return Error("Invalid section ID");
1598 Section = SectionTable[Record[5]-1];
1600 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1601 if (Record.size() > 6)
1602 Visibility = GetDecodedVisibility(Record[6]);
1603 bool isThreadLocal = false;
1604 if (Record.size() > 7)
1605 isThreadLocal = Record[7];
1607 bool UnnamedAddr = false;
1608 if (Record.size() > 8)
1609 UnnamedAddr = Record[8];
1611 GlobalVariable *NewGV =
1612 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1613 isThreadLocal, AddressSpace);
1614 NewGV->setAlignment(Alignment);
1615 if (!Section.empty())
1616 NewGV->setSection(Section);
1617 NewGV->setVisibility(Visibility);
1618 NewGV->setThreadLocal(isThreadLocal);
1619 NewGV->setUnnamedAddr(UnnamedAddr);
1621 ValueList.push_back(NewGV);
1623 // Remember which value to use for the global initializer.
1624 if (unsigned InitID = Record[2])
1625 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1628 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1629 // alignment, section, visibility, gc, unnamed_addr]
1630 case bitc::MODULE_CODE_FUNCTION: {
1631 if (Record.size() < 8)
1632 return Error("Invalid MODULE_CODE_FUNCTION record");
1633 Type *Ty = getTypeByID(Record[0]);
1634 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1635 if (!Ty->isPointerTy())
1636 return Error("Function not a pointer type!");
1638 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1640 return Error("Function not a pointer to function type!");
1642 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1645 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1646 bool isProto = Record[2];
1647 Func->setLinkage(GetDecodedLinkage(Record[3]));
1648 Func->setAttributes(getAttributes(Record[4]));
1650 Func->setAlignment((1 << Record[5]) >> 1);
1652 if (Record[6]-1 >= SectionTable.size())
1653 return Error("Invalid section ID");
1654 Func->setSection(SectionTable[Record[6]-1]);
1656 Func->setVisibility(GetDecodedVisibility(Record[7]));
1657 if (Record.size() > 8 && Record[8]) {
1658 if (Record[8]-1 > GCTable.size())
1659 return Error("Invalid GC ID");
1660 Func->setGC(GCTable[Record[8]-1].c_str());
1662 bool UnnamedAddr = false;
1663 if (Record.size() > 9)
1664 UnnamedAddr = Record[9];
1665 Func->setUnnamedAddr(UnnamedAddr);
1666 ValueList.push_back(Func);
1668 // If this is a function with a body, remember the prototype we are
1669 // creating now, so that we can match up the body with them later.
1671 FunctionsWithBodies.push_back(Func);
1672 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1676 // ALIAS: [alias type, aliasee val#, linkage]
1677 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1678 case bitc::MODULE_CODE_ALIAS: {
1679 if (Record.size() < 3)
1680 return Error("Invalid MODULE_ALIAS record");
1681 Type *Ty = getTypeByID(Record[0]);
1682 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1683 if (!Ty->isPointerTy())
1684 return Error("Function not a pointer type!");
1686 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1688 // Old bitcode files didn't have visibility field.
1689 if (Record.size() > 3)
1690 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1691 ValueList.push_back(NewGA);
1692 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1695 /// MODULE_CODE_PURGEVALS: [numvals]
1696 case bitc::MODULE_CODE_PURGEVALS:
1697 // Trim down the value list to the specified size.
1698 if (Record.size() < 1 || Record[0] > ValueList.size())
1699 return Error("Invalid MODULE_PURGEVALS record");
1700 ValueList.shrinkTo(Record[0]);
1706 return Error("Premature end of bitstream");
1709 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1712 if (InitStream()) return true;
1714 // Sniff for the signature.
1715 if (Stream.Read(8) != 'B' ||
1716 Stream.Read(8) != 'C' ||
1717 Stream.Read(4) != 0x0 ||
1718 Stream.Read(4) != 0xC ||
1719 Stream.Read(4) != 0xE ||
1720 Stream.Read(4) != 0xD)
1721 return Error("Invalid bitcode signature");
1723 // We expect a number of well-defined blocks, though we don't necessarily
1724 // need to understand them all.
1725 while (!Stream.AtEndOfStream()) {
1726 unsigned Code = Stream.ReadCode();
1728 if (Code != bitc::ENTER_SUBBLOCK) {
1730 // The ranlib in xcode 4 will align archive members by appending newlines
1731 // to the end of them. If this file size is a multiple of 4 but not 8, we
1732 // have to read and ignore these final 4 bytes :-(
1733 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1734 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1735 Stream.AtEndOfStream())
1738 return Error("Invalid record at top-level");
1741 unsigned BlockID = Stream.ReadSubBlockID();
1743 // We only know the MODULE subblock ID.
1745 case bitc::BLOCKINFO_BLOCK_ID:
1746 if (Stream.ReadBlockInfoBlock())
1747 return Error("Malformed BlockInfoBlock");
1749 case bitc::MODULE_BLOCK_ID:
1750 // Reject multiple MODULE_BLOCK's in a single bitstream.
1752 return Error("Multiple MODULE_BLOCKs in same stream");
1754 if (ParseModule(false))
1756 if (LazyStreamer) return false;
1759 if (Stream.SkipBlock())
1760 return Error("Malformed block record");
1768 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1769 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1770 return Error("Malformed block record");
1772 SmallVector<uint64_t, 64> Record;
1774 // Read all the records for this module.
1775 while (!Stream.AtEndOfStream()) {
1776 unsigned Code = Stream.ReadCode();
1777 if (Code == bitc::END_BLOCK) {
1778 if (Stream.ReadBlockEnd())
1779 return Error("Error at end of module block");
1784 if (Code == bitc::ENTER_SUBBLOCK) {
1785 switch (Stream.ReadSubBlockID()) {
1786 default: // Skip unknown content.
1787 if (Stream.SkipBlock())
1788 return Error("Malformed block record");
1794 if (Code == bitc::DEFINE_ABBREV) {
1795 Stream.ReadAbbrevRecord();
1800 switch (Stream.ReadRecord(Code, Record)) {
1801 default: break; // Default behavior, ignore unknown content.
1802 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1803 if (Record.size() < 1)
1804 return Error("Malformed MODULE_CODE_VERSION");
1805 // Only version #0 is supported so far.
1807 return Error("Unknown bitstream version!");
1809 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1811 if (ConvertToString(Record, 0, S))
1812 return Error("Invalid MODULE_CODE_TRIPLE record");
1820 return Error("Premature end of bitstream");
1823 bool BitcodeReader::ParseTriple(std::string &Triple) {
1824 if (InitStream()) return true;
1826 // Sniff for the signature.
1827 if (Stream.Read(8) != 'B' ||
1828 Stream.Read(8) != 'C' ||
1829 Stream.Read(4) != 0x0 ||
1830 Stream.Read(4) != 0xC ||
1831 Stream.Read(4) != 0xE ||
1832 Stream.Read(4) != 0xD)
1833 return Error("Invalid bitcode signature");
1835 // We expect a number of well-defined blocks, though we don't necessarily
1836 // need to understand them all.
1837 while (!Stream.AtEndOfStream()) {
1838 unsigned Code = Stream.ReadCode();
1840 if (Code != bitc::ENTER_SUBBLOCK)
1841 return Error("Invalid record at top-level");
1843 unsigned BlockID = Stream.ReadSubBlockID();
1845 // We only know the MODULE subblock ID.
1847 case bitc::MODULE_BLOCK_ID:
1848 if (ParseModuleTriple(Triple))
1852 if (Stream.SkipBlock())
1853 return Error("Malformed block record");
1861 /// ParseMetadataAttachment - Parse metadata attachments.
1862 bool BitcodeReader::ParseMetadataAttachment() {
1863 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1864 return Error("Malformed block record");
1866 SmallVector<uint64_t, 64> Record;
1868 unsigned Code = Stream.ReadCode();
1869 if (Code == bitc::END_BLOCK) {
1870 if (Stream.ReadBlockEnd())
1871 return Error("Error at end of PARAMATTR block");
1874 if (Code == bitc::DEFINE_ABBREV) {
1875 Stream.ReadAbbrevRecord();
1878 // Read a metadata attachment record.
1880 switch (Stream.ReadRecord(Code, Record)) {
1881 default: // Default behavior: ignore.
1883 case bitc::METADATA_ATTACHMENT: {
1884 unsigned RecordLength = Record.size();
1885 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1886 return Error ("Invalid METADATA_ATTACHMENT reader!");
1887 Instruction *Inst = InstructionList[Record[0]];
1888 for (unsigned i = 1; i != RecordLength; i = i+2) {
1889 unsigned Kind = Record[i];
1890 DenseMap<unsigned, unsigned>::iterator I =
1891 MDKindMap.find(Kind);
1892 if (I == MDKindMap.end())
1893 return Error("Invalid metadata kind ID");
1894 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1895 Inst->setMetadata(I->second, cast<MDNode>(Node));
1904 /// ParseFunctionBody - Lazily parse the specified function body block.
1905 bool BitcodeReader::ParseFunctionBody(Function *F) {
1906 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1907 return Error("Malformed block record");
1909 InstructionList.clear();
1910 unsigned ModuleValueListSize = ValueList.size();
1911 unsigned ModuleMDValueListSize = MDValueList.size();
1913 // Add all the function arguments to the value table.
1914 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1915 ValueList.push_back(I);
1917 unsigned NextValueNo = ValueList.size();
1918 BasicBlock *CurBB = 0;
1919 unsigned CurBBNo = 0;
1923 // Read all the records.
1924 SmallVector<uint64_t, 64> Record;
1926 unsigned Code = Stream.ReadCode();
1927 if (Code == bitc::END_BLOCK) {
1928 if (Stream.ReadBlockEnd())
1929 return Error("Error at end of function block");
1933 if (Code == bitc::ENTER_SUBBLOCK) {
1934 switch (Stream.ReadSubBlockID()) {
1935 default: // Skip unknown content.
1936 if (Stream.SkipBlock())
1937 return Error("Malformed block record");
1939 case bitc::CONSTANTS_BLOCK_ID:
1940 if (ParseConstants()) return true;
1941 NextValueNo = ValueList.size();
1943 case bitc::VALUE_SYMTAB_BLOCK_ID:
1944 if (ParseValueSymbolTable()) return true;
1946 case bitc::METADATA_ATTACHMENT_ID:
1947 if (ParseMetadataAttachment()) return true;
1949 case bitc::METADATA_BLOCK_ID:
1950 if (ParseMetadata()) return true;
1956 if (Code == bitc::DEFINE_ABBREV) {
1957 Stream.ReadAbbrevRecord();
1964 unsigned BitCode = Stream.ReadRecord(Code, Record);
1966 default: // Default behavior: reject
1967 return Error("Unknown instruction");
1968 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1969 if (Record.size() < 1 || Record[0] == 0)
1970 return Error("Invalid DECLAREBLOCKS record");
1971 // Create all the basic blocks for the function.
1972 FunctionBBs.resize(Record[0]);
1973 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1974 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1975 CurBB = FunctionBBs[0];
1978 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1979 // This record indicates that the last instruction is at the same
1980 // location as the previous instruction with a location.
1983 // Get the last instruction emitted.
1984 if (CurBB && !CurBB->empty())
1986 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1987 !FunctionBBs[CurBBNo-1]->empty())
1988 I = &FunctionBBs[CurBBNo-1]->back();
1990 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1991 I->setDebugLoc(LastLoc);
1995 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
1996 I = 0; // Get the last instruction emitted.
1997 if (CurBB && !CurBB->empty())
1999 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2000 !FunctionBBs[CurBBNo-1]->empty())
2001 I = &FunctionBBs[CurBBNo-1]->back();
2002 if (I == 0 || Record.size() < 4)
2003 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2005 unsigned Line = Record[0], Col = Record[1];
2006 unsigned ScopeID = Record[2], IAID = Record[3];
2008 MDNode *Scope = 0, *IA = 0;
2009 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2010 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2011 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2012 I->setDebugLoc(LastLoc);
2017 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2020 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2021 getValue(Record, OpNum, LHS->getType(), RHS) ||
2022 OpNum+1 > Record.size())
2023 return Error("Invalid BINOP record");
2025 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2026 if (Opc == -1) return Error("Invalid BINOP record");
2027 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2028 InstructionList.push_back(I);
2029 if (OpNum < Record.size()) {
2030 if (Opc == Instruction::Add ||
2031 Opc == Instruction::Sub ||
2032 Opc == Instruction::Mul ||
2033 Opc == Instruction::Shl) {
2034 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2035 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2036 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2037 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2038 } else if (Opc == Instruction::SDiv ||
2039 Opc == Instruction::UDiv ||
2040 Opc == Instruction::LShr ||
2041 Opc == Instruction::AShr) {
2042 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2043 cast<BinaryOperator>(I)->setIsExact(true);
2048 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2051 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2052 OpNum+2 != Record.size())
2053 return Error("Invalid CAST record");
2055 Type *ResTy = getTypeByID(Record[OpNum]);
2056 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2057 if (Opc == -1 || ResTy == 0)
2058 return Error("Invalid CAST record");
2059 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2060 InstructionList.push_back(I);
2063 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2064 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2067 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2068 return Error("Invalid GEP record");
2070 SmallVector<Value*, 16> GEPIdx;
2071 while (OpNum != Record.size()) {
2073 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2074 return Error("Invalid GEP record");
2075 GEPIdx.push_back(Op);
2078 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2079 InstructionList.push_back(I);
2080 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2081 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2085 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2086 // EXTRACTVAL: [opty, opval, n x indices]
2089 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2090 return Error("Invalid EXTRACTVAL record");
2092 SmallVector<unsigned, 4> EXTRACTVALIdx;
2093 for (unsigned RecSize = Record.size();
2094 OpNum != RecSize; ++OpNum) {
2095 uint64_t Index = Record[OpNum];
2096 if ((unsigned)Index != Index)
2097 return Error("Invalid EXTRACTVAL index");
2098 EXTRACTVALIdx.push_back((unsigned)Index);
2101 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2102 InstructionList.push_back(I);
2106 case bitc::FUNC_CODE_INST_INSERTVAL: {
2107 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2110 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2111 return Error("Invalid INSERTVAL record");
2113 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2114 return Error("Invalid INSERTVAL record");
2116 SmallVector<unsigned, 4> INSERTVALIdx;
2117 for (unsigned RecSize = Record.size();
2118 OpNum != RecSize; ++OpNum) {
2119 uint64_t Index = Record[OpNum];
2120 if ((unsigned)Index != Index)
2121 return Error("Invalid INSERTVAL index");
2122 INSERTVALIdx.push_back((unsigned)Index);
2125 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2126 InstructionList.push_back(I);
2130 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2131 // obsolete form of select
2132 // handles select i1 ... in old bitcode
2134 Value *TrueVal, *FalseVal, *Cond;
2135 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2136 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2137 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2138 return Error("Invalid SELECT record");
2140 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2141 InstructionList.push_back(I);
2145 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2146 // new form of select
2147 // handles select i1 or select [N x i1]
2149 Value *TrueVal, *FalseVal, *Cond;
2150 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2151 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2152 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2153 return Error("Invalid SELECT record");
2155 // select condition can be either i1 or [N x i1]
2156 if (VectorType* vector_type =
2157 dyn_cast<VectorType>(Cond->getType())) {
2159 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2160 return Error("Invalid SELECT condition type");
2163 if (Cond->getType() != Type::getInt1Ty(Context))
2164 return Error("Invalid SELECT condition type");
2167 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2168 InstructionList.push_back(I);
2172 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2175 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2176 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2177 return Error("Invalid EXTRACTELT record");
2178 I = ExtractElementInst::Create(Vec, Idx);
2179 InstructionList.push_back(I);
2183 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2185 Value *Vec, *Elt, *Idx;
2186 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2187 getValue(Record, OpNum,
2188 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2189 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2190 return Error("Invalid INSERTELT record");
2191 I = InsertElementInst::Create(Vec, Elt, Idx);
2192 InstructionList.push_back(I);
2196 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2198 Value *Vec1, *Vec2, *Mask;
2199 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2200 getValue(Record, OpNum, Vec1->getType(), Vec2))
2201 return Error("Invalid SHUFFLEVEC record");
2203 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2204 return Error("Invalid SHUFFLEVEC record");
2205 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2206 InstructionList.push_back(I);
2210 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2211 // Old form of ICmp/FCmp returning bool
2212 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2213 // both legal on vectors but had different behaviour.
2214 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2215 // FCmp/ICmp returning bool or vector of bool
2219 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2220 getValue(Record, OpNum, LHS->getType(), RHS) ||
2221 OpNum+1 != Record.size())
2222 return Error("Invalid CMP record");
2224 if (LHS->getType()->isFPOrFPVectorTy())
2225 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2227 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2228 InstructionList.push_back(I);
2232 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2234 unsigned Size = Record.size();
2236 I = ReturnInst::Create(Context);
2237 InstructionList.push_back(I);
2243 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2244 return Error("Invalid RET record");
2245 if (OpNum != Record.size())
2246 return Error("Invalid RET record");
2248 I = ReturnInst::Create(Context, Op);
2249 InstructionList.push_back(I);
2252 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2253 if (Record.size() != 1 && Record.size() != 3)
2254 return Error("Invalid BR record");
2255 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2257 return Error("Invalid BR record");
2259 if (Record.size() == 1) {
2260 I = BranchInst::Create(TrueDest);
2261 InstructionList.push_back(I);
2264 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2265 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2266 if (FalseDest == 0 || Cond == 0)
2267 return Error("Invalid BR record");
2268 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2269 InstructionList.push_back(I);
2273 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2274 if (Record.size() < 3 || (Record.size() & 1) == 0)
2275 return Error("Invalid SWITCH record");
2276 Type *OpTy = getTypeByID(Record[0]);
2277 Value *Cond = getFnValueByID(Record[1], OpTy);
2278 BasicBlock *Default = getBasicBlock(Record[2]);
2279 if (OpTy == 0 || Cond == 0 || Default == 0)
2280 return Error("Invalid SWITCH record");
2281 unsigned NumCases = (Record.size()-3)/2;
2282 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2283 InstructionList.push_back(SI);
2284 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2285 ConstantInt *CaseVal =
2286 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2287 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2288 if (CaseVal == 0 || DestBB == 0) {
2290 return Error("Invalid SWITCH record!");
2292 SI->addCase(CaseVal, DestBB);
2297 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2298 if (Record.size() < 2)
2299 return Error("Invalid INDIRECTBR record");
2300 Type *OpTy = getTypeByID(Record[0]);
2301 Value *Address = getFnValueByID(Record[1], OpTy);
2302 if (OpTy == 0 || Address == 0)
2303 return Error("Invalid INDIRECTBR record");
2304 unsigned NumDests = Record.size()-2;
2305 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2306 InstructionList.push_back(IBI);
2307 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2308 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2309 IBI->addDestination(DestBB);
2312 return Error("Invalid INDIRECTBR record!");
2319 case bitc::FUNC_CODE_INST_INVOKE: {
2320 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2321 if (Record.size() < 4) return Error("Invalid INVOKE record");
2322 AttrListPtr PAL = getAttributes(Record[0]);
2323 unsigned CCInfo = Record[1];
2324 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2325 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2329 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2330 return Error("Invalid INVOKE record");
2332 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2333 FunctionType *FTy = !CalleeTy ? 0 :
2334 dyn_cast<FunctionType>(CalleeTy->getElementType());
2336 // Check that the right number of fixed parameters are here.
2337 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2338 Record.size() < OpNum+FTy->getNumParams())
2339 return Error("Invalid INVOKE record");
2341 SmallVector<Value*, 16> Ops;
2342 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2343 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2344 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2347 if (!FTy->isVarArg()) {
2348 if (Record.size() != OpNum)
2349 return Error("Invalid INVOKE record");
2351 // Read type/value pairs for varargs params.
2352 while (OpNum != Record.size()) {
2354 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2355 return Error("Invalid INVOKE record");
2360 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2361 InstructionList.push_back(I);
2362 cast<InvokeInst>(I)->setCallingConv(
2363 static_cast<CallingConv::ID>(CCInfo));
2364 cast<InvokeInst>(I)->setAttributes(PAL);
2367 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2370 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2371 return Error("Invalid RESUME record");
2372 I = ResumeInst::Create(Val);
2373 InstructionList.push_back(I);
2376 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2377 I = new UnreachableInst(Context);
2378 InstructionList.push_back(I);
2380 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2381 if (Record.size() < 1 || ((Record.size()-1)&1))
2382 return Error("Invalid PHI record");
2383 Type *Ty = getTypeByID(Record[0]);
2384 if (!Ty) return Error("Invalid PHI record");
2386 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2387 InstructionList.push_back(PN);
2389 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2390 Value *V = getFnValueByID(Record[1+i], Ty);
2391 BasicBlock *BB = getBasicBlock(Record[2+i]);
2392 if (!V || !BB) return Error("Invalid PHI record");
2393 PN->addIncoming(V, BB);
2399 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2400 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2402 if (Record.size() < 4)
2403 return Error("Invalid LANDINGPAD record");
2404 Type *Ty = getTypeByID(Record[Idx++]);
2405 if (!Ty) return Error("Invalid LANDINGPAD record");
2407 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2408 return Error("Invalid LANDINGPAD record");
2410 bool IsCleanup = !!Record[Idx++];
2411 unsigned NumClauses = Record[Idx++];
2412 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2413 LP->setCleanup(IsCleanup);
2414 for (unsigned J = 0; J != NumClauses; ++J) {
2415 LandingPadInst::ClauseType CT =
2416 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2419 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2421 return Error("Invalid LANDINGPAD record");
2424 assert((CT != LandingPadInst::Catch ||
2425 !isa<ArrayType>(Val->getType())) &&
2426 "Catch clause has a invalid type!");
2427 assert((CT != LandingPadInst::Filter ||
2428 isa<ArrayType>(Val->getType())) &&
2429 "Filter clause has invalid type!");
2434 InstructionList.push_back(I);
2438 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2439 if (Record.size() != 4)
2440 return Error("Invalid ALLOCA record");
2442 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2443 Type *OpTy = getTypeByID(Record[1]);
2444 Value *Size = getFnValueByID(Record[2], OpTy);
2445 unsigned Align = Record[3];
2446 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2447 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2448 InstructionList.push_back(I);
2451 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2454 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2455 OpNum+2 != Record.size())
2456 return Error("Invalid LOAD record");
2458 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2459 InstructionList.push_back(I);
2462 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2463 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2466 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2467 OpNum+4 != Record.size())
2468 return Error("Invalid LOADATOMIC record");
2471 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2472 if (Ordering == NotAtomic || Ordering == Release ||
2473 Ordering == AcquireRelease)
2474 return Error("Invalid LOADATOMIC record");
2475 if (Ordering != NotAtomic && Record[OpNum] == 0)
2476 return Error("Invalid LOADATOMIC record");
2477 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2479 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2480 Ordering, SynchScope);
2481 InstructionList.push_back(I);
2484 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2487 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2488 getValue(Record, OpNum,
2489 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2490 OpNum+2 != Record.size())
2491 return Error("Invalid STORE record");
2493 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2494 InstructionList.push_back(I);
2497 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2498 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2501 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2502 getValue(Record, OpNum,
2503 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2504 OpNum+4 != Record.size())
2505 return Error("Invalid STOREATOMIC record");
2507 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2508 if (Ordering == NotAtomic || Ordering == Acquire ||
2509 Ordering == AcquireRelease)
2510 return Error("Invalid STOREATOMIC record");
2511 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2512 if (Ordering != NotAtomic && Record[OpNum] == 0)
2513 return Error("Invalid STOREATOMIC record");
2515 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2516 Ordering, SynchScope);
2517 InstructionList.push_back(I);
2520 case bitc::FUNC_CODE_INST_CMPXCHG: {
2521 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2523 Value *Ptr, *Cmp, *New;
2524 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2525 getValue(Record, OpNum,
2526 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2527 getValue(Record, OpNum,
2528 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2529 OpNum+3 != Record.size())
2530 return Error("Invalid CMPXCHG record");
2531 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2532 if (Ordering == NotAtomic || Ordering == Unordered)
2533 return Error("Invalid CMPXCHG record");
2534 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2535 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2536 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2537 InstructionList.push_back(I);
2540 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2541 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2544 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2545 getValue(Record, OpNum,
2546 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2547 OpNum+4 != Record.size())
2548 return Error("Invalid ATOMICRMW record");
2549 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2550 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2551 Operation > AtomicRMWInst::LAST_BINOP)
2552 return Error("Invalid ATOMICRMW record");
2553 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2554 if (Ordering == NotAtomic || Ordering == Unordered)
2555 return Error("Invalid ATOMICRMW record");
2556 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2557 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2558 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2559 InstructionList.push_back(I);
2562 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2563 if (2 != Record.size())
2564 return Error("Invalid FENCE record");
2565 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2566 if (Ordering == NotAtomic || Ordering == Unordered ||
2567 Ordering == Monotonic)
2568 return Error("Invalid FENCE record");
2569 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2570 I = new FenceInst(Context, Ordering, SynchScope);
2571 InstructionList.push_back(I);
2574 case bitc::FUNC_CODE_INST_CALL: {
2575 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2576 if (Record.size() < 3)
2577 return Error("Invalid CALL record");
2579 AttrListPtr PAL = getAttributes(Record[0]);
2580 unsigned CCInfo = Record[1];
2584 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2585 return Error("Invalid CALL record");
2587 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2588 FunctionType *FTy = 0;
2589 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2590 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2591 return Error("Invalid CALL record");
2593 SmallVector<Value*, 16> Args;
2594 // Read the fixed params.
2595 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2596 if (FTy->getParamType(i)->isLabelTy())
2597 Args.push_back(getBasicBlock(Record[OpNum]));
2599 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2600 if (Args.back() == 0) return Error("Invalid CALL record");
2603 // Read type/value pairs for varargs params.
2604 if (!FTy->isVarArg()) {
2605 if (OpNum != Record.size())
2606 return Error("Invalid CALL record");
2608 while (OpNum != Record.size()) {
2610 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2611 return Error("Invalid CALL record");
2616 I = CallInst::Create(Callee, Args);
2617 InstructionList.push_back(I);
2618 cast<CallInst>(I)->setCallingConv(
2619 static_cast<CallingConv::ID>(CCInfo>>1));
2620 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2621 cast<CallInst>(I)->setAttributes(PAL);
2624 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2625 if (Record.size() < 3)
2626 return Error("Invalid VAARG record");
2627 Type *OpTy = getTypeByID(Record[0]);
2628 Value *Op = getFnValueByID(Record[1], OpTy);
2629 Type *ResTy = getTypeByID(Record[2]);
2630 if (!OpTy || !Op || !ResTy)
2631 return Error("Invalid VAARG record");
2632 I = new VAArgInst(Op, ResTy);
2633 InstructionList.push_back(I);
2638 // Add instruction to end of current BB. If there is no current BB, reject
2642 return Error("Invalid instruction with no BB");
2644 CurBB->getInstList().push_back(I);
2646 // If this was a terminator instruction, move to the next block.
2647 if (isa<TerminatorInst>(I)) {
2649 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2652 // Non-void values get registered in the value table for future use.
2653 if (I && !I->getType()->isVoidTy())
2654 ValueList.AssignValue(I, NextValueNo++);
2657 // Check the function list for unresolved values.
2658 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2659 if (A->getParent() == 0) {
2660 // We found at least one unresolved value. Nuke them all to avoid leaks.
2661 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2662 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2663 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2667 return Error("Never resolved value found in function!");
2671 // FIXME: Check for unresolved forward-declared metadata references
2672 // and clean up leaks.
2674 // See if anything took the address of blocks in this function. If so,
2675 // resolve them now.
2676 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2677 BlockAddrFwdRefs.find(F);
2678 if (BAFRI != BlockAddrFwdRefs.end()) {
2679 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2680 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2681 unsigned BlockIdx = RefList[i].first;
2682 if (BlockIdx >= FunctionBBs.size())
2683 return Error("Invalid blockaddress block #");
2685 GlobalVariable *FwdRef = RefList[i].second;
2686 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2687 FwdRef->eraseFromParent();
2690 BlockAddrFwdRefs.erase(BAFRI);
2693 // Trim the value list down to the size it was before we parsed this function.
2694 ValueList.shrinkTo(ModuleValueListSize);
2695 MDValueList.shrinkTo(ModuleMDValueListSize);
2696 std::vector<BasicBlock*>().swap(FunctionBBs);
2700 /// FindFunctionInStream - Find the function body in the bitcode stream
2701 bool BitcodeReader::FindFunctionInStream(Function *F,
2702 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2703 while (DeferredFunctionInfoIterator->second == 0) {
2704 if (Stream.AtEndOfStream())
2705 return Error("Could not find Function in stream");
2706 // ParseModule will parse the next body in the stream and set its
2707 // position in the DeferredFunctionInfo map.
2708 if (ParseModule(true)) return true;
2713 //===----------------------------------------------------------------------===//
2714 // GVMaterializer implementation
2715 //===----------------------------------------------------------------------===//
2718 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2719 if (const Function *F = dyn_cast<Function>(GV)) {
2720 return F->isDeclaration() &&
2721 DeferredFunctionInfo.count(const_cast<Function*>(F));
2726 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2727 Function *F = dyn_cast<Function>(GV);
2728 // If it's not a function or is already material, ignore the request.
2729 if (!F || !F->isMaterializable()) return false;
2731 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2732 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2733 // If its position is recorded as 0, its body is somewhere in the stream
2734 // but we haven't seen it yet.
2735 if (DFII->second == 0)
2736 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
2738 // Move the bit stream to the saved position of the deferred function body.
2739 Stream.JumpToBit(DFII->second);
2741 if (ParseFunctionBody(F)) {
2742 if (ErrInfo) *ErrInfo = ErrorString;
2746 // Upgrade any old intrinsic calls in the function.
2747 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2748 E = UpgradedIntrinsics.end(); I != E; ++I) {
2749 if (I->first != I->second) {
2750 for (Value::use_iterator UI = I->first->use_begin(),
2751 UE = I->first->use_end(); UI != UE; ) {
2752 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2753 UpgradeIntrinsicCall(CI, I->second);
2761 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2762 const Function *F = dyn_cast<Function>(GV);
2763 if (!F || F->isDeclaration())
2765 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2768 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2769 Function *F = dyn_cast<Function>(GV);
2770 // If this function isn't dematerializable, this is a noop.
2771 if (!F || !isDematerializable(F))
2774 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2776 // Just forget the function body, we can remat it later.
2781 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2782 assert(M == TheModule &&
2783 "Can only Materialize the Module this BitcodeReader is attached to.");
2784 // Iterate over the module, deserializing any functions that are still on
2786 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2788 if (F->isMaterializable() &&
2789 Materialize(F, ErrInfo))
2792 // At this point, if there are any function bodies, the current bit is
2793 // pointing to the END_BLOCK record after them. Now make sure the rest
2794 // of the bits in the module have been read.
2798 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2799 // delete the old functions to clean up. We can't do this unless the entire
2800 // module is materialized because there could always be another function body
2801 // with calls to the old function.
2802 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2803 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2804 if (I->first != I->second) {
2805 for (Value::use_iterator UI = I->first->use_begin(),
2806 UE = I->first->use_end(); UI != UE; ) {
2807 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2808 UpgradeIntrinsicCall(CI, I->second);
2810 if (!I->first->use_empty())
2811 I->first->replaceAllUsesWith(I->second);
2812 I->first->eraseFromParent();
2815 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2820 bool BitcodeReader::InitStream() {
2821 if (LazyStreamer) return InitLazyStream();
2822 return InitStreamFromBuffer();
2825 bool BitcodeReader::InitStreamFromBuffer() {
2826 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2827 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2829 if (Buffer->getBufferSize() & 3) {
2830 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2831 return Error("Invalid bitcode signature");
2833 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2836 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2837 // The magic number is 0x0B17C0DE stored in little endian.
2838 if (isBitcodeWrapper(BufPtr, BufEnd))
2839 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2840 return Error("Invalid bitcode wrapper header");
2842 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2843 Stream.init(*StreamFile);
2848 bool BitcodeReader::InitLazyStream() {
2849 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2851 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2852 StreamFile.reset(new BitstreamReader(Bytes));
2853 Stream.init(*StreamFile);
2855 unsigned char buf[16];
2856 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2857 return Error("Bitcode stream must be at least 16 bytes in length");
2859 if (!isBitcode(buf, buf + 16))
2860 return Error("Invalid bitcode signature");
2862 if (isBitcodeWrapper(buf, buf + 4)) {
2863 const unsigned char *bitcodeStart = buf;
2864 const unsigned char *bitcodeEnd = buf + 16;
2865 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2866 Bytes->dropLeadingBytes(bitcodeStart - buf);
2867 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2872 //===----------------------------------------------------------------------===//
2873 // External interface
2874 //===----------------------------------------------------------------------===//
2876 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2878 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2879 LLVMContext& Context,
2880 std::string *ErrMsg) {
2881 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2882 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2883 M->setMaterializer(R);
2884 if (R->ParseBitcodeInto(M)) {
2886 *ErrMsg = R->getErrorString();
2888 delete M; // Also deletes R.
2891 // Have the BitcodeReader dtor delete 'Buffer'.
2892 R->setBufferOwned(true);
2894 R->materializeForwardReferencedFunctions();
2900 Module *llvm::getStreamedBitcodeModule(const std::string &name,
2901 DataStreamer *streamer,
2902 LLVMContext &Context,
2903 std::string *ErrMsg) {
2904 Module *M = new Module(name, Context);
2905 BitcodeReader *R = new BitcodeReader(streamer, Context);
2906 M->setMaterializer(R);
2907 if (R->ParseBitcodeInto(M)) {
2909 *ErrMsg = R->getErrorString();
2910 delete M; // Also deletes R.
2913 R->setBufferOwned(false); // no buffer to delete
2917 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2918 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2919 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2920 std::string *ErrMsg){
2921 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2924 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2925 // there was an error.
2926 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2928 // Read in the entire module, and destroy the BitcodeReader.
2929 if (M->MaterializeAllPermanently(ErrMsg)) {
2934 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2935 // written. We must defer until the Module has been fully materialized.
2940 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2941 LLVMContext& Context,
2942 std::string *ErrMsg) {
2943 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2944 // Don't let the BitcodeReader dtor delete 'Buffer'.
2945 R->setBufferOwned(false);
2947 std::string Triple("");
2948 if (R->ParseTriple(Triple))
2950 *ErrMsg = R->getErrorString();