1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitcodeReader class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "BitcodeReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/AutoUpgrade.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/OperandTraits.h"
30 void BitcodeReader::materializeForwardReferencedFunctions() {
31 while (!BlockAddrFwdRefs.empty()) {
32 Function *F = BlockAddrFwdRefs.begin()->first;
37 void BitcodeReader::FreeState() {
41 std::vector<Type*>().swap(TypeList);
45 std::vector<AttrListPtr>().swap(MAttributes);
46 std::vector<BasicBlock*>().swap(FunctionBBs);
47 std::vector<Function*>().swap(FunctionsWithBodies);
48 DeferredFunctionInfo.clear();
52 //===----------------------------------------------------------------------===//
53 // Helper functions to implement forward reference resolution, etc.
54 //===----------------------------------------------------------------------===//
56 /// ConvertToString - Convert a string from a record into an std::string, return
58 template<typename StrTy>
59 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
61 if (Idx > Record.size())
64 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
65 Result += (char)Record[i];
69 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
71 default: // Map unknown/new linkages to external
72 case 0: return GlobalValue::ExternalLinkage;
73 case 1: return GlobalValue::WeakAnyLinkage;
74 case 2: return GlobalValue::AppendingLinkage;
75 case 3: return GlobalValue::InternalLinkage;
76 case 4: return GlobalValue::LinkOnceAnyLinkage;
77 case 5: return GlobalValue::DLLImportLinkage;
78 case 6: return GlobalValue::DLLExportLinkage;
79 case 7: return GlobalValue::ExternalWeakLinkage;
80 case 8: return GlobalValue::CommonLinkage;
81 case 9: return GlobalValue::PrivateLinkage;
82 case 10: return GlobalValue::WeakODRLinkage;
83 case 11: return GlobalValue::LinkOnceODRLinkage;
84 case 12: return GlobalValue::AvailableExternallyLinkage;
85 case 13: return GlobalValue::LinkerPrivateLinkage;
86 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
87 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
91 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
93 default: // Map unknown visibilities to default.
94 case 0: return GlobalValue::DefaultVisibility;
95 case 1: return GlobalValue::HiddenVisibility;
96 case 2: return GlobalValue::ProtectedVisibility;
100 static int GetDecodedCastOpcode(unsigned Val) {
103 case bitc::CAST_TRUNC : return Instruction::Trunc;
104 case bitc::CAST_ZEXT : return Instruction::ZExt;
105 case bitc::CAST_SEXT : return Instruction::SExt;
106 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
107 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
108 case bitc::CAST_UITOFP : return Instruction::UIToFP;
109 case bitc::CAST_SITOFP : return Instruction::SIToFP;
110 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
111 case bitc::CAST_FPEXT : return Instruction::FPExt;
112 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
113 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
114 case bitc::CAST_BITCAST : return Instruction::BitCast;
117 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
120 case bitc::BINOP_ADD:
121 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
122 case bitc::BINOP_SUB:
123 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
124 case bitc::BINOP_MUL:
125 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
126 case bitc::BINOP_UDIV: return Instruction::UDiv;
127 case bitc::BINOP_SDIV:
128 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
129 case bitc::BINOP_UREM: return Instruction::URem;
130 case bitc::BINOP_SREM:
131 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
132 case bitc::BINOP_SHL: return Instruction::Shl;
133 case bitc::BINOP_LSHR: return Instruction::LShr;
134 case bitc::BINOP_ASHR: return Instruction::AShr;
135 case bitc::BINOP_AND: return Instruction::And;
136 case bitc::BINOP_OR: return Instruction::Or;
137 case bitc::BINOP_XOR: return Instruction::Xor;
141 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
143 default: return AtomicRMWInst::BAD_BINOP;
144 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
145 case bitc::RMW_ADD: return AtomicRMWInst::Add;
146 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
147 case bitc::RMW_AND: return AtomicRMWInst::And;
148 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
149 case bitc::RMW_OR: return AtomicRMWInst::Or;
150 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
151 case bitc::RMW_MAX: return AtomicRMWInst::Max;
152 case bitc::RMW_MIN: return AtomicRMWInst::Min;
153 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
154 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
158 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
160 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
161 case bitc::ORDERING_UNORDERED: return Unordered;
162 case bitc::ORDERING_MONOTONIC: return Monotonic;
163 case bitc::ORDERING_ACQUIRE: return Acquire;
164 case bitc::ORDERING_RELEASE: return Release;
165 case bitc::ORDERING_ACQREL: return AcquireRelease;
166 default: // Map unknown orderings to sequentially-consistent.
167 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
171 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
173 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
174 default: // Map unknown scopes to cross-thread.
175 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
181 /// @brief A class for maintaining the slot number definition
182 /// as a placeholder for the actual definition for forward constants defs.
183 class ConstantPlaceHolder : public ConstantExpr {
184 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
186 // allocate space for exactly one operand
187 void *operator new(size_t s) {
188 return User::operator new(s, 1);
190 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
191 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
192 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
195 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
196 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
197 static bool classof(const Value *V) {
198 return isa<ConstantExpr>(V) &&
199 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
203 /// Provide fast operand accessors
204 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
208 // FIXME: can we inherit this from ConstantExpr?
210 struct OperandTraits<ConstantPlaceHolder> :
211 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
216 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
225 WeakVH &OldV = ValuePtrs[Idx];
231 // Handle constants and non-constants (e.g. instrs) differently for
233 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
234 ResolveConstants.push_back(std::make_pair(PHC, Idx));
237 // If there was a forward reference to this value, replace it.
238 Value *PrevVal = OldV;
239 OldV->replaceAllUsesWith(V);
245 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
250 if (Value *V = ValuePtrs[Idx]) {
251 assert(Ty == V->getType() && "Type mismatch in constant table!");
252 return cast<Constant>(V);
255 // Create and return a placeholder, which will later be RAUW'd.
256 Constant *C = new ConstantPlaceHolder(Ty, Context);
261 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
265 if (Value *V = ValuePtrs[Idx]) {
266 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
270 // No type specified, must be invalid reference.
271 if (Ty == 0) return 0;
273 // Create and return a placeholder, which will later be RAUW'd.
274 Value *V = new Argument(Ty);
279 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
280 /// resolves any forward references. The idea behind this is that we sometimes
281 /// get constants (such as large arrays) which reference *many* forward ref
282 /// constants. Replacing each of these causes a lot of thrashing when
283 /// building/reuniquing the constant. Instead of doing this, we look at all the
284 /// uses and rewrite all the place holders at once for any constant that uses
286 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
287 // Sort the values by-pointer so that they are efficient to look up with a
289 std::sort(ResolveConstants.begin(), ResolveConstants.end());
291 SmallVector<Constant*, 64> NewOps;
293 while (!ResolveConstants.empty()) {
294 Value *RealVal = operator[](ResolveConstants.back().second);
295 Constant *Placeholder = ResolveConstants.back().first;
296 ResolveConstants.pop_back();
298 // Loop over all users of the placeholder, updating them to reference the
299 // new value. If they reference more than one placeholder, update them all
301 while (!Placeholder->use_empty()) {
302 Value::use_iterator UI = Placeholder->use_begin();
305 // If the using object isn't uniqued, just update the operands. This
306 // handles instructions and initializers for global variables.
307 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
308 UI.getUse().set(RealVal);
312 // Otherwise, we have a constant that uses the placeholder. Replace that
313 // constant with a new constant that has *all* placeholder uses updated.
314 Constant *UserC = cast<Constant>(U);
315 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
318 if (!isa<ConstantPlaceHolder>(*I)) {
319 // Not a placeholder reference.
321 } else if (*I == Placeholder) {
322 // Common case is that it just references this one placeholder.
325 // Otherwise, look up the placeholder in ResolveConstants.
326 ResolveConstantsTy::iterator It =
327 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
328 std::pair<Constant*, unsigned>(cast<Constant>(*I),
330 assert(It != ResolveConstants.end() && It->first == *I);
331 NewOp = operator[](It->second);
334 NewOps.push_back(cast<Constant>(NewOp));
337 // Make the new constant.
339 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
340 NewC = ConstantArray::get(UserCA->getType(), NewOps);
341 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
342 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
343 } else if (isa<ConstantVector>(UserC)) {
344 NewC = ConstantVector::get(NewOps);
346 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
347 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
350 UserC->replaceAllUsesWith(NewC);
351 UserC->destroyConstant();
355 // Update all ValueHandles, they should be the only users at this point.
356 Placeholder->replaceAllUsesWith(RealVal);
361 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
370 WeakVH &OldV = MDValuePtrs[Idx];
376 // If there was a forward reference to this value, replace it.
377 MDNode *PrevVal = cast<MDNode>(OldV);
378 OldV->replaceAllUsesWith(V);
379 MDNode::deleteTemporary(PrevVal);
380 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
382 MDValuePtrs[Idx] = V;
385 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
389 if (Value *V = MDValuePtrs[Idx]) {
390 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
394 // Create and return a placeholder, which will later be RAUW'd.
395 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
396 MDValuePtrs[Idx] = V;
400 Type *BitcodeReader::getTypeByID(unsigned ID) {
401 // The type table size is always specified correctly.
402 if (ID >= TypeList.size())
405 if (Type *Ty = TypeList[ID])
408 // If we have a forward reference, the only possible case is when it is to a
409 // named struct. Just create a placeholder for now.
410 return TypeList[ID] = StructType::create(Context);
414 //===----------------------------------------------------------------------===//
415 // Functions for parsing blocks from the bitcode file
416 //===----------------------------------------------------------------------===//
418 bool BitcodeReader::ParseAttributeBlock() {
419 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
420 return Error("Malformed block record");
422 if (!MAttributes.empty())
423 return Error("Multiple PARAMATTR blocks found!");
425 SmallVector<uint64_t, 64> Record;
427 SmallVector<AttributeWithIndex, 8> Attrs;
429 // Read all the records.
431 unsigned Code = Stream.ReadCode();
432 if (Code == bitc::END_BLOCK) {
433 if (Stream.ReadBlockEnd())
434 return Error("Error at end of PARAMATTR block");
438 if (Code == bitc::ENTER_SUBBLOCK) {
439 // No known subblocks, always skip them.
440 Stream.ReadSubBlockID();
441 if (Stream.SkipBlock())
442 return Error("Malformed block record");
446 if (Code == bitc::DEFINE_ABBREV) {
447 Stream.ReadAbbrevRecord();
453 switch (Stream.ReadRecord(Code, Record)) {
454 default: // Default behavior: ignore.
456 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
457 if (Record.size() & 1)
458 return Error("Invalid ENTRY record");
460 // FIXME : Remove this autoupgrade code in LLVM 3.0.
461 // If Function attributes are using index 0 then transfer them
462 // to index ~0. Index 0 is used for return value attributes but used to be
463 // used for function attributes.
464 Attributes RetAttribute;
465 Attributes FnAttribute;
466 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
467 // FIXME: remove in LLVM 3.0
468 // The alignment is stored as a 16-bit raw value from bits 31--16.
469 // We shift the bits above 31 down by 11 bits.
471 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
472 if (Alignment && !isPowerOf2_32(Alignment))
473 return Error("Alignment is not a power of two.");
475 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
477 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
479 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
481 Record[i+1] = ReconstitutedAttr.Raw();
483 RetAttribute = ReconstitutedAttr;
484 else if (Record[i] == ~0U)
485 FnAttribute = ReconstitutedAttr;
488 Attributes OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
489 Attribute::ReadOnly|Attribute::ReadNone);
491 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
492 (RetAttribute & OldRetAttrs)) {
493 if (FnAttribute == Attribute::None) { // add a slot so they get added.
494 Record.push_back(~0U);
498 FnAttribute |= RetAttribute & OldRetAttrs;
499 RetAttribute &= ~OldRetAttrs;
502 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
503 if (Record[i] == 0) {
504 if (RetAttribute != Attribute::None)
505 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
506 } else if (Record[i] == ~0U) {
507 if (FnAttribute != Attribute::None)
508 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
509 } else if (Attributes(Record[i+1]) != Attribute::None)
510 Attrs.push_back(AttributeWithIndex::get(Record[i],
511 Attributes(Record[i+1])));
514 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
522 bool BitcodeReader::ParseTypeTable() {
523 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
524 return Error("Malformed block record");
526 return ParseTypeTableBody();
529 bool BitcodeReader::ParseTypeTableBody() {
530 if (!TypeList.empty())
531 return Error("Multiple TYPE_BLOCKs found!");
533 SmallVector<uint64_t, 64> Record;
534 unsigned NumRecords = 0;
536 SmallString<64> TypeName;
538 // Read all the records for this type table.
540 unsigned Code = Stream.ReadCode();
541 if (Code == bitc::END_BLOCK) {
542 if (NumRecords != TypeList.size())
543 return Error("Invalid type forward reference in TYPE_BLOCK");
544 if (Stream.ReadBlockEnd())
545 return Error("Error at end of type table block");
549 if (Code == bitc::ENTER_SUBBLOCK) {
550 // No known subblocks, always skip them.
551 Stream.ReadSubBlockID();
552 if (Stream.SkipBlock())
553 return Error("Malformed block record");
557 if (Code == bitc::DEFINE_ABBREV) {
558 Stream.ReadAbbrevRecord();
565 switch (Stream.ReadRecord(Code, Record)) {
566 default: return Error("unknown type in type table");
567 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
568 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
569 // type list. This allows us to reserve space.
570 if (Record.size() < 1)
571 return Error("Invalid TYPE_CODE_NUMENTRY record");
572 TypeList.resize(Record[0]);
574 case bitc::TYPE_CODE_VOID: // VOID
575 ResultTy = Type::getVoidTy(Context);
577 case bitc::TYPE_CODE_HALF: // HALF
578 ResultTy = Type::getHalfTy(Context);
580 case bitc::TYPE_CODE_FLOAT: // FLOAT
581 ResultTy = Type::getFloatTy(Context);
583 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
584 ResultTy = Type::getDoubleTy(Context);
586 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
587 ResultTy = Type::getX86_FP80Ty(Context);
589 case bitc::TYPE_CODE_FP128: // FP128
590 ResultTy = Type::getFP128Ty(Context);
592 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
593 ResultTy = Type::getPPC_FP128Ty(Context);
595 case bitc::TYPE_CODE_LABEL: // LABEL
596 ResultTy = Type::getLabelTy(Context);
598 case bitc::TYPE_CODE_METADATA: // METADATA
599 ResultTy = Type::getMetadataTy(Context);
601 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
602 ResultTy = Type::getX86_MMXTy(Context);
604 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
605 if (Record.size() < 1)
606 return Error("Invalid Integer type record");
608 ResultTy = IntegerType::get(Context, Record[0]);
610 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
611 // [pointee type, address space]
612 if (Record.size() < 1)
613 return Error("Invalid POINTER type record");
614 unsigned AddressSpace = 0;
615 if (Record.size() == 2)
616 AddressSpace = Record[1];
617 ResultTy = getTypeByID(Record[0]);
618 if (ResultTy == 0) return Error("invalid element type in pointer type");
619 ResultTy = PointerType::get(ResultTy, AddressSpace);
622 case bitc::TYPE_CODE_FUNCTION_OLD: {
623 // FIXME: attrid is dead, remove it in LLVM 3.0
624 // FUNCTION: [vararg, attrid, retty, paramty x N]
625 if (Record.size() < 3)
626 return Error("Invalid FUNCTION type record");
627 SmallVector<Type*, 8> ArgTys;
628 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
629 if (Type *T = getTypeByID(Record[i]))
635 ResultTy = getTypeByID(Record[2]);
636 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
637 return Error("invalid type in function type");
639 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
642 case bitc::TYPE_CODE_FUNCTION: {
643 // FUNCTION: [vararg, retty, paramty x N]
644 if (Record.size() < 2)
645 return Error("Invalid FUNCTION type record");
646 SmallVector<Type*, 8> ArgTys;
647 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
648 if (Type *T = getTypeByID(Record[i]))
654 ResultTy = getTypeByID(Record[1]);
655 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
656 return Error("invalid type in function type");
658 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
661 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
662 if (Record.size() < 1)
663 return Error("Invalid STRUCT type record");
664 SmallVector<Type*, 8> EltTys;
665 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
666 if (Type *T = getTypeByID(Record[i]))
671 if (EltTys.size() != Record.size()-1)
672 return Error("invalid type in struct type");
673 ResultTy = StructType::get(Context, EltTys, Record[0]);
676 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
677 if (ConvertToString(Record, 0, TypeName))
678 return Error("Invalid STRUCT_NAME record");
681 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
682 if (Record.size() < 1)
683 return Error("Invalid STRUCT type record");
685 if (NumRecords >= TypeList.size())
686 return Error("invalid TYPE table");
688 // Check to see if this was forward referenced, if so fill in the temp.
689 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
691 Res->setName(TypeName);
692 TypeList[NumRecords] = 0;
693 } else // Otherwise, create a new struct.
694 Res = StructType::create(Context, TypeName);
697 SmallVector<Type*, 8> EltTys;
698 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
699 if (Type *T = getTypeByID(Record[i]))
704 if (EltTys.size() != Record.size()-1)
705 return Error("invalid STRUCT type record");
706 Res->setBody(EltTys, Record[0]);
710 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
711 if (Record.size() != 1)
712 return Error("Invalid OPAQUE type record");
714 if (NumRecords >= TypeList.size())
715 return Error("invalid TYPE table");
717 // Check to see if this was forward referenced, if so fill in the temp.
718 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
720 Res->setName(TypeName);
721 TypeList[NumRecords] = 0;
722 } else // Otherwise, create a new struct with no body.
723 Res = StructType::create(Context, TypeName);
728 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
729 if (Record.size() < 2)
730 return Error("Invalid ARRAY type record");
731 if ((ResultTy = getTypeByID(Record[1])))
732 ResultTy = ArrayType::get(ResultTy, Record[0]);
734 return Error("Invalid ARRAY type element");
736 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
737 if (Record.size() < 2)
738 return Error("Invalid VECTOR type record");
739 if ((ResultTy = getTypeByID(Record[1])))
740 ResultTy = VectorType::get(ResultTy, Record[0]);
742 return Error("Invalid ARRAY type element");
746 if (NumRecords >= TypeList.size())
747 return Error("invalid TYPE table");
748 assert(ResultTy && "Didn't read a type?");
749 assert(TypeList[NumRecords] == 0 && "Already read type?");
750 TypeList[NumRecords++] = ResultTy;
754 bool BitcodeReader::ParseValueSymbolTable() {
755 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
756 return Error("Malformed block record");
758 SmallVector<uint64_t, 64> Record;
760 // Read all the records for this value table.
761 SmallString<128> ValueName;
763 unsigned Code = Stream.ReadCode();
764 if (Code == bitc::END_BLOCK) {
765 if (Stream.ReadBlockEnd())
766 return Error("Error at end of value symbol table block");
769 if (Code == bitc::ENTER_SUBBLOCK) {
770 // No known subblocks, always skip them.
771 Stream.ReadSubBlockID();
772 if (Stream.SkipBlock())
773 return Error("Malformed block record");
777 if (Code == bitc::DEFINE_ABBREV) {
778 Stream.ReadAbbrevRecord();
784 switch (Stream.ReadRecord(Code, Record)) {
785 default: // Default behavior: unknown type.
787 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
788 if (ConvertToString(Record, 1, ValueName))
789 return Error("Invalid VST_ENTRY record");
790 unsigned ValueID = Record[0];
791 if (ValueID >= ValueList.size())
792 return Error("Invalid Value ID in VST_ENTRY record");
793 Value *V = ValueList[ValueID];
795 V->setName(StringRef(ValueName.data(), ValueName.size()));
799 case bitc::VST_CODE_BBENTRY: {
800 if (ConvertToString(Record, 1, ValueName))
801 return Error("Invalid VST_BBENTRY record");
802 BasicBlock *BB = getBasicBlock(Record[0]);
804 return Error("Invalid BB ID in VST_BBENTRY record");
806 BB->setName(StringRef(ValueName.data(), ValueName.size()));
814 bool BitcodeReader::ParseMetadata() {
815 unsigned NextMDValueNo = MDValueList.size();
817 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
818 return Error("Malformed block record");
820 SmallVector<uint64_t, 64> Record;
822 // Read all the records.
824 unsigned Code = Stream.ReadCode();
825 if (Code == bitc::END_BLOCK) {
826 if (Stream.ReadBlockEnd())
827 return Error("Error at end of PARAMATTR block");
831 if (Code == bitc::ENTER_SUBBLOCK) {
832 // No known subblocks, always skip them.
833 Stream.ReadSubBlockID();
834 if (Stream.SkipBlock())
835 return Error("Malformed block record");
839 if (Code == bitc::DEFINE_ABBREV) {
840 Stream.ReadAbbrevRecord();
844 bool IsFunctionLocal = false;
847 Code = Stream.ReadRecord(Code, Record);
849 default: // Default behavior: ignore.
851 case bitc::METADATA_NAME: {
852 // Read named of the named metadata.
853 unsigned NameLength = Record.size();
855 Name.resize(NameLength);
856 for (unsigned i = 0; i != NameLength; ++i)
859 Code = Stream.ReadCode();
861 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
862 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
863 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
865 // Read named metadata elements.
866 unsigned Size = Record.size();
867 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
868 for (unsigned i = 0; i != Size; ++i) {
869 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
871 return Error("Malformed metadata record");
876 case bitc::METADATA_FN_NODE:
877 IsFunctionLocal = true;
879 case bitc::METADATA_NODE: {
880 if (Record.size() % 2 == 1)
881 return Error("Invalid METADATA_NODE record");
883 unsigned Size = Record.size();
884 SmallVector<Value*, 8> Elts;
885 for (unsigned i = 0; i != Size; i += 2) {
886 Type *Ty = getTypeByID(Record[i]);
887 if (!Ty) return Error("Invalid METADATA_NODE record");
888 if (Ty->isMetadataTy())
889 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
890 else if (!Ty->isVoidTy())
891 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
893 Elts.push_back(NULL);
895 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
896 IsFunctionLocal = false;
897 MDValueList.AssignValue(V, NextMDValueNo++);
900 case bitc::METADATA_STRING: {
901 unsigned MDStringLength = Record.size();
902 SmallString<8> String;
903 String.resize(MDStringLength);
904 for (unsigned i = 0; i != MDStringLength; ++i)
905 String[i] = Record[i];
906 Value *V = MDString::get(Context,
907 StringRef(String.data(), String.size()));
908 MDValueList.AssignValue(V, NextMDValueNo++);
911 case bitc::METADATA_KIND: {
912 unsigned RecordLength = Record.size();
913 if (Record.empty() || RecordLength < 2)
914 return Error("Invalid METADATA_KIND record");
916 Name.resize(RecordLength-1);
917 unsigned Kind = Record[0];
918 for (unsigned i = 1; i != RecordLength; ++i)
919 Name[i-1] = Record[i];
921 unsigned NewKind = TheModule->getMDKindID(Name.str());
922 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
923 return Error("Conflicting METADATA_KIND records");
930 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
931 /// the LSB for dense VBR encoding.
932 static uint64_t DecodeSignRotatedValue(uint64_t V) {
937 // There is no such thing as -0 with integers. "-0" really means MININT.
941 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
942 /// values and aliases that we can.
943 bool BitcodeReader::ResolveGlobalAndAliasInits() {
944 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
945 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
947 GlobalInitWorklist.swap(GlobalInits);
948 AliasInitWorklist.swap(AliasInits);
950 while (!GlobalInitWorklist.empty()) {
951 unsigned ValID = GlobalInitWorklist.back().second;
952 if (ValID >= ValueList.size()) {
953 // Not ready to resolve this yet, it requires something later in the file.
954 GlobalInits.push_back(GlobalInitWorklist.back());
956 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
957 GlobalInitWorklist.back().first->setInitializer(C);
959 return Error("Global variable initializer is not a constant!");
961 GlobalInitWorklist.pop_back();
964 while (!AliasInitWorklist.empty()) {
965 unsigned ValID = AliasInitWorklist.back().second;
966 if (ValID >= ValueList.size()) {
967 AliasInits.push_back(AliasInitWorklist.back());
969 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
970 AliasInitWorklist.back().first->setAliasee(C);
972 return Error("Alias initializer is not a constant!");
974 AliasInitWorklist.pop_back();
979 bool BitcodeReader::ParseConstants() {
980 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
981 return Error("Malformed block record");
983 SmallVector<uint64_t, 64> Record;
985 // Read all the records for this value table.
986 Type *CurTy = Type::getInt32Ty(Context);
987 unsigned NextCstNo = ValueList.size();
989 unsigned Code = Stream.ReadCode();
990 if (Code == bitc::END_BLOCK)
993 if (Code == bitc::ENTER_SUBBLOCK) {
994 // No known subblocks, always skip them.
995 Stream.ReadSubBlockID();
996 if (Stream.SkipBlock())
997 return Error("Malformed block record");
1001 if (Code == bitc::DEFINE_ABBREV) {
1002 Stream.ReadAbbrevRecord();
1009 unsigned BitCode = Stream.ReadRecord(Code, Record);
1011 default: // Default behavior: unknown constant
1012 case bitc::CST_CODE_UNDEF: // UNDEF
1013 V = UndefValue::get(CurTy);
1015 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1017 return Error("Malformed CST_SETTYPE record");
1018 if (Record[0] >= TypeList.size())
1019 return Error("Invalid Type ID in CST_SETTYPE record");
1020 CurTy = TypeList[Record[0]];
1021 continue; // Skip the ValueList manipulation.
1022 case bitc::CST_CODE_NULL: // NULL
1023 V = Constant::getNullValue(CurTy);
1025 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1026 if (!CurTy->isIntegerTy() || Record.empty())
1027 return Error("Invalid CST_INTEGER record");
1028 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
1030 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1031 if (!CurTy->isIntegerTy() || Record.empty())
1032 return Error("Invalid WIDE_INTEGER record");
1034 unsigned NumWords = Record.size();
1035 SmallVector<uint64_t, 8> Words;
1036 Words.resize(NumWords);
1037 for (unsigned i = 0; i != NumWords; ++i)
1038 Words[i] = DecodeSignRotatedValue(Record[i]);
1039 V = ConstantInt::get(Context,
1040 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
1044 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1046 return Error("Invalid FLOAT record");
1047 if (CurTy->isHalfTy())
1048 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1049 else if (CurTy->isFloatTy())
1050 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1051 else if (CurTy->isDoubleTy())
1052 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1053 else if (CurTy->isX86_FP80Ty()) {
1054 // Bits are not stored the same way as a normal i80 APInt, compensate.
1055 uint64_t Rearrange[2];
1056 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1057 Rearrange[1] = Record[0] >> 48;
1058 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1059 } else if (CurTy->isFP128Ty())
1060 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1061 else if (CurTy->isPPC_FP128Ty())
1062 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1064 V = UndefValue::get(CurTy);
1068 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1070 return Error("Invalid CST_AGGREGATE record");
1072 unsigned Size = Record.size();
1073 SmallVector<Constant*, 16> Elts;
1075 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1076 for (unsigned i = 0; i != Size; ++i)
1077 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1078 STy->getElementType(i)));
1079 V = ConstantStruct::get(STy, Elts);
1080 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1081 Type *EltTy = ATy->getElementType();
1082 for (unsigned i = 0; i != Size; ++i)
1083 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1084 V = ConstantArray::get(ATy, Elts);
1085 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1086 Type *EltTy = VTy->getElementType();
1087 for (unsigned i = 0; i != Size; ++i)
1088 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1089 V = ConstantVector::get(Elts);
1091 V = UndefValue::get(CurTy);
1095 case bitc::CST_CODE_STRING: { // STRING: [values]
1097 return Error("Invalid CST_AGGREGATE record");
1099 ArrayType *ATy = cast<ArrayType>(CurTy);
1100 Type *EltTy = ATy->getElementType();
1102 unsigned Size = Record.size();
1103 SmallVector<Constant*, 16> Elts;
1104 for (unsigned i = 0; i != Size; ++i)
1105 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1106 V = ConstantArray::get(ATy, Elts);
1109 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1111 return Error("Invalid CST_AGGREGATE record");
1113 ArrayType *ATy = cast<ArrayType>(CurTy);
1114 Type *EltTy = ATy->getElementType();
1116 unsigned Size = Record.size();
1117 SmallVector<Constant*, 16> Elts;
1118 for (unsigned i = 0; i != Size; ++i)
1119 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1120 Elts.push_back(Constant::getNullValue(EltTy));
1121 V = ConstantArray::get(ATy, Elts);
1124 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1126 return Error("Invalid CST_DATA record");
1128 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1129 unsigned Size = Record.size();
1131 if (EltTy->isIntegerTy(8)) {
1132 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1133 if (isa<VectorType>(CurTy))
1134 V = ConstantDataVector::get(Context, Elts);
1136 V = ConstantDataArray::get(Context, Elts);
1137 } else if (EltTy->isIntegerTy(16)) {
1138 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1139 if (isa<VectorType>(CurTy))
1140 V = ConstantDataVector::get(Context, Elts);
1142 V = ConstantDataArray::get(Context, Elts);
1143 } else if (EltTy->isIntegerTy(32)) {
1144 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1145 if (isa<VectorType>(CurTy))
1146 V = ConstantDataVector::get(Context, Elts);
1148 V = ConstantDataArray::get(Context, Elts);
1149 } else if (EltTy->isIntegerTy(64)) {
1150 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1151 if (isa<VectorType>(CurTy))
1152 V = ConstantDataVector::get(Context, Elts);
1154 V = ConstantDataArray::get(Context, Elts);
1155 } else if (EltTy->isFloatTy()) {
1156 SmallVector<float, 16> Elts;
1157 for (unsigned i = 0; i != Size; ++i) {
1158 union { uint32_t I; float F; };
1162 if (isa<VectorType>(CurTy))
1163 V = ConstantDataVector::get(Context, Elts);
1165 V = ConstantDataArray::get(Context, Elts);
1166 } else if (EltTy->isDoubleTy()) {
1167 SmallVector<double, 16> Elts;
1168 for (unsigned i = 0; i != Size; ++i) {
1169 union { uint64_t I; double F; };
1173 if (isa<VectorType>(CurTy))
1174 V = ConstantDataVector::get(Context, Elts);
1176 V = ConstantDataArray::get(Context, Elts);
1178 return Error("Unknown element type in CE_DATA");
1183 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1184 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1185 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1187 V = UndefValue::get(CurTy); // Unknown binop.
1189 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1190 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1192 if (Record.size() >= 4) {
1193 if (Opc == Instruction::Add ||
1194 Opc == Instruction::Sub ||
1195 Opc == Instruction::Mul ||
1196 Opc == Instruction::Shl) {
1197 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1198 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1199 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1200 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1201 } else if (Opc == Instruction::SDiv ||
1202 Opc == Instruction::UDiv ||
1203 Opc == Instruction::LShr ||
1204 Opc == Instruction::AShr) {
1205 if (Record[3] & (1 << bitc::PEO_EXACT))
1206 Flags |= SDivOperator::IsExact;
1209 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1213 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1214 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1215 int Opc = GetDecodedCastOpcode(Record[0]);
1217 V = UndefValue::get(CurTy); // Unknown cast.
1219 Type *OpTy = getTypeByID(Record[1]);
1220 if (!OpTy) return Error("Invalid CE_CAST record");
1221 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1222 V = ConstantExpr::getCast(Opc, Op, CurTy);
1226 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1227 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1228 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1229 SmallVector<Constant*, 16> Elts;
1230 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1231 Type *ElTy = getTypeByID(Record[i]);
1232 if (!ElTy) return Error("Invalid CE_GEP record");
1233 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1235 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1236 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1238 bitc::CST_CODE_CE_INBOUNDS_GEP);
1241 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1242 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1243 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1244 Type::getInt1Ty(Context)),
1245 ValueList.getConstantFwdRef(Record[1],CurTy),
1246 ValueList.getConstantFwdRef(Record[2],CurTy));
1248 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1249 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1251 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1252 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1253 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1254 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1255 V = ConstantExpr::getExtractElement(Op0, Op1);
1258 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1259 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1260 if (Record.size() < 3 || OpTy == 0)
1261 return Error("Invalid CE_INSERTELT record");
1262 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1263 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1264 OpTy->getElementType());
1265 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1266 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1269 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1270 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1271 if (Record.size() < 3 || OpTy == 0)
1272 return Error("Invalid CE_SHUFFLEVEC record");
1273 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1274 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1275 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1276 OpTy->getNumElements());
1277 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1278 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1281 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1282 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1284 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1285 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1286 return Error("Invalid CE_SHUFVEC_EX record");
1287 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1288 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1289 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1290 RTy->getNumElements());
1291 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1292 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1295 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1296 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1297 Type *OpTy = getTypeByID(Record[0]);
1298 if (OpTy == 0) return Error("Invalid CE_CMP record");
1299 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1300 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1302 if (OpTy->isFPOrFPVectorTy())
1303 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1305 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1308 case bitc::CST_CODE_INLINEASM: {
1309 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1310 std::string AsmStr, ConstrStr;
1311 bool HasSideEffects = Record[0] & 1;
1312 bool IsAlignStack = Record[0] >> 1;
1313 unsigned AsmStrSize = Record[1];
1314 if (2+AsmStrSize >= Record.size())
1315 return Error("Invalid INLINEASM record");
1316 unsigned ConstStrSize = Record[2+AsmStrSize];
1317 if (3+AsmStrSize+ConstStrSize > Record.size())
1318 return Error("Invalid INLINEASM record");
1320 for (unsigned i = 0; i != AsmStrSize; ++i)
1321 AsmStr += (char)Record[2+i];
1322 for (unsigned i = 0; i != ConstStrSize; ++i)
1323 ConstrStr += (char)Record[3+AsmStrSize+i];
1324 PointerType *PTy = cast<PointerType>(CurTy);
1325 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1326 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1329 case bitc::CST_CODE_BLOCKADDRESS:{
1330 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1331 Type *FnTy = getTypeByID(Record[0]);
1332 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1334 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1335 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1337 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1338 Type::getInt8Ty(Context),
1339 false, GlobalValue::InternalLinkage,
1341 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1347 ValueList.AssignValue(V, NextCstNo);
1351 if (NextCstNo != ValueList.size())
1352 return Error("Invalid constant reference!");
1354 if (Stream.ReadBlockEnd())
1355 return Error("Error at end of constants block");
1357 // Once all the constants have been read, go through and resolve forward
1359 ValueList.ResolveConstantForwardRefs();
1363 bool BitcodeReader::ParseUseLists() {
1364 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1365 return Error("Malformed block record");
1367 SmallVector<uint64_t, 64> Record;
1369 // Read all the records.
1371 unsigned Code = Stream.ReadCode();
1372 if (Code == bitc::END_BLOCK) {
1373 if (Stream.ReadBlockEnd())
1374 return Error("Error at end of use-list table block");
1378 if (Code == bitc::ENTER_SUBBLOCK) {
1379 // No known subblocks, always skip them.
1380 Stream.ReadSubBlockID();
1381 if (Stream.SkipBlock())
1382 return Error("Malformed block record");
1386 if (Code == bitc::DEFINE_ABBREV) {
1387 Stream.ReadAbbrevRecord();
1391 // Read a use list record.
1393 switch (Stream.ReadRecord(Code, Record)) {
1394 default: // Default behavior: unknown type.
1396 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1397 unsigned RecordLength = Record.size();
1398 if (RecordLength < 1)
1399 return Error ("Invalid UseList reader!");
1400 UseListRecords.push_back(Record);
1407 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1408 /// remember where it is and then skip it. This lets us lazily deserialize the
1410 bool BitcodeReader::RememberAndSkipFunctionBody() {
1411 // Get the function we are talking about.
1412 if (FunctionsWithBodies.empty())
1413 return Error("Insufficient function protos");
1415 Function *Fn = FunctionsWithBodies.back();
1416 FunctionsWithBodies.pop_back();
1418 // Save the current stream state.
1419 uint64_t CurBit = Stream.GetCurrentBitNo();
1420 DeferredFunctionInfo[Fn] = CurBit;
1422 // Skip over the function block for now.
1423 if (Stream.SkipBlock())
1424 return Error("Malformed block record");
1428 bool BitcodeReader::ParseModule() {
1429 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1430 return Error("Malformed block record");
1432 SmallVector<uint64_t, 64> Record;
1433 std::vector<std::string> SectionTable;
1434 std::vector<std::string> GCTable;
1436 // Read all the records for this module.
1437 while (!Stream.AtEndOfStream()) {
1438 unsigned Code = Stream.ReadCode();
1439 if (Code == bitc::END_BLOCK) {
1440 if (Stream.ReadBlockEnd())
1441 return Error("Error at end of module block");
1443 // Patch the initializers for globals and aliases up.
1444 ResolveGlobalAndAliasInits();
1445 if (!GlobalInits.empty() || !AliasInits.empty())
1446 return Error("Malformed global initializer set");
1447 if (!FunctionsWithBodies.empty())
1448 return Error("Too few function bodies found");
1450 // Look for intrinsic functions which need to be upgraded at some point
1451 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1454 if (UpgradeIntrinsicFunction(FI, NewFn))
1455 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1458 // Look for global variables which need to be renamed.
1459 for (Module::global_iterator
1460 GI = TheModule->global_begin(), GE = TheModule->global_end();
1462 UpgradeGlobalVariable(GI);
1464 // Force deallocation of memory for these vectors to favor the client that
1465 // want lazy deserialization.
1466 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1467 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1468 std::vector<Function*>().swap(FunctionsWithBodies);
1472 if (Code == bitc::ENTER_SUBBLOCK) {
1473 switch (Stream.ReadSubBlockID()) {
1474 default: // Skip unknown content.
1475 if (Stream.SkipBlock())
1476 return Error("Malformed block record");
1478 case bitc::BLOCKINFO_BLOCK_ID:
1479 if (Stream.ReadBlockInfoBlock())
1480 return Error("Malformed BlockInfoBlock");
1482 case bitc::PARAMATTR_BLOCK_ID:
1483 if (ParseAttributeBlock())
1486 case bitc::TYPE_BLOCK_ID_NEW:
1487 if (ParseTypeTable())
1490 case bitc::VALUE_SYMTAB_BLOCK_ID:
1491 if (ParseValueSymbolTable())
1494 case bitc::CONSTANTS_BLOCK_ID:
1495 if (ParseConstants() || ResolveGlobalAndAliasInits())
1498 case bitc::METADATA_BLOCK_ID:
1499 if (ParseMetadata())
1502 case bitc::FUNCTION_BLOCK_ID:
1503 // If this is the first function body we've seen, reverse the
1504 // FunctionsWithBodies list.
1505 if (!HasReversedFunctionsWithBodies) {
1506 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1507 HasReversedFunctionsWithBodies = true;
1510 if (RememberAndSkipFunctionBody())
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);
1674 // ALIAS: [alias type, aliasee val#, linkage]
1675 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1676 case bitc::MODULE_CODE_ALIAS: {
1677 if (Record.size() < 3)
1678 return Error("Invalid MODULE_ALIAS record");
1679 Type *Ty = getTypeByID(Record[0]);
1680 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1681 if (!Ty->isPointerTy())
1682 return Error("Function not a pointer type!");
1684 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1686 // Old bitcode files didn't have visibility field.
1687 if (Record.size() > 3)
1688 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1689 ValueList.push_back(NewGA);
1690 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1693 /// MODULE_CODE_PURGEVALS: [numvals]
1694 case bitc::MODULE_CODE_PURGEVALS:
1695 // Trim down the value list to the specified size.
1696 if (Record.size() < 1 || Record[0] > ValueList.size())
1697 return Error("Invalid MODULE_PURGEVALS record");
1698 ValueList.shrinkTo(Record[0]);
1704 return Error("Premature end of bitstream");
1707 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1710 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1711 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1713 if (Buffer->getBufferSize() & 3) {
1714 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1715 return Error("Invalid bitcode signature");
1717 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1720 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1721 // The magic number is 0x0B17C0DE stored in little endian.
1722 if (isBitcodeWrapper(BufPtr, BufEnd))
1723 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1724 return Error("Invalid bitcode wrapper header");
1726 StreamFile.init(BufPtr, BufEnd);
1727 Stream.init(StreamFile);
1729 // Sniff for the signature.
1730 if (Stream.Read(8) != 'B' ||
1731 Stream.Read(8) != 'C' ||
1732 Stream.Read(4) != 0x0 ||
1733 Stream.Read(4) != 0xC ||
1734 Stream.Read(4) != 0xE ||
1735 Stream.Read(4) != 0xD)
1736 return Error("Invalid bitcode signature");
1738 // We expect a number of well-defined blocks, though we don't necessarily
1739 // need to understand them all.
1740 while (!Stream.AtEndOfStream()) {
1741 unsigned Code = Stream.ReadCode();
1743 if (Code != bitc::ENTER_SUBBLOCK) {
1745 // The ranlib in xcode 4 will align archive members by appending newlines
1746 // to the end of them. If this file size is a multiple of 4 but not 8, we
1747 // have to read and ignore these final 4 bytes :-(
1748 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1749 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1750 Stream.AtEndOfStream())
1753 return Error("Invalid record at top-level");
1756 unsigned BlockID = Stream.ReadSubBlockID();
1758 // We only know the MODULE subblock ID.
1760 case bitc::BLOCKINFO_BLOCK_ID:
1761 if (Stream.ReadBlockInfoBlock())
1762 return Error("Malformed BlockInfoBlock");
1764 case bitc::MODULE_BLOCK_ID:
1765 // Reject multiple MODULE_BLOCK's in a single bitstream.
1767 return Error("Multiple MODULE_BLOCKs in same stream");
1773 if (Stream.SkipBlock())
1774 return Error("Malformed block record");
1782 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1783 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1784 return Error("Malformed block record");
1786 SmallVector<uint64_t, 64> Record;
1788 // Read all the records for this module.
1789 while (!Stream.AtEndOfStream()) {
1790 unsigned Code = Stream.ReadCode();
1791 if (Code == bitc::END_BLOCK) {
1792 if (Stream.ReadBlockEnd())
1793 return Error("Error at end of module block");
1798 if (Code == bitc::ENTER_SUBBLOCK) {
1799 switch (Stream.ReadSubBlockID()) {
1800 default: // Skip unknown content.
1801 if (Stream.SkipBlock())
1802 return Error("Malformed block record");
1808 if (Code == bitc::DEFINE_ABBREV) {
1809 Stream.ReadAbbrevRecord();
1814 switch (Stream.ReadRecord(Code, Record)) {
1815 default: break; // Default behavior, ignore unknown content.
1816 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1817 if (Record.size() < 1)
1818 return Error("Malformed MODULE_CODE_VERSION");
1819 // Only version #0 is supported so far.
1821 return Error("Unknown bitstream version!");
1823 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1825 if (ConvertToString(Record, 0, S))
1826 return Error("Invalid MODULE_CODE_TRIPLE record");
1834 return Error("Premature end of bitstream");
1837 bool BitcodeReader::ParseTriple(std::string &Triple) {
1838 if (Buffer->getBufferSize() & 3)
1839 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1841 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1842 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1844 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1845 // The magic number is 0x0B17C0DE stored in little endian.
1846 if (isBitcodeWrapper(BufPtr, BufEnd))
1847 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1848 return Error("Invalid bitcode wrapper header");
1850 StreamFile.init(BufPtr, BufEnd);
1851 Stream.init(StreamFile);
1853 // Sniff for the signature.
1854 if (Stream.Read(8) != 'B' ||
1855 Stream.Read(8) != 'C' ||
1856 Stream.Read(4) != 0x0 ||
1857 Stream.Read(4) != 0xC ||
1858 Stream.Read(4) != 0xE ||
1859 Stream.Read(4) != 0xD)
1860 return Error("Invalid bitcode signature");
1862 // We expect a number of well-defined blocks, though we don't necessarily
1863 // need to understand them all.
1864 while (!Stream.AtEndOfStream()) {
1865 unsigned Code = Stream.ReadCode();
1867 if (Code != bitc::ENTER_SUBBLOCK)
1868 return Error("Invalid record at top-level");
1870 unsigned BlockID = Stream.ReadSubBlockID();
1872 // We only know the MODULE subblock ID.
1874 case bitc::MODULE_BLOCK_ID:
1875 if (ParseModuleTriple(Triple))
1879 if (Stream.SkipBlock())
1880 return Error("Malformed block record");
1888 /// ParseMetadataAttachment - Parse metadata attachments.
1889 bool BitcodeReader::ParseMetadataAttachment() {
1890 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1891 return Error("Malformed block record");
1893 SmallVector<uint64_t, 64> Record;
1895 unsigned Code = Stream.ReadCode();
1896 if (Code == bitc::END_BLOCK) {
1897 if (Stream.ReadBlockEnd())
1898 return Error("Error at end of PARAMATTR block");
1901 if (Code == bitc::DEFINE_ABBREV) {
1902 Stream.ReadAbbrevRecord();
1905 // Read a metadata attachment record.
1907 switch (Stream.ReadRecord(Code, Record)) {
1908 default: // Default behavior: ignore.
1910 case bitc::METADATA_ATTACHMENT: {
1911 unsigned RecordLength = Record.size();
1912 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1913 return Error ("Invalid METADATA_ATTACHMENT reader!");
1914 Instruction *Inst = InstructionList[Record[0]];
1915 for (unsigned i = 1; i != RecordLength; i = i+2) {
1916 unsigned Kind = Record[i];
1917 DenseMap<unsigned, unsigned>::iterator I =
1918 MDKindMap.find(Kind);
1919 if (I == MDKindMap.end())
1920 return Error("Invalid metadata kind ID");
1921 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1922 Inst->setMetadata(I->second, cast<MDNode>(Node));
1931 /// ParseFunctionBody - Lazily parse the specified function body block.
1932 bool BitcodeReader::ParseFunctionBody(Function *F) {
1933 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1934 return Error("Malformed block record");
1936 InstructionList.clear();
1937 unsigned ModuleValueListSize = ValueList.size();
1938 unsigned ModuleMDValueListSize = MDValueList.size();
1940 // Add all the function arguments to the value table.
1941 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1942 ValueList.push_back(I);
1944 unsigned NextValueNo = ValueList.size();
1945 BasicBlock *CurBB = 0;
1946 unsigned CurBBNo = 0;
1950 // Read all the records.
1951 SmallVector<uint64_t, 64> Record;
1953 unsigned Code = Stream.ReadCode();
1954 if (Code == bitc::END_BLOCK) {
1955 if (Stream.ReadBlockEnd())
1956 return Error("Error at end of function block");
1960 if (Code == bitc::ENTER_SUBBLOCK) {
1961 switch (Stream.ReadSubBlockID()) {
1962 default: // Skip unknown content.
1963 if (Stream.SkipBlock())
1964 return Error("Malformed block record");
1966 case bitc::CONSTANTS_BLOCK_ID:
1967 if (ParseConstants()) return true;
1968 NextValueNo = ValueList.size();
1970 case bitc::VALUE_SYMTAB_BLOCK_ID:
1971 if (ParseValueSymbolTable()) return true;
1973 case bitc::METADATA_ATTACHMENT_ID:
1974 if (ParseMetadataAttachment()) return true;
1976 case bitc::METADATA_BLOCK_ID:
1977 if (ParseMetadata()) return true;
1983 if (Code == bitc::DEFINE_ABBREV) {
1984 Stream.ReadAbbrevRecord();
1991 unsigned BitCode = Stream.ReadRecord(Code, Record);
1993 default: // Default behavior: reject
1994 return Error("Unknown instruction");
1995 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1996 if (Record.size() < 1 || Record[0] == 0)
1997 return Error("Invalid DECLAREBLOCKS record");
1998 // Create all the basic blocks for the function.
1999 FunctionBBs.resize(Record[0]);
2000 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2001 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2002 CurBB = FunctionBBs[0];
2005 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2006 // This record indicates that the last instruction is at the same
2007 // location as the previous instruction with a location.
2010 // Get the last instruction emitted.
2011 if (CurBB && !CurBB->empty())
2013 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2014 !FunctionBBs[CurBBNo-1]->empty())
2015 I = &FunctionBBs[CurBBNo-1]->back();
2017 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2018 I->setDebugLoc(LastLoc);
2022 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2023 I = 0; // Get the last instruction emitted.
2024 if (CurBB && !CurBB->empty())
2026 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2027 !FunctionBBs[CurBBNo-1]->empty())
2028 I = &FunctionBBs[CurBBNo-1]->back();
2029 if (I == 0 || Record.size() < 4)
2030 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2032 unsigned Line = Record[0], Col = Record[1];
2033 unsigned ScopeID = Record[2], IAID = Record[3];
2035 MDNode *Scope = 0, *IA = 0;
2036 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2037 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2038 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2039 I->setDebugLoc(LastLoc);
2044 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2047 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2048 getValue(Record, OpNum, LHS->getType(), RHS) ||
2049 OpNum+1 > Record.size())
2050 return Error("Invalid BINOP record");
2052 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2053 if (Opc == -1) return Error("Invalid BINOP record");
2054 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2055 InstructionList.push_back(I);
2056 if (OpNum < Record.size()) {
2057 if (Opc == Instruction::Add ||
2058 Opc == Instruction::Sub ||
2059 Opc == Instruction::Mul ||
2060 Opc == Instruction::Shl) {
2061 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2062 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2063 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2064 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2065 } else if (Opc == Instruction::SDiv ||
2066 Opc == Instruction::UDiv ||
2067 Opc == Instruction::LShr ||
2068 Opc == Instruction::AShr) {
2069 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2070 cast<BinaryOperator>(I)->setIsExact(true);
2075 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2078 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2079 OpNum+2 != Record.size())
2080 return Error("Invalid CAST record");
2082 Type *ResTy = getTypeByID(Record[OpNum]);
2083 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2084 if (Opc == -1 || ResTy == 0)
2085 return Error("Invalid CAST record");
2086 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2087 InstructionList.push_back(I);
2090 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2091 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2094 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2095 return Error("Invalid GEP record");
2097 SmallVector<Value*, 16> GEPIdx;
2098 while (OpNum != Record.size()) {
2100 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2101 return Error("Invalid GEP record");
2102 GEPIdx.push_back(Op);
2105 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2106 InstructionList.push_back(I);
2107 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2108 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2112 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2113 // EXTRACTVAL: [opty, opval, n x indices]
2116 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2117 return Error("Invalid EXTRACTVAL record");
2119 SmallVector<unsigned, 4> EXTRACTVALIdx;
2120 for (unsigned RecSize = Record.size();
2121 OpNum != RecSize; ++OpNum) {
2122 uint64_t Index = Record[OpNum];
2123 if ((unsigned)Index != Index)
2124 return Error("Invalid EXTRACTVAL index");
2125 EXTRACTVALIdx.push_back((unsigned)Index);
2128 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2129 InstructionList.push_back(I);
2133 case bitc::FUNC_CODE_INST_INSERTVAL: {
2134 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2137 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2138 return Error("Invalid INSERTVAL record");
2140 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2141 return Error("Invalid INSERTVAL record");
2143 SmallVector<unsigned, 4> INSERTVALIdx;
2144 for (unsigned RecSize = Record.size();
2145 OpNum != RecSize; ++OpNum) {
2146 uint64_t Index = Record[OpNum];
2147 if ((unsigned)Index != Index)
2148 return Error("Invalid INSERTVAL index");
2149 INSERTVALIdx.push_back((unsigned)Index);
2152 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2153 InstructionList.push_back(I);
2157 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2158 // obsolete form of select
2159 // handles select i1 ... in old bitcode
2161 Value *TrueVal, *FalseVal, *Cond;
2162 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2163 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2164 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2165 return Error("Invalid SELECT record");
2167 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2168 InstructionList.push_back(I);
2172 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2173 // new form of select
2174 // handles select i1 or select [N x i1]
2176 Value *TrueVal, *FalseVal, *Cond;
2177 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2178 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2179 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2180 return Error("Invalid SELECT record");
2182 // select condition can be either i1 or [N x i1]
2183 if (VectorType* vector_type =
2184 dyn_cast<VectorType>(Cond->getType())) {
2186 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2187 return Error("Invalid SELECT condition type");
2190 if (Cond->getType() != Type::getInt1Ty(Context))
2191 return Error("Invalid SELECT condition type");
2194 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2195 InstructionList.push_back(I);
2199 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2202 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2203 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2204 return Error("Invalid EXTRACTELT record");
2205 I = ExtractElementInst::Create(Vec, Idx);
2206 InstructionList.push_back(I);
2210 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2212 Value *Vec, *Elt, *Idx;
2213 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2214 getValue(Record, OpNum,
2215 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2216 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2217 return Error("Invalid INSERTELT record");
2218 I = InsertElementInst::Create(Vec, Elt, Idx);
2219 InstructionList.push_back(I);
2223 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2225 Value *Vec1, *Vec2, *Mask;
2226 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2227 getValue(Record, OpNum, Vec1->getType(), Vec2))
2228 return Error("Invalid SHUFFLEVEC record");
2230 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2231 return Error("Invalid SHUFFLEVEC record");
2232 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2233 InstructionList.push_back(I);
2237 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2238 // Old form of ICmp/FCmp returning bool
2239 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2240 // both legal on vectors but had different behaviour.
2241 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2242 // FCmp/ICmp returning bool or vector of bool
2246 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2247 getValue(Record, OpNum, LHS->getType(), RHS) ||
2248 OpNum+1 != Record.size())
2249 return Error("Invalid CMP record");
2251 if (LHS->getType()->isFPOrFPVectorTy())
2252 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2254 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2255 InstructionList.push_back(I);
2259 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2261 unsigned Size = Record.size();
2263 I = ReturnInst::Create(Context);
2264 InstructionList.push_back(I);
2270 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2271 return Error("Invalid RET record");
2272 if (OpNum != Record.size())
2273 return Error("Invalid RET record");
2275 I = ReturnInst::Create(Context, Op);
2276 InstructionList.push_back(I);
2279 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2280 if (Record.size() != 1 && Record.size() != 3)
2281 return Error("Invalid BR record");
2282 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2284 return Error("Invalid BR record");
2286 if (Record.size() == 1) {
2287 I = BranchInst::Create(TrueDest);
2288 InstructionList.push_back(I);
2291 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2292 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2293 if (FalseDest == 0 || Cond == 0)
2294 return Error("Invalid BR record");
2295 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2296 InstructionList.push_back(I);
2300 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2301 if (Record.size() < 3 || (Record.size() & 1) == 0)
2302 return Error("Invalid SWITCH record");
2303 Type *OpTy = getTypeByID(Record[0]);
2304 Value *Cond = getFnValueByID(Record[1], OpTy);
2305 BasicBlock *Default = getBasicBlock(Record[2]);
2306 if (OpTy == 0 || Cond == 0 || Default == 0)
2307 return Error("Invalid SWITCH record");
2308 unsigned NumCases = (Record.size()-3)/2;
2309 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2310 InstructionList.push_back(SI);
2311 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2312 ConstantInt *CaseVal =
2313 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2314 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2315 if (CaseVal == 0 || DestBB == 0) {
2317 return Error("Invalid SWITCH record!");
2319 SI->addCase(CaseVal, DestBB);
2324 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2325 if (Record.size() < 2)
2326 return Error("Invalid INDIRECTBR record");
2327 Type *OpTy = getTypeByID(Record[0]);
2328 Value *Address = getFnValueByID(Record[1], OpTy);
2329 if (OpTy == 0 || Address == 0)
2330 return Error("Invalid INDIRECTBR record");
2331 unsigned NumDests = Record.size()-2;
2332 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2333 InstructionList.push_back(IBI);
2334 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2335 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2336 IBI->addDestination(DestBB);
2339 return Error("Invalid INDIRECTBR record!");
2346 case bitc::FUNC_CODE_INST_INVOKE: {
2347 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2348 if (Record.size() < 4) return Error("Invalid INVOKE record");
2349 AttrListPtr PAL = getAttributes(Record[0]);
2350 unsigned CCInfo = Record[1];
2351 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2352 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2356 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2357 return Error("Invalid INVOKE record");
2359 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2360 FunctionType *FTy = !CalleeTy ? 0 :
2361 dyn_cast<FunctionType>(CalleeTy->getElementType());
2363 // Check that the right number of fixed parameters are here.
2364 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2365 Record.size() < OpNum+FTy->getNumParams())
2366 return Error("Invalid INVOKE record");
2368 SmallVector<Value*, 16> Ops;
2369 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2370 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2371 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2374 if (!FTy->isVarArg()) {
2375 if (Record.size() != OpNum)
2376 return Error("Invalid INVOKE record");
2378 // Read type/value pairs for varargs params.
2379 while (OpNum != Record.size()) {
2381 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2382 return Error("Invalid INVOKE record");
2387 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2388 InstructionList.push_back(I);
2389 cast<InvokeInst>(I)->setCallingConv(
2390 static_cast<CallingConv::ID>(CCInfo));
2391 cast<InvokeInst>(I)->setAttributes(PAL);
2394 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2397 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2398 return Error("Invalid RESUME record");
2399 I = ResumeInst::Create(Val);
2400 InstructionList.push_back(I);
2403 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2404 I = new UnwindInst(Context);
2405 InstructionList.push_back(I);
2407 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2408 I = new UnreachableInst(Context);
2409 InstructionList.push_back(I);
2411 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2412 if (Record.size() < 1 || ((Record.size()-1)&1))
2413 return Error("Invalid PHI record");
2414 Type *Ty = getTypeByID(Record[0]);
2415 if (!Ty) return Error("Invalid PHI record");
2417 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2418 InstructionList.push_back(PN);
2420 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2421 Value *V = getFnValueByID(Record[1+i], Ty);
2422 BasicBlock *BB = getBasicBlock(Record[2+i]);
2423 if (!V || !BB) return Error("Invalid PHI record");
2424 PN->addIncoming(V, BB);
2430 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2431 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2433 if (Record.size() < 4)
2434 return Error("Invalid LANDINGPAD record");
2435 Type *Ty = getTypeByID(Record[Idx++]);
2436 if (!Ty) return Error("Invalid LANDINGPAD record");
2438 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2439 return Error("Invalid LANDINGPAD record");
2441 bool IsCleanup = !!Record[Idx++];
2442 unsigned NumClauses = Record[Idx++];
2443 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2444 LP->setCleanup(IsCleanup);
2445 for (unsigned J = 0; J != NumClauses; ++J) {
2446 LandingPadInst::ClauseType CT =
2447 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2450 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2452 return Error("Invalid LANDINGPAD record");
2455 assert((CT != LandingPadInst::Catch ||
2456 !isa<ArrayType>(Val->getType())) &&
2457 "Catch clause has a invalid type!");
2458 assert((CT != LandingPadInst::Filter ||
2459 isa<ArrayType>(Val->getType())) &&
2460 "Filter clause has invalid type!");
2465 InstructionList.push_back(I);
2469 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2470 if (Record.size() != 4)
2471 return Error("Invalid ALLOCA record");
2473 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2474 Type *OpTy = getTypeByID(Record[1]);
2475 Value *Size = getFnValueByID(Record[2], OpTy);
2476 unsigned Align = Record[3];
2477 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2478 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2479 InstructionList.push_back(I);
2482 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2485 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2486 OpNum+2 != Record.size())
2487 return Error("Invalid LOAD record");
2489 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2490 InstructionList.push_back(I);
2493 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2494 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2497 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2498 OpNum+4 != Record.size())
2499 return Error("Invalid LOADATOMIC record");
2502 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2503 if (Ordering == NotAtomic || Ordering == Release ||
2504 Ordering == AcquireRelease)
2505 return Error("Invalid LOADATOMIC record");
2506 if (Ordering != NotAtomic && Record[OpNum] == 0)
2507 return Error("Invalid LOADATOMIC record");
2508 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2510 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2511 Ordering, SynchScope);
2512 InstructionList.push_back(I);
2515 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2518 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2519 getValue(Record, OpNum,
2520 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2521 OpNum+2 != Record.size())
2522 return Error("Invalid STORE record");
2524 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2525 InstructionList.push_back(I);
2528 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2529 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2532 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2533 getValue(Record, OpNum,
2534 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2535 OpNum+4 != Record.size())
2536 return Error("Invalid STOREATOMIC record");
2538 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2539 if (Ordering == NotAtomic || Ordering == Acquire ||
2540 Ordering == AcquireRelease)
2541 return Error("Invalid STOREATOMIC record");
2542 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2543 if (Ordering != NotAtomic && Record[OpNum] == 0)
2544 return Error("Invalid STOREATOMIC record");
2546 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2547 Ordering, SynchScope);
2548 InstructionList.push_back(I);
2551 case bitc::FUNC_CODE_INST_CMPXCHG: {
2552 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2554 Value *Ptr, *Cmp, *New;
2555 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2556 getValue(Record, OpNum,
2557 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2558 getValue(Record, OpNum,
2559 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2560 OpNum+3 != Record.size())
2561 return Error("Invalid CMPXCHG record");
2562 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2563 if (Ordering == NotAtomic || Ordering == Unordered)
2564 return Error("Invalid CMPXCHG record");
2565 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2566 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2567 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2568 InstructionList.push_back(I);
2571 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2572 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2575 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2576 getValue(Record, OpNum,
2577 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2578 OpNum+4 != Record.size())
2579 return Error("Invalid ATOMICRMW record");
2580 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2581 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2582 Operation > AtomicRMWInst::LAST_BINOP)
2583 return Error("Invalid ATOMICRMW record");
2584 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2585 if (Ordering == NotAtomic || Ordering == Unordered)
2586 return Error("Invalid ATOMICRMW record");
2587 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2588 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2589 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2590 InstructionList.push_back(I);
2593 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2594 if (2 != Record.size())
2595 return Error("Invalid FENCE record");
2596 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2597 if (Ordering == NotAtomic || Ordering == Unordered ||
2598 Ordering == Monotonic)
2599 return Error("Invalid FENCE record");
2600 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2601 I = new FenceInst(Context, Ordering, SynchScope);
2602 InstructionList.push_back(I);
2605 case bitc::FUNC_CODE_INST_CALL: {
2606 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2607 if (Record.size() < 3)
2608 return Error("Invalid CALL record");
2610 AttrListPtr PAL = getAttributes(Record[0]);
2611 unsigned CCInfo = Record[1];
2615 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2616 return Error("Invalid CALL record");
2618 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2619 FunctionType *FTy = 0;
2620 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2621 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2622 return Error("Invalid CALL record");
2624 SmallVector<Value*, 16> Args;
2625 // Read the fixed params.
2626 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2627 if (FTy->getParamType(i)->isLabelTy())
2628 Args.push_back(getBasicBlock(Record[OpNum]));
2630 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2631 if (Args.back() == 0) return Error("Invalid CALL record");
2634 // Read type/value pairs for varargs params.
2635 if (!FTy->isVarArg()) {
2636 if (OpNum != Record.size())
2637 return Error("Invalid CALL record");
2639 while (OpNum != Record.size()) {
2641 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2642 return Error("Invalid CALL record");
2647 I = CallInst::Create(Callee, Args);
2648 InstructionList.push_back(I);
2649 cast<CallInst>(I)->setCallingConv(
2650 static_cast<CallingConv::ID>(CCInfo>>1));
2651 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2652 cast<CallInst>(I)->setAttributes(PAL);
2655 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2656 if (Record.size() < 3)
2657 return Error("Invalid VAARG record");
2658 Type *OpTy = getTypeByID(Record[0]);
2659 Value *Op = getFnValueByID(Record[1], OpTy);
2660 Type *ResTy = getTypeByID(Record[2]);
2661 if (!OpTy || !Op || !ResTy)
2662 return Error("Invalid VAARG record");
2663 I = new VAArgInst(Op, ResTy);
2664 InstructionList.push_back(I);
2669 // Add instruction to end of current BB. If there is no current BB, reject
2673 return Error("Invalid instruction with no BB");
2675 CurBB->getInstList().push_back(I);
2677 // If this was a terminator instruction, move to the next block.
2678 if (isa<TerminatorInst>(I)) {
2680 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2683 // Non-void values get registered in the value table for future use.
2684 if (I && !I->getType()->isVoidTy())
2685 ValueList.AssignValue(I, NextValueNo++);
2688 // Check the function list for unresolved values.
2689 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2690 if (A->getParent() == 0) {
2691 // We found at least one unresolved value. Nuke them all to avoid leaks.
2692 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2693 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2694 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2698 return Error("Never resolved value found in function!");
2702 // FIXME: Check for unresolved forward-declared metadata references
2703 // and clean up leaks.
2705 // See if anything took the address of blocks in this function. If so,
2706 // resolve them now.
2707 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2708 BlockAddrFwdRefs.find(F);
2709 if (BAFRI != BlockAddrFwdRefs.end()) {
2710 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2711 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2712 unsigned BlockIdx = RefList[i].first;
2713 if (BlockIdx >= FunctionBBs.size())
2714 return Error("Invalid blockaddress block #");
2716 GlobalVariable *FwdRef = RefList[i].second;
2717 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2718 FwdRef->eraseFromParent();
2721 BlockAddrFwdRefs.erase(BAFRI);
2724 // Trim the value list down to the size it was before we parsed this function.
2725 ValueList.shrinkTo(ModuleValueListSize);
2726 MDValueList.shrinkTo(ModuleMDValueListSize);
2727 std::vector<BasicBlock*>().swap(FunctionBBs);
2731 //===----------------------------------------------------------------------===//
2732 // GVMaterializer implementation
2733 //===----------------------------------------------------------------------===//
2736 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2737 if (const Function *F = dyn_cast<Function>(GV)) {
2738 return F->isDeclaration() &&
2739 DeferredFunctionInfo.count(const_cast<Function*>(F));
2744 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2745 Function *F = dyn_cast<Function>(GV);
2746 // If it's not a function or is already material, ignore the request.
2747 if (!F || !F->isMaterializable()) return false;
2749 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2750 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2752 // Move the bit stream to the saved position of the deferred function body.
2753 Stream.JumpToBit(DFII->second);
2755 if (ParseFunctionBody(F)) {
2756 if (ErrInfo) *ErrInfo = ErrorString;
2760 // Upgrade any old intrinsic calls in the function.
2761 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2762 E = UpgradedIntrinsics.end(); I != E; ++I) {
2763 if (I->first != I->second) {
2764 for (Value::use_iterator UI = I->first->use_begin(),
2765 UE = I->first->use_end(); UI != UE; ) {
2766 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2767 UpgradeIntrinsicCall(CI, I->second);
2775 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2776 const Function *F = dyn_cast<Function>(GV);
2777 if (!F || F->isDeclaration())
2779 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2782 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2783 Function *F = dyn_cast<Function>(GV);
2784 // If this function isn't dematerializable, this is a noop.
2785 if (!F || !isDematerializable(F))
2788 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2790 // Just forget the function body, we can remat it later.
2795 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2796 assert(M == TheModule &&
2797 "Can only Materialize the Module this BitcodeReader is attached to.");
2798 // Iterate over the module, deserializing any functions that are still on
2800 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2802 if (F->isMaterializable() &&
2803 Materialize(F, ErrInfo))
2806 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2807 // delete the old functions to clean up. We can't do this unless the entire
2808 // module is materialized because there could always be another function body
2809 // with calls to the old function.
2810 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2811 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2812 if (I->first != I->second) {
2813 for (Value::use_iterator UI = I->first->use_begin(),
2814 UE = I->first->use_end(); UI != UE; ) {
2815 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2816 UpgradeIntrinsicCall(CI, I->second);
2818 if (!I->first->use_empty())
2819 I->first->replaceAllUsesWith(I->second);
2820 I->first->eraseFromParent();
2823 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2829 //===----------------------------------------------------------------------===//
2830 // External interface
2831 //===----------------------------------------------------------------------===//
2833 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2835 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2836 LLVMContext& Context,
2837 std::string *ErrMsg) {
2838 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2839 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2840 M->setMaterializer(R);
2841 if (R->ParseBitcodeInto(M)) {
2843 *ErrMsg = R->getErrorString();
2845 delete M; // Also deletes R.
2848 // Have the BitcodeReader dtor delete 'Buffer'.
2849 R->setBufferOwned(true);
2851 R->materializeForwardReferencedFunctions();
2856 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2857 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2858 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2859 std::string *ErrMsg){
2860 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2863 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2864 // there was an error.
2865 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2867 // Read in the entire module, and destroy the BitcodeReader.
2868 if (M->MaterializeAllPermanently(ErrMsg)) {
2873 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2874 // written. We must defer until the Module has been fully materialized.
2879 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2880 LLVMContext& Context,
2881 std::string *ErrMsg) {
2882 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2883 // Don't let the BitcodeReader dtor delete 'Buffer'.
2884 R->setBufferOwned(false);
2886 std::string Triple("");
2887 if (R->ParseTriple(Triple))
2889 *ErrMsg = R->getErrorString();