1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitcodeReader class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "BitcodeReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/AutoUpgrade.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/OperandTraits.h"
30 void BitcodeReader::FreeState() {
34 std::vector<Type*>().swap(TypeList);
38 std::vector<AttrListPtr>().swap(MAttributes);
39 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
45 //===----------------------------------------------------------------------===//
46 // Helper functions to implement forward reference resolution, etc.
47 //===----------------------------------------------------------------------===//
49 /// ConvertToString - Convert a string from a record into an std::string, return
51 template<typename StrTy>
52 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
54 if (Idx > Record.size())
57 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58 Result += (char)Record[i];
62 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
64 default: // Map unknown/new linkages to external
65 case 0: return GlobalValue::ExternalLinkage;
66 case 1: return GlobalValue::WeakAnyLinkage;
67 case 2: return GlobalValue::AppendingLinkage;
68 case 3: return GlobalValue::InternalLinkage;
69 case 4: return GlobalValue::LinkOnceAnyLinkage;
70 case 5: return GlobalValue::DLLImportLinkage;
71 case 6: return GlobalValue::DLLExportLinkage;
72 case 7: return GlobalValue::ExternalWeakLinkage;
73 case 8: return GlobalValue::CommonLinkage;
74 case 9: return GlobalValue::PrivateLinkage;
75 case 10: return GlobalValue::WeakODRLinkage;
76 case 11: return GlobalValue::LinkOnceODRLinkage;
77 case 12: return GlobalValue::AvailableExternallyLinkage;
78 case 13: return GlobalValue::LinkerPrivateLinkage;
79 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
80 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
84 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
86 default: // Map unknown visibilities to default.
87 case 0: return GlobalValue::DefaultVisibility;
88 case 1: return GlobalValue::HiddenVisibility;
89 case 2: return GlobalValue::ProtectedVisibility;
93 static int GetDecodedCastOpcode(unsigned Val) {
96 case bitc::CAST_TRUNC : return Instruction::Trunc;
97 case bitc::CAST_ZEXT : return Instruction::ZExt;
98 case bitc::CAST_SEXT : return Instruction::SExt;
99 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
100 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
101 case bitc::CAST_UITOFP : return Instruction::UIToFP;
102 case bitc::CAST_SITOFP : return Instruction::SIToFP;
103 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
104 case bitc::CAST_FPEXT : return Instruction::FPExt;
105 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
106 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
107 case bitc::CAST_BITCAST : return Instruction::BitCast;
110 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
113 case bitc::BINOP_ADD:
114 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
115 case bitc::BINOP_SUB:
116 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
117 case bitc::BINOP_MUL:
118 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
119 case bitc::BINOP_UDIV: return Instruction::UDiv;
120 case bitc::BINOP_SDIV:
121 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
122 case bitc::BINOP_UREM: return Instruction::URem;
123 case bitc::BINOP_SREM:
124 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
125 case bitc::BINOP_SHL: return Instruction::Shl;
126 case bitc::BINOP_LSHR: return Instruction::LShr;
127 case bitc::BINOP_ASHR: return Instruction::AShr;
128 case bitc::BINOP_AND: return Instruction::And;
129 case bitc::BINOP_OR: return Instruction::Or;
130 case bitc::BINOP_XOR: return Instruction::Xor;
134 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
136 default: return AtomicRMWInst::BAD_BINOP;
137 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
138 case bitc::RMW_ADD: return AtomicRMWInst::Add;
139 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
140 case bitc::RMW_AND: return AtomicRMWInst::And;
141 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
142 case bitc::RMW_OR: return AtomicRMWInst::Or;
143 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
144 case bitc::RMW_MAX: return AtomicRMWInst::Max;
145 case bitc::RMW_MIN: return AtomicRMWInst::Min;
146 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
147 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
151 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
153 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
154 case bitc::ORDERING_UNORDERED: return Unordered;
155 case bitc::ORDERING_MONOTONIC: return Monotonic;
156 case bitc::ORDERING_ACQUIRE: return Acquire;
157 case bitc::ORDERING_RELEASE: return Release;
158 case bitc::ORDERING_ACQREL: return AcquireRelease;
159 default: // Map unknown orderings to sequentially-consistent.
160 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
164 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
166 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
167 default: // Map unknown scopes to cross-thread.
168 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
174 /// @brief A class for maintaining the slot number definition
175 /// as a placeholder for the actual definition for forward constants defs.
176 class ConstantPlaceHolder : public ConstantExpr {
177 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
179 // allocate space for exactly one operand
180 void *operator new(size_t s) {
181 return User::operator new(s, 1);
183 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
184 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
185 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
188 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
189 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
190 static bool classof(const Value *V) {
191 return isa<ConstantExpr>(V) &&
192 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
196 /// Provide fast operand accessors
197 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
201 // FIXME: can we inherit this from ConstantExpr?
203 struct OperandTraits<ConstantPlaceHolder> :
204 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
209 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
218 WeakVH &OldV = ValuePtrs[Idx];
224 // Handle constants and non-constants (e.g. instrs) differently for
226 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
227 ResolveConstants.push_back(std::make_pair(PHC, Idx));
230 // If there was a forward reference to this value, replace it.
231 Value *PrevVal = OldV;
232 OldV->replaceAllUsesWith(V);
238 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
243 if (Value *V = ValuePtrs[Idx]) {
244 assert(Ty == V->getType() && "Type mismatch in constant table!");
245 return cast<Constant>(V);
248 // Create and return a placeholder, which will later be RAUW'd.
249 Constant *C = new ConstantPlaceHolder(Ty, Context);
254 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
258 if (Value *V = ValuePtrs[Idx]) {
259 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
263 // No type specified, must be invalid reference.
264 if (Ty == 0) return 0;
266 // Create and return a placeholder, which will later be RAUW'd.
267 Value *V = new Argument(Ty);
272 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
273 /// resolves any forward references. The idea behind this is that we sometimes
274 /// get constants (such as large arrays) which reference *many* forward ref
275 /// constants. Replacing each of these causes a lot of thrashing when
276 /// building/reuniquing the constant. Instead of doing this, we look at all the
277 /// uses and rewrite all the place holders at once for any constant that uses
279 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
280 // Sort the values by-pointer so that they are efficient to look up with a
282 std::sort(ResolveConstants.begin(), ResolveConstants.end());
284 SmallVector<Constant*, 64> NewOps;
286 while (!ResolveConstants.empty()) {
287 Value *RealVal = operator[](ResolveConstants.back().second);
288 Constant *Placeholder = ResolveConstants.back().first;
289 ResolveConstants.pop_back();
291 // Loop over all users of the placeholder, updating them to reference the
292 // new value. If they reference more than one placeholder, update them all
294 while (!Placeholder->use_empty()) {
295 Value::use_iterator UI = Placeholder->use_begin();
298 // If the using object isn't uniqued, just update the operands. This
299 // handles instructions and initializers for global variables.
300 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
301 UI.getUse().set(RealVal);
305 // Otherwise, we have a constant that uses the placeholder. Replace that
306 // constant with a new constant that has *all* placeholder uses updated.
307 Constant *UserC = cast<Constant>(U);
308 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
311 if (!isa<ConstantPlaceHolder>(*I)) {
312 // Not a placeholder reference.
314 } else if (*I == Placeholder) {
315 // Common case is that it just references this one placeholder.
318 // Otherwise, look up the placeholder in ResolveConstants.
319 ResolveConstantsTy::iterator It =
320 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
321 std::pair<Constant*, unsigned>(cast<Constant>(*I),
323 assert(It != ResolveConstants.end() && It->first == *I);
324 NewOp = operator[](It->second);
327 NewOps.push_back(cast<Constant>(NewOp));
330 // Make the new constant.
332 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
333 NewC = ConstantArray::get(UserCA->getType(), NewOps);
334 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
335 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
336 } else if (isa<ConstantVector>(UserC)) {
337 NewC = ConstantVector::get(NewOps);
339 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
340 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
343 UserC->replaceAllUsesWith(NewC);
344 UserC->destroyConstant();
348 // Update all ValueHandles, they should be the only users at this point.
349 Placeholder->replaceAllUsesWith(RealVal);
354 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
363 WeakVH &OldV = MDValuePtrs[Idx];
369 // If there was a forward reference to this value, replace it.
370 MDNode *PrevVal = cast<MDNode>(OldV);
371 OldV->replaceAllUsesWith(V);
372 MDNode::deleteTemporary(PrevVal);
373 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
375 MDValuePtrs[Idx] = V;
378 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
382 if (Value *V = MDValuePtrs[Idx]) {
383 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
387 // Create and return a placeholder, which will later be RAUW'd.
388 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
389 MDValuePtrs[Idx] = V;
393 Type *BitcodeReader::getTypeByID(unsigned ID) {
394 // The type table size is always specified correctly.
395 if (ID >= TypeList.size())
398 if (Type *Ty = TypeList[ID])
401 // If we have a forward reference, the only possible case is when it is to a
402 // named struct. Just create a placeholder for now.
403 return TypeList[ID] = StructType::createNamed(Context, "");
406 /// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable.
407 Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) {
408 if (ID >= TypeList.size())
409 TypeList.resize(ID+1);
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 = Attribute::None;
466 Attributes FnAttribute = Attribute::None;
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);
479 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
480 Record[i+1] = ReconstitutedAttr;
483 RetAttribute = Record[i+1];
484 else if (Record[i] == ~0U)
485 FnAttribute = Record[i+1];
488 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
489 Attribute::ReadOnly|Attribute::ReadNone);
491 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
492 (RetAttribute & OldRetAttrs) != 0) {
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 (Record[i+1] != Attribute::None)
510 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
513 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
521 bool BitcodeReader::ParseTypeTable() {
522 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
523 return Error("Malformed block record");
525 return ParseTypeTableBody();
528 bool BitcodeReader::ParseTypeTableBody() {
529 if (!TypeList.empty())
530 return Error("Multiple TYPE_BLOCKs found!");
532 SmallVector<uint64_t, 64> Record;
533 unsigned NumRecords = 0;
535 SmallString<64> TypeName;
537 // Read all the records for this type table.
539 unsigned Code = Stream.ReadCode();
540 if (Code == bitc::END_BLOCK) {
541 if (NumRecords != TypeList.size())
542 return Error("Invalid type forward reference in TYPE_BLOCK");
543 if (Stream.ReadBlockEnd())
544 return Error("Error at end of type table block");
548 if (Code == bitc::ENTER_SUBBLOCK) {
549 // No known subblocks, always skip them.
550 Stream.ReadSubBlockID();
551 if (Stream.SkipBlock())
552 return Error("Malformed block record");
556 if (Code == bitc::DEFINE_ABBREV) {
557 Stream.ReadAbbrevRecord();
564 switch (Stream.ReadRecord(Code, Record)) {
565 default: return Error("unknown type in type table");
566 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
567 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
568 // type list. This allows us to reserve space.
569 if (Record.size() < 1)
570 return Error("Invalid TYPE_CODE_NUMENTRY record");
571 TypeList.resize(Record[0]);
573 case bitc::TYPE_CODE_VOID: // VOID
574 ResultTy = Type::getVoidTy(Context);
576 case bitc::TYPE_CODE_FLOAT: // FLOAT
577 ResultTy = Type::getFloatTy(Context);
579 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
580 ResultTy = Type::getDoubleTy(Context);
582 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
583 ResultTy = Type::getX86_FP80Ty(Context);
585 case bitc::TYPE_CODE_FP128: // FP128
586 ResultTy = Type::getFP128Ty(Context);
588 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
589 ResultTy = Type::getPPC_FP128Ty(Context);
591 case bitc::TYPE_CODE_LABEL: // LABEL
592 ResultTy = Type::getLabelTy(Context);
594 case bitc::TYPE_CODE_METADATA: // METADATA
595 ResultTy = Type::getMetadataTy(Context);
597 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
598 ResultTy = Type::getX86_MMXTy(Context);
600 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
601 if (Record.size() < 1)
602 return Error("Invalid Integer type record");
604 ResultTy = IntegerType::get(Context, Record[0]);
606 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
607 // [pointee type, address space]
608 if (Record.size() < 1)
609 return Error("Invalid POINTER type record");
610 unsigned AddressSpace = 0;
611 if (Record.size() == 2)
612 AddressSpace = Record[1];
613 ResultTy = getTypeByID(Record[0]);
614 if (ResultTy == 0) return Error("invalid element type in pointer type");
615 ResultTy = PointerType::get(ResultTy, AddressSpace);
618 case bitc::TYPE_CODE_FUNCTION: {
619 // FIXME: attrid is dead, remove it in LLVM 3.0
620 // FUNCTION: [vararg, attrid, retty, paramty x N]
621 if (Record.size() < 3)
622 return Error("Invalid FUNCTION type record");
623 std::vector<Type*> ArgTys;
624 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
625 if (Type *T = getTypeByID(Record[i]))
631 ResultTy = getTypeByID(Record[2]);
632 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
633 return Error("invalid type in function type");
635 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
638 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
639 if (Record.size() < 1)
640 return Error("Invalid STRUCT type record");
641 std::vector<Type*> EltTys;
642 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
643 if (Type *T = getTypeByID(Record[i]))
648 if (EltTys.size() != Record.size()-1)
649 return Error("invalid type in struct type");
650 ResultTy = StructType::get(Context, EltTys, Record[0]);
653 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
654 if (ConvertToString(Record, 0, TypeName))
655 return Error("Invalid STRUCT_NAME record");
658 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
659 if (Record.size() < 1)
660 return Error("Invalid STRUCT type record");
662 if (NumRecords >= TypeList.size())
663 return Error("invalid TYPE table");
665 // Check to see if this was forward referenced, if so fill in the temp.
666 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
668 Res->setName(TypeName);
669 TypeList[NumRecords] = 0;
670 } else // Otherwise, create a new struct.
671 Res = StructType::createNamed(Context, TypeName);
674 SmallVector<Type*, 8> EltTys;
675 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
676 if (Type *T = getTypeByID(Record[i]))
681 if (EltTys.size() != Record.size()-1)
682 return Error("invalid STRUCT type record");
683 Res->setBody(EltTys, Record[0]);
687 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
688 if (Record.size() != 1)
689 return Error("Invalid OPAQUE type record");
691 if (NumRecords >= TypeList.size())
692 return Error("invalid TYPE table");
694 // Check to see if this was forward referenced, if so fill in the temp.
695 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
697 Res->setName(TypeName);
698 TypeList[NumRecords] = 0;
699 } else // Otherwise, create a new struct with no body.
700 Res = StructType::createNamed(Context, TypeName);
705 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
706 if (Record.size() < 2)
707 return Error("Invalid ARRAY type record");
708 if ((ResultTy = getTypeByID(Record[1])))
709 ResultTy = ArrayType::get(ResultTy, Record[0]);
711 return Error("Invalid ARRAY type element");
713 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
714 if (Record.size() < 2)
715 return Error("Invalid VECTOR type record");
716 if ((ResultTy = getTypeByID(Record[1])))
717 ResultTy = VectorType::get(ResultTy, Record[0]);
719 return Error("Invalid ARRAY type element");
723 if (NumRecords >= TypeList.size())
724 return Error("invalid TYPE table");
725 assert(ResultTy && "Didn't read a type?");
726 assert(TypeList[NumRecords] == 0 && "Already read type?");
727 TypeList[NumRecords++] = ResultTy;
731 // FIXME: Remove in LLVM 3.1
732 bool BitcodeReader::ParseOldTypeTable() {
733 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_OLD))
734 return Error("Malformed block record");
736 if (!TypeList.empty())
737 return Error("Multiple TYPE_BLOCKs found!");
740 // While horrible, we have no good ordering of types in the bc file. Just
741 // iteratively parse types out of the bc file in multiple passes until we get
742 // them all. Do this by saving a cursor for the start of the type block.
743 BitstreamCursor StartOfTypeBlockCursor(Stream);
745 unsigned NumTypesRead = 0;
747 SmallVector<uint64_t, 64> Record;
749 unsigned NextTypeID = 0;
750 bool ReadAnyTypes = false;
752 // Read all the records for this type table.
754 unsigned Code = Stream.ReadCode();
755 if (Code == bitc::END_BLOCK) {
756 if (NextTypeID != TypeList.size())
757 return Error("Invalid type forward reference in TYPE_BLOCK_ID_OLD");
759 // If we haven't read all of the types yet, iterate again.
760 if (NumTypesRead != TypeList.size()) {
761 // If we didn't successfully read any types in this pass, then we must
762 // have an unhandled forward reference.
764 return Error("Obsolete bitcode contains unhandled recursive type");
766 Stream = StartOfTypeBlockCursor;
770 if (Stream.ReadBlockEnd())
771 return Error("Error at end of type table block");
775 if (Code == bitc::ENTER_SUBBLOCK) {
776 // No known subblocks, always skip them.
777 Stream.ReadSubBlockID();
778 if (Stream.SkipBlock())
779 return Error("Malformed block record");
783 if (Code == bitc::DEFINE_ABBREV) {
784 Stream.ReadAbbrevRecord();
791 switch (Stream.ReadRecord(Code, Record)) {
792 default: return Error("unknown type in type table");
793 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
794 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
795 // type list. This allows us to reserve space.
796 if (Record.size() < 1)
797 return Error("Invalid TYPE_CODE_NUMENTRY record");
798 TypeList.resize(Record[0]);
800 case bitc::TYPE_CODE_VOID: // VOID
801 ResultTy = Type::getVoidTy(Context);
803 case bitc::TYPE_CODE_FLOAT: // FLOAT
804 ResultTy = Type::getFloatTy(Context);
806 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
807 ResultTy = Type::getDoubleTy(Context);
809 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
810 ResultTy = Type::getX86_FP80Ty(Context);
812 case bitc::TYPE_CODE_FP128: // FP128
813 ResultTy = Type::getFP128Ty(Context);
815 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
816 ResultTy = Type::getPPC_FP128Ty(Context);
818 case bitc::TYPE_CODE_LABEL: // LABEL
819 ResultTy = Type::getLabelTy(Context);
821 case bitc::TYPE_CODE_METADATA: // METADATA
822 ResultTy = Type::getMetadataTy(Context);
824 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
825 ResultTy = Type::getX86_MMXTy(Context);
827 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
828 if (Record.size() < 1)
829 return Error("Invalid Integer type record");
830 ResultTy = IntegerType::get(Context, Record[0]);
832 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
833 if (NextTypeID < TypeList.size() && TypeList[NextTypeID] == 0)
834 ResultTy = StructType::createNamed(Context, "");
836 case bitc::TYPE_CODE_STRUCT_OLD: {// STRUCT_OLD
837 if (NextTypeID >= TypeList.size()) break;
838 // If we already read it, don't reprocess.
839 if (TypeList[NextTypeID] &&
840 !cast<StructType>(TypeList[NextTypeID])->isOpaque())
844 if (TypeList[NextTypeID] == 0)
845 TypeList[NextTypeID] = StructType::createNamed(Context, "");
847 std::vector<Type*> EltTys;
848 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
849 if (Type *Elt = getTypeByIDOrNull(Record[i]))
850 EltTys.push_back(Elt);
855 if (EltTys.size() != Record.size()-1)
856 break; // Not all elements are ready.
858 cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]);
859 ResultTy = TypeList[NextTypeID];
860 TypeList[NextTypeID] = 0;
863 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
864 // [pointee type, address space]
865 if (Record.size() < 1)
866 return Error("Invalid POINTER type record");
867 unsigned AddressSpace = 0;
868 if (Record.size() == 2)
869 AddressSpace = Record[1];
870 if ((ResultTy = getTypeByIDOrNull(Record[0])))
871 ResultTy = PointerType::get(ResultTy, AddressSpace);
874 case bitc::TYPE_CODE_FUNCTION: {
875 // FIXME: attrid is dead, remove it in LLVM 3.0
876 // FUNCTION: [vararg, attrid, retty, paramty x N]
877 if (Record.size() < 3)
878 return Error("Invalid FUNCTION type record");
879 std::vector<Type*> ArgTys;
880 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
881 if (Type *Elt = getTypeByIDOrNull(Record[i]))
882 ArgTys.push_back(Elt);
886 if (ArgTys.size()+3 != Record.size())
887 break; // Something was null.
888 if ((ResultTy = getTypeByIDOrNull(Record[2])))
889 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
892 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
893 if (Record.size() < 2)
894 return Error("Invalid ARRAY type record");
895 if ((ResultTy = getTypeByIDOrNull(Record[1])))
896 ResultTy = ArrayType::get(ResultTy, Record[0]);
898 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
899 if (Record.size() < 2)
900 return Error("Invalid VECTOR type record");
901 if ((ResultTy = getTypeByIDOrNull(Record[1])))
902 ResultTy = VectorType::get(ResultTy, Record[0]);
906 if (NextTypeID >= TypeList.size())
907 return Error("invalid TYPE table");
909 if (ResultTy && TypeList[NextTypeID] == 0) {
913 TypeList[NextTypeID] = ResultTy;
921 bool BitcodeReader::ParseOldTypeSymbolTable() {
922 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID_OLD))
923 return Error("Malformed block record");
925 SmallVector<uint64_t, 64> Record;
927 // Read all the records for this type table.
928 std::string TypeName;
930 unsigned Code = Stream.ReadCode();
931 if (Code == bitc::END_BLOCK) {
932 if (Stream.ReadBlockEnd())
933 return Error("Error at end of type symbol table block");
937 if (Code == bitc::ENTER_SUBBLOCK) {
938 // No known subblocks, always skip them.
939 Stream.ReadSubBlockID();
940 if (Stream.SkipBlock())
941 return Error("Malformed block record");
945 if (Code == bitc::DEFINE_ABBREV) {
946 Stream.ReadAbbrevRecord();
952 switch (Stream.ReadRecord(Code, Record)) {
953 default: // Default behavior: unknown type.
955 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
956 if (ConvertToString(Record, 1, TypeName))
957 return Error("Invalid TST_ENTRY record");
958 unsigned TypeID = Record[0];
959 if (TypeID >= TypeList.size())
960 return Error("Invalid Type ID in TST_ENTRY record");
962 // Only apply the type name to a struct type with no name.
963 if (StructType *STy = dyn_cast<StructType>(TypeList[TypeID]))
964 if (!STy->isAnonymous() && !STy->hasName())
965 STy->setName(TypeName);
972 bool BitcodeReader::ParseValueSymbolTable() {
973 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
974 return Error("Malformed block record");
976 SmallVector<uint64_t, 64> Record;
978 // Read all the records for this value table.
979 SmallString<128> ValueName;
981 unsigned Code = Stream.ReadCode();
982 if (Code == bitc::END_BLOCK) {
983 if (Stream.ReadBlockEnd())
984 return Error("Error at end of value symbol table block");
987 if (Code == bitc::ENTER_SUBBLOCK) {
988 // No known subblocks, always skip them.
989 Stream.ReadSubBlockID();
990 if (Stream.SkipBlock())
991 return Error("Malformed block record");
995 if (Code == bitc::DEFINE_ABBREV) {
996 Stream.ReadAbbrevRecord();
1002 switch (Stream.ReadRecord(Code, Record)) {
1003 default: // Default behavior: unknown type.
1005 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1006 if (ConvertToString(Record, 1, ValueName))
1007 return Error("Invalid VST_ENTRY record");
1008 unsigned ValueID = Record[0];
1009 if (ValueID >= ValueList.size())
1010 return Error("Invalid Value ID in VST_ENTRY record");
1011 Value *V = ValueList[ValueID];
1013 V->setName(StringRef(ValueName.data(), ValueName.size()));
1017 case bitc::VST_CODE_BBENTRY: {
1018 if (ConvertToString(Record, 1, ValueName))
1019 return Error("Invalid VST_BBENTRY record");
1020 BasicBlock *BB = getBasicBlock(Record[0]);
1022 return Error("Invalid BB ID in VST_BBENTRY record");
1024 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1032 bool BitcodeReader::ParseMetadata() {
1033 unsigned NextMDValueNo = MDValueList.size();
1035 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1036 return Error("Malformed block record");
1038 SmallVector<uint64_t, 64> Record;
1040 // Read all the records.
1042 unsigned Code = Stream.ReadCode();
1043 if (Code == bitc::END_BLOCK) {
1044 if (Stream.ReadBlockEnd())
1045 return Error("Error at end of PARAMATTR block");
1049 if (Code == bitc::ENTER_SUBBLOCK) {
1050 // No known subblocks, always skip them.
1051 Stream.ReadSubBlockID();
1052 if (Stream.SkipBlock())
1053 return Error("Malformed block record");
1057 if (Code == bitc::DEFINE_ABBREV) {
1058 Stream.ReadAbbrevRecord();
1062 bool IsFunctionLocal = false;
1065 Code = Stream.ReadRecord(Code, Record);
1067 default: // Default behavior: ignore.
1069 case bitc::METADATA_NAME: {
1070 // Read named of the named metadata.
1071 unsigned NameLength = Record.size();
1072 SmallString<8> Name;
1073 Name.resize(NameLength);
1074 for (unsigned i = 0; i != NameLength; ++i)
1075 Name[i] = Record[i];
1077 Code = Stream.ReadCode();
1079 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1080 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
1081 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1083 // Read named metadata elements.
1084 unsigned Size = Record.size();
1085 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1086 for (unsigned i = 0; i != Size; ++i) {
1087 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1089 return Error("Malformed metadata record");
1090 NMD->addOperand(MD);
1094 case bitc::METADATA_FN_NODE:
1095 IsFunctionLocal = true;
1097 case bitc::METADATA_NODE: {
1098 if (Record.size() % 2 == 1)
1099 return Error("Invalid METADATA_NODE record");
1101 unsigned Size = Record.size();
1102 SmallVector<Value*, 8> Elts;
1103 for (unsigned i = 0; i != Size; i += 2) {
1104 Type *Ty = getTypeByID(Record[i]);
1105 if (!Ty) return Error("Invalid METADATA_NODE record");
1106 if (Ty->isMetadataTy())
1107 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1108 else if (!Ty->isVoidTy())
1109 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1111 Elts.push_back(NULL);
1113 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1114 IsFunctionLocal = false;
1115 MDValueList.AssignValue(V, NextMDValueNo++);
1118 case bitc::METADATA_STRING: {
1119 unsigned MDStringLength = Record.size();
1120 SmallString<8> String;
1121 String.resize(MDStringLength);
1122 for (unsigned i = 0; i != MDStringLength; ++i)
1123 String[i] = Record[i];
1124 Value *V = MDString::get(Context,
1125 StringRef(String.data(), String.size()));
1126 MDValueList.AssignValue(V, NextMDValueNo++);
1129 case bitc::METADATA_KIND: {
1130 unsigned RecordLength = Record.size();
1131 if (Record.empty() || RecordLength < 2)
1132 return Error("Invalid METADATA_KIND record");
1133 SmallString<8> Name;
1134 Name.resize(RecordLength-1);
1135 unsigned Kind = Record[0];
1136 for (unsigned i = 1; i != RecordLength; ++i)
1137 Name[i-1] = Record[i];
1139 unsigned NewKind = TheModule->getMDKindID(Name.str());
1140 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1141 return Error("Conflicting METADATA_KIND records");
1148 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
1149 /// the LSB for dense VBR encoding.
1150 static uint64_t DecodeSignRotatedValue(uint64_t V) {
1155 // There is no such thing as -0 with integers. "-0" really means MININT.
1159 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1160 /// values and aliases that we can.
1161 bool BitcodeReader::ResolveGlobalAndAliasInits() {
1162 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1163 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1165 GlobalInitWorklist.swap(GlobalInits);
1166 AliasInitWorklist.swap(AliasInits);
1168 while (!GlobalInitWorklist.empty()) {
1169 unsigned ValID = GlobalInitWorklist.back().second;
1170 if (ValID >= ValueList.size()) {
1171 // Not ready to resolve this yet, it requires something later in the file.
1172 GlobalInits.push_back(GlobalInitWorklist.back());
1174 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1175 GlobalInitWorklist.back().first->setInitializer(C);
1177 return Error("Global variable initializer is not a constant!");
1179 GlobalInitWorklist.pop_back();
1182 while (!AliasInitWorklist.empty()) {
1183 unsigned ValID = AliasInitWorklist.back().second;
1184 if (ValID >= ValueList.size()) {
1185 AliasInits.push_back(AliasInitWorklist.back());
1187 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1188 AliasInitWorklist.back().first->setAliasee(C);
1190 return Error("Alias initializer is not a constant!");
1192 AliasInitWorklist.pop_back();
1197 bool BitcodeReader::ParseConstants() {
1198 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1199 return Error("Malformed block record");
1201 SmallVector<uint64_t, 64> Record;
1203 // Read all the records for this value table.
1204 Type *CurTy = Type::getInt32Ty(Context);
1205 unsigned NextCstNo = ValueList.size();
1207 unsigned Code = Stream.ReadCode();
1208 if (Code == bitc::END_BLOCK)
1211 if (Code == bitc::ENTER_SUBBLOCK) {
1212 // No known subblocks, always skip them.
1213 Stream.ReadSubBlockID();
1214 if (Stream.SkipBlock())
1215 return Error("Malformed block record");
1219 if (Code == bitc::DEFINE_ABBREV) {
1220 Stream.ReadAbbrevRecord();
1227 unsigned BitCode = Stream.ReadRecord(Code, Record);
1229 default: // Default behavior: unknown constant
1230 case bitc::CST_CODE_UNDEF: // UNDEF
1231 V = UndefValue::get(CurTy);
1233 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1235 return Error("Malformed CST_SETTYPE record");
1236 if (Record[0] >= TypeList.size())
1237 return Error("Invalid Type ID in CST_SETTYPE record");
1238 CurTy = TypeList[Record[0]];
1239 continue; // Skip the ValueList manipulation.
1240 case bitc::CST_CODE_NULL: // NULL
1241 V = Constant::getNullValue(CurTy);
1243 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1244 if (!CurTy->isIntegerTy() || Record.empty())
1245 return Error("Invalid CST_INTEGER record");
1246 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
1248 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1249 if (!CurTy->isIntegerTy() || Record.empty())
1250 return Error("Invalid WIDE_INTEGER record");
1252 unsigned NumWords = Record.size();
1253 SmallVector<uint64_t, 8> Words;
1254 Words.resize(NumWords);
1255 for (unsigned i = 0; i != NumWords; ++i)
1256 Words[i] = DecodeSignRotatedValue(Record[i]);
1257 V = ConstantInt::get(Context,
1258 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
1262 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1264 return Error("Invalid FLOAT record");
1265 if (CurTy->isFloatTy())
1266 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1267 else if (CurTy->isDoubleTy())
1268 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1269 else if (CurTy->isX86_FP80Ty()) {
1270 // Bits are not stored the same way as a normal i80 APInt, compensate.
1271 uint64_t Rearrange[2];
1272 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1273 Rearrange[1] = Record[0] >> 48;
1274 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1275 } else if (CurTy->isFP128Ty())
1276 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1277 else if (CurTy->isPPC_FP128Ty())
1278 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1280 V = UndefValue::get(CurTy);
1284 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1286 return Error("Invalid CST_AGGREGATE record");
1288 unsigned Size = Record.size();
1289 std::vector<Constant*> Elts;
1291 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1292 for (unsigned i = 0; i != Size; ++i)
1293 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1294 STy->getElementType(i)));
1295 V = ConstantStruct::get(STy, Elts);
1296 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1297 Type *EltTy = ATy->getElementType();
1298 for (unsigned i = 0; i != Size; ++i)
1299 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1300 V = ConstantArray::get(ATy, Elts);
1301 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1302 Type *EltTy = VTy->getElementType();
1303 for (unsigned i = 0; i != Size; ++i)
1304 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1305 V = ConstantVector::get(Elts);
1307 V = UndefValue::get(CurTy);
1311 case bitc::CST_CODE_STRING: { // STRING: [values]
1313 return Error("Invalid CST_AGGREGATE record");
1315 ArrayType *ATy = cast<ArrayType>(CurTy);
1316 Type *EltTy = ATy->getElementType();
1318 unsigned Size = Record.size();
1319 std::vector<Constant*> Elts;
1320 for (unsigned i = 0; i != Size; ++i)
1321 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1322 V = ConstantArray::get(ATy, Elts);
1325 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1327 return Error("Invalid CST_AGGREGATE record");
1329 ArrayType *ATy = cast<ArrayType>(CurTy);
1330 Type *EltTy = ATy->getElementType();
1332 unsigned Size = Record.size();
1333 std::vector<Constant*> Elts;
1334 for (unsigned i = 0; i != Size; ++i)
1335 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1336 Elts.push_back(Constant::getNullValue(EltTy));
1337 V = ConstantArray::get(ATy, Elts);
1340 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1341 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1342 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1344 V = UndefValue::get(CurTy); // Unknown binop.
1346 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1347 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1349 if (Record.size() >= 4) {
1350 if (Opc == Instruction::Add ||
1351 Opc == Instruction::Sub ||
1352 Opc == Instruction::Mul ||
1353 Opc == Instruction::Shl) {
1354 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1355 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1356 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1357 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1358 } else if (Opc == Instruction::SDiv ||
1359 Opc == Instruction::UDiv ||
1360 Opc == Instruction::LShr ||
1361 Opc == Instruction::AShr) {
1362 if (Record[3] & (1 << bitc::PEO_EXACT))
1363 Flags |= SDivOperator::IsExact;
1366 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1370 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1371 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1372 int Opc = GetDecodedCastOpcode(Record[0]);
1374 V = UndefValue::get(CurTy); // Unknown cast.
1376 Type *OpTy = getTypeByID(Record[1]);
1377 if (!OpTy) return Error("Invalid CE_CAST record");
1378 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1379 V = ConstantExpr::getCast(Opc, Op, CurTy);
1383 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1384 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1385 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1386 SmallVector<Constant*, 16> Elts;
1387 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1388 Type *ElTy = getTypeByID(Record[i]);
1389 if (!ElTy) return Error("Invalid CE_GEP record");
1390 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1392 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1393 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1395 bitc::CST_CODE_CE_INBOUNDS_GEP);
1398 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1399 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1400 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1401 Type::getInt1Ty(Context)),
1402 ValueList.getConstantFwdRef(Record[1],CurTy),
1403 ValueList.getConstantFwdRef(Record[2],CurTy));
1405 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1406 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1408 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1409 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1410 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1411 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1412 V = ConstantExpr::getExtractElement(Op0, Op1);
1415 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1416 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1417 if (Record.size() < 3 || OpTy == 0)
1418 return Error("Invalid CE_INSERTELT record");
1419 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1420 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1421 OpTy->getElementType());
1422 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1423 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1426 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1427 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1428 if (Record.size() < 3 || OpTy == 0)
1429 return Error("Invalid CE_SHUFFLEVEC record");
1430 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1431 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1432 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1433 OpTy->getNumElements());
1434 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1435 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1438 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1439 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1441 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1442 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1443 return Error("Invalid CE_SHUFVEC_EX record");
1444 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1445 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1446 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1447 RTy->getNumElements());
1448 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1449 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1452 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1453 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1454 Type *OpTy = getTypeByID(Record[0]);
1455 if (OpTy == 0) return Error("Invalid CE_CMP record");
1456 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1457 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1459 if (OpTy->isFPOrFPVectorTy())
1460 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1462 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1465 case bitc::CST_CODE_INLINEASM: {
1466 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1467 std::string AsmStr, ConstrStr;
1468 bool HasSideEffects = Record[0] & 1;
1469 bool IsAlignStack = Record[0] >> 1;
1470 unsigned AsmStrSize = Record[1];
1471 if (2+AsmStrSize >= Record.size())
1472 return Error("Invalid INLINEASM record");
1473 unsigned ConstStrSize = Record[2+AsmStrSize];
1474 if (3+AsmStrSize+ConstStrSize > Record.size())
1475 return Error("Invalid INLINEASM record");
1477 for (unsigned i = 0; i != AsmStrSize; ++i)
1478 AsmStr += (char)Record[2+i];
1479 for (unsigned i = 0; i != ConstStrSize; ++i)
1480 ConstrStr += (char)Record[3+AsmStrSize+i];
1481 PointerType *PTy = cast<PointerType>(CurTy);
1482 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1483 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1486 case bitc::CST_CODE_BLOCKADDRESS:{
1487 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1488 Type *FnTy = getTypeByID(Record[0]);
1489 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1491 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1492 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1494 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1495 Type::getInt8Ty(Context),
1496 false, GlobalValue::InternalLinkage,
1498 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1504 ValueList.AssignValue(V, NextCstNo);
1508 if (NextCstNo != ValueList.size())
1509 return Error("Invalid constant reference!");
1511 if (Stream.ReadBlockEnd())
1512 return Error("Error at end of constants block");
1514 // Once all the constants have been read, go through and resolve forward
1516 ValueList.ResolveConstantForwardRefs();
1520 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1521 /// remember where it is and then skip it. This lets us lazily deserialize the
1523 bool BitcodeReader::RememberAndSkipFunctionBody() {
1524 // Get the function we are talking about.
1525 if (FunctionsWithBodies.empty())
1526 return Error("Insufficient function protos");
1528 Function *Fn = FunctionsWithBodies.back();
1529 FunctionsWithBodies.pop_back();
1531 // Save the current stream state.
1532 uint64_t CurBit = Stream.GetCurrentBitNo();
1533 DeferredFunctionInfo[Fn] = CurBit;
1535 // Skip over the function block for now.
1536 if (Stream.SkipBlock())
1537 return Error("Malformed block record");
1541 bool BitcodeReader::ParseModule() {
1542 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1543 return Error("Malformed block record");
1545 SmallVector<uint64_t, 64> Record;
1546 std::vector<std::string> SectionTable;
1547 std::vector<std::string> GCTable;
1549 // Read all the records for this module.
1550 while (!Stream.AtEndOfStream()) {
1551 unsigned Code = Stream.ReadCode();
1552 if (Code == bitc::END_BLOCK) {
1553 if (Stream.ReadBlockEnd())
1554 return Error("Error at end of module block");
1556 // Patch the initializers for globals and aliases up.
1557 ResolveGlobalAndAliasInits();
1558 if (!GlobalInits.empty() || !AliasInits.empty())
1559 return Error("Malformed global initializer set");
1560 if (!FunctionsWithBodies.empty())
1561 return Error("Too few function bodies found");
1563 // Look for intrinsic functions which need to be upgraded at some point
1564 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1567 if (UpgradeIntrinsicFunction(FI, NewFn))
1568 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1571 // Look for global variables which need to be renamed.
1572 for (Module::global_iterator
1573 GI = TheModule->global_begin(), GE = TheModule->global_end();
1575 UpgradeGlobalVariable(GI);
1577 // Force deallocation of memory for these vectors to favor the client that
1578 // want lazy deserialization.
1579 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1580 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1581 std::vector<Function*>().swap(FunctionsWithBodies);
1585 if (Code == bitc::ENTER_SUBBLOCK) {
1586 switch (Stream.ReadSubBlockID()) {
1587 default: // Skip unknown content.
1588 if (Stream.SkipBlock())
1589 return Error("Malformed block record");
1591 case bitc::BLOCKINFO_BLOCK_ID:
1592 if (Stream.ReadBlockInfoBlock())
1593 return Error("Malformed BlockInfoBlock");
1595 case bitc::PARAMATTR_BLOCK_ID:
1596 if (ParseAttributeBlock())
1599 case bitc::TYPE_BLOCK_ID_NEW:
1600 if (ParseTypeTable())
1603 case bitc::TYPE_BLOCK_ID_OLD:
1604 if (ParseOldTypeTable())
1607 case bitc::TYPE_SYMTAB_BLOCK_ID_OLD:
1608 if (ParseOldTypeSymbolTable())
1611 case bitc::VALUE_SYMTAB_BLOCK_ID:
1612 if (ParseValueSymbolTable())
1615 case bitc::CONSTANTS_BLOCK_ID:
1616 if (ParseConstants() || ResolveGlobalAndAliasInits())
1619 case bitc::METADATA_BLOCK_ID:
1620 if (ParseMetadata())
1623 case bitc::FUNCTION_BLOCK_ID:
1624 // If this is the first function body we've seen, reverse the
1625 // FunctionsWithBodies list.
1626 if (!HasReversedFunctionsWithBodies) {
1627 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1628 HasReversedFunctionsWithBodies = true;
1631 if (RememberAndSkipFunctionBody())
1638 if (Code == bitc::DEFINE_ABBREV) {
1639 Stream.ReadAbbrevRecord();
1644 switch (Stream.ReadRecord(Code, Record)) {
1645 default: break; // Default behavior, ignore unknown content.
1646 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1647 if (Record.size() < 1)
1648 return Error("Malformed MODULE_CODE_VERSION");
1649 // Only version #0 is supported so far.
1651 return Error("Unknown bitstream version!");
1653 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1655 if (ConvertToString(Record, 0, S))
1656 return Error("Invalid MODULE_CODE_TRIPLE record");
1657 TheModule->setTargetTriple(S);
1660 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1662 if (ConvertToString(Record, 0, S))
1663 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1664 TheModule->setDataLayout(S);
1667 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1669 if (ConvertToString(Record, 0, S))
1670 return Error("Invalid MODULE_CODE_ASM record");
1671 TheModule->setModuleInlineAsm(S);
1674 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1676 if (ConvertToString(Record, 0, S))
1677 return Error("Invalid MODULE_CODE_DEPLIB record");
1678 TheModule->addLibrary(S);
1681 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1683 if (ConvertToString(Record, 0, S))
1684 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1685 SectionTable.push_back(S);
1688 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1690 if (ConvertToString(Record, 0, S))
1691 return Error("Invalid MODULE_CODE_GCNAME record");
1692 GCTable.push_back(S);
1695 // GLOBALVAR: [pointer type, isconst, initid,
1696 // linkage, alignment, section, visibility, threadlocal,
1698 case bitc::MODULE_CODE_GLOBALVAR: {
1699 if (Record.size() < 6)
1700 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1701 Type *Ty = getTypeByID(Record[0]);
1702 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1703 if (!Ty->isPointerTy())
1704 return Error("Global not a pointer type!");
1705 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1706 Ty = cast<PointerType>(Ty)->getElementType();
1708 bool isConstant = Record[1];
1709 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1710 unsigned Alignment = (1 << Record[4]) >> 1;
1711 std::string Section;
1713 if (Record[5]-1 >= SectionTable.size())
1714 return Error("Invalid section ID");
1715 Section = SectionTable[Record[5]-1];
1717 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1718 if (Record.size() > 6)
1719 Visibility = GetDecodedVisibility(Record[6]);
1720 bool isThreadLocal = false;
1721 if (Record.size() > 7)
1722 isThreadLocal = Record[7];
1724 bool UnnamedAddr = false;
1725 if (Record.size() > 8)
1726 UnnamedAddr = Record[8];
1728 GlobalVariable *NewGV =
1729 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1730 isThreadLocal, AddressSpace);
1731 NewGV->setAlignment(Alignment);
1732 if (!Section.empty())
1733 NewGV->setSection(Section);
1734 NewGV->setVisibility(Visibility);
1735 NewGV->setThreadLocal(isThreadLocal);
1736 NewGV->setUnnamedAddr(UnnamedAddr);
1738 ValueList.push_back(NewGV);
1740 // Remember which value to use for the global initializer.
1741 if (unsigned InitID = Record[2])
1742 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1745 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1746 // alignment, section, visibility, gc, unnamed_addr]
1747 case bitc::MODULE_CODE_FUNCTION: {
1748 if (Record.size() < 8)
1749 return Error("Invalid MODULE_CODE_FUNCTION record");
1750 Type *Ty = getTypeByID(Record[0]);
1751 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1752 if (!Ty->isPointerTy())
1753 return Error("Function not a pointer type!");
1755 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1757 return Error("Function not a pointer to function type!");
1759 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1762 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1763 bool isProto = Record[2];
1764 Func->setLinkage(GetDecodedLinkage(Record[3]));
1765 Func->setAttributes(getAttributes(Record[4]));
1767 Func->setAlignment((1 << Record[5]) >> 1);
1769 if (Record[6]-1 >= SectionTable.size())
1770 return Error("Invalid section ID");
1771 Func->setSection(SectionTable[Record[6]-1]);
1773 Func->setVisibility(GetDecodedVisibility(Record[7]));
1774 if (Record.size() > 8 && Record[8]) {
1775 if (Record[8]-1 > GCTable.size())
1776 return Error("Invalid GC ID");
1777 Func->setGC(GCTable[Record[8]-1].c_str());
1779 bool UnnamedAddr = false;
1780 if (Record.size() > 9)
1781 UnnamedAddr = Record[9];
1782 Func->setUnnamedAddr(UnnamedAddr);
1783 ValueList.push_back(Func);
1785 // If this is a function with a body, remember the prototype we are
1786 // creating now, so that we can match up the body with them later.
1788 FunctionsWithBodies.push_back(Func);
1791 // ALIAS: [alias type, aliasee val#, linkage]
1792 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1793 case bitc::MODULE_CODE_ALIAS: {
1794 if (Record.size() < 3)
1795 return Error("Invalid MODULE_ALIAS record");
1796 Type *Ty = getTypeByID(Record[0]);
1797 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1798 if (!Ty->isPointerTy())
1799 return Error("Function not a pointer type!");
1801 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1803 // Old bitcode files didn't have visibility field.
1804 if (Record.size() > 3)
1805 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1806 ValueList.push_back(NewGA);
1807 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1810 /// MODULE_CODE_PURGEVALS: [numvals]
1811 case bitc::MODULE_CODE_PURGEVALS:
1812 // Trim down the value list to the specified size.
1813 if (Record.size() < 1 || Record[0] > ValueList.size())
1814 return Error("Invalid MODULE_PURGEVALS record");
1815 ValueList.shrinkTo(Record[0]);
1821 return Error("Premature end of bitstream");
1824 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1827 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1828 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1830 if (Buffer->getBufferSize() & 3) {
1831 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1832 return Error("Invalid bitcode signature");
1834 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1837 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1838 // The magic number is 0x0B17C0DE stored in little endian.
1839 if (isBitcodeWrapper(BufPtr, BufEnd))
1840 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1841 return Error("Invalid bitcode wrapper header");
1843 StreamFile.init(BufPtr, BufEnd);
1844 Stream.init(StreamFile);
1846 // Sniff for the signature.
1847 if (Stream.Read(8) != 'B' ||
1848 Stream.Read(8) != 'C' ||
1849 Stream.Read(4) != 0x0 ||
1850 Stream.Read(4) != 0xC ||
1851 Stream.Read(4) != 0xE ||
1852 Stream.Read(4) != 0xD)
1853 return Error("Invalid bitcode signature");
1855 // We expect a number of well-defined blocks, though we don't necessarily
1856 // need to understand them all.
1857 while (!Stream.AtEndOfStream()) {
1858 unsigned Code = Stream.ReadCode();
1860 if (Code != bitc::ENTER_SUBBLOCK) {
1862 // The ranlib in xcode 4 will align archive members by appending newlines to the
1863 // end of them. If this file size is a multiple of 4 but not 8, we have to read and
1864 // ignore these final 4 bytes :-(
1865 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1866 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1867 Stream.AtEndOfStream())
1870 return Error("Invalid record at top-level");
1873 unsigned BlockID = Stream.ReadSubBlockID();
1875 // We only know the MODULE subblock ID.
1877 case bitc::BLOCKINFO_BLOCK_ID:
1878 if (Stream.ReadBlockInfoBlock())
1879 return Error("Malformed BlockInfoBlock");
1881 case bitc::MODULE_BLOCK_ID:
1882 // Reject multiple MODULE_BLOCK's in a single bitstream.
1884 return Error("Multiple MODULE_BLOCKs in same stream");
1890 if (Stream.SkipBlock())
1891 return Error("Malformed block record");
1899 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1900 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1901 return Error("Malformed block record");
1903 SmallVector<uint64_t, 64> Record;
1905 // Read all the records for this module.
1906 while (!Stream.AtEndOfStream()) {
1907 unsigned Code = Stream.ReadCode();
1908 if (Code == bitc::END_BLOCK) {
1909 if (Stream.ReadBlockEnd())
1910 return Error("Error at end of module block");
1915 if (Code == bitc::ENTER_SUBBLOCK) {
1916 switch (Stream.ReadSubBlockID()) {
1917 default: // Skip unknown content.
1918 if (Stream.SkipBlock())
1919 return Error("Malformed block record");
1925 if (Code == bitc::DEFINE_ABBREV) {
1926 Stream.ReadAbbrevRecord();
1931 switch (Stream.ReadRecord(Code, Record)) {
1932 default: break; // Default behavior, ignore unknown content.
1933 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1934 if (Record.size() < 1)
1935 return Error("Malformed MODULE_CODE_VERSION");
1936 // Only version #0 is supported so far.
1938 return Error("Unknown bitstream version!");
1940 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1942 if (ConvertToString(Record, 0, S))
1943 return Error("Invalid MODULE_CODE_TRIPLE record");
1951 return Error("Premature end of bitstream");
1954 bool BitcodeReader::ParseTriple(std::string &Triple) {
1955 if (Buffer->getBufferSize() & 3)
1956 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1958 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1959 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1961 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1962 // The magic number is 0x0B17C0DE stored in little endian.
1963 if (isBitcodeWrapper(BufPtr, BufEnd))
1964 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1965 return Error("Invalid bitcode wrapper header");
1967 StreamFile.init(BufPtr, BufEnd);
1968 Stream.init(StreamFile);
1970 // Sniff for the signature.
1971 if (Stream.Read(8) != 'B' ||
1972 Stream.Read(8) != 'C' ||
1973 Stream.Read(4) != 0x0 ||
1974 Stream.Read(4) != 0xC ||
1975 Stream.Read(4) != 0xE ||
1976 Stream.Read(4) != 0xD)
1977 return Error("Invalid bitcode signature");
1979 // We expect a number of well-defined blocks, though we don't necessarily
1980 // need to understand them all.
1981 while (!Stream.AtEndOfStream()) {
1982 unsigned Code = Stream.ReadCode();
1984 if (Code != bitc::ENTER_SUBBLOCK)
1985 return Error("Invalid record at top-level");
1987 unsigned BlockID = Stream.ReadSubBlockID();
1989 // We only know the MODULE subblock ID.
1991 case bitc::MODULE_BLOCK_ID:
1992 if (ParseModuleTriple(Triple))
1996 if (Stream.SkipBlock())
1997 return Error("Malformed block record");
2005 /// ParseMetadataAttachment - Parse metadata attachments.
2006 bool BitcodeReader::ParseMetadataAttachment() {
2007 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2008 return Error("Malformed block record");
2010 SmallVector<uint64_t, 64> Record;
2012 unsigned Code = Stream.ReadCode();
2013 if (Code == bitc::END_BLOCK) {
2014 if (Stream.ReadBlockEnd())
2015 return Error("Error at end of PARAMATTR block");
2018 if (Code == bitc::DEFINE_ABBREV) {
2019 Stream.ReadAbbrevRecord();
2022 // Read a metadata attachment record.
2024 switch (Stream.ReadRecord(Code, Record)) {
2025 default: // Default behavior: ignore.
2027 case bitc::METADATA_ATTACHMENT: {
2028 unsigned RecordLength = Record.size();
2029 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2030 return Error ("Invalid METADATA_ATTACHMENT reader!");
2031 Instruction *Inst = InstructionList[Record[0]];
2032 for (unsigned i = 1; i != RecordLength; i = i+2) {
2033 unsigned Kind = Record[i];
2034 DenseMap<unsigned, unsigned>::iterator I =
2035 MDKindMap.find(Kind);
2036 if (I == MDKindMap.end())
2037 return Error("Invalid metadata kind ID");
2038 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2039 Inst->setMetadata(I->second, cast<MDNode>(Node));
2048 /// ParseFunctionBody - Lazily parse the specified function body block.
2049 bool BitcodeReader::ParseFunctionBody(Function *F) {
2050 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2051 return Error("Malformed block record");
2053 InstructionList.clear();
2054 unsigned ModuleValueListSize = ValueList.size();
2055 unsigned ModuleMDValueListSize = MDValueList.size();
2057 // Add all the function arguments to the value table.
2058 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2059 ValueList.push_back(I);
2061 unsigned NextValueNo = ValueList.size();
2062 BasicBlock *CurBB = 0;
2063 unsigned CurBBNo = 0;
2067 // Read all the records.
2068 SmallVector<uint64_t, 64> Record;
2070 unsigned Code = Stream.ReadCode();
2071 if (Code == bitc::END_BLOCK) {
2072 if (Stream.ReadBlockEnd())
2073 return Error("Error at end of function block");
2077 if (Code == bitc::ENTER_SUBBLOCK) {
2078 switch (Stream.ReadSubBlockID()) {
2079 default: // Skip unknown content.
2080 if (Stream.SkipBlock())
2081 return Error("Malformed block record");
2083 case bitc::CONSTANTS_BLOCK_ID:
2084 if (ParseConstants()) return true;
2085 NextValueNo = ValueList.size();
2087 case bitc::VALUE_SYMTAB_BLOCK_ID:
2088 if (ParseValueSymbolTable()) return true;
2090 case bitc::METADATA_ATTACHMENT_ID:
2091 if (ParseMetadataAttachment()) return true;
2093 case bitc::METADATA_BLOCK_ID:
2094 if (ParseMetadata()) return true;
2100 if (Code == bitc::DEFINE_ABBREV) {
2101 Stream.ReadAbbrevRecord();
2108 unsigned BitCode = Stream.ReadRecord(Code, Record);
2110 default: // Default behavior: reject
2111 return Error("Unknown instruction");
2112 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2113 if (Record.size() < 1 || Record[0] == 0)
2114 return Error("Invalid DECLAREBLOCKS record");
2115 // Create all the basic blocks for the function.
2116 FunctionBBs.resize(Record[0]);
2117 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2118 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2119 CurBB = FunctionBBs[0];
2122 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2123 // This record indicates that the last instruction is at the same
2124 // location as the previous instruction with a location.
2127 // Get the last instruction emitted.
2128 if (CurBB && !CurBB->empty())
2130 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2131 !FunctionBBs[CurBBNo-1]->empty())
2132 I = &FunctionBBs[CurBBNo-1]->back();
2134 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2135 I->setDebugLoc(LastLoc);
2139 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2140 I = 0; // Get the last instruction emitted.
2141 if (CurBB && !CurBB->empty())
2143 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2144 !FunctionBBs[CurBBNo-1]->empty())
2145 I = &FunctionBBs[CurBBNo-1]->back();
2146 if (I == 0 || Record.size() < 4)
2147 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2149 unsigned Line = Record[0], Col = Record[1];
2150 unsigned ScopeID = Record[2], IAID = Record[3];
2152 MDNode *Scope = 0, *IA = 0;
2153 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2154 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2155 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2156 I->setDebugLoc(LastLoc);
2161 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2164 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2165 getValue(Record, OpNum, LHS->getType(), RHS) ||
2166 OpNum+1 > Record.size())
2167 return Error("Invalid BINOP record");
2169 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2170 if (Opc == -1) return Error("Invalid BINOP record");
2171 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2172 InstructionList.push_back(I);
2173 if (OpNum < Record.size()) {
2174 if (Opc == Instruction::Add ||
2175 Opc == Instruction::Sub ||
2176 Opc == Instruction::Mul ||
2177 Opc == Instruction::Shl) {
2178 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2179 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2180 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2181 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2182 } else if (Opc == Instruction::SDiv ||
2183 Opc == Instruction::UDiv ||
2184 Opc == Instruction::LShr ||
2185 Opc == Instruction::AShr) {
2186 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2187 cast<BinaryOperator>(I)->setIsExact(true);
2192 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2195 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2196 OpNum+2 != Record.size())
2197 return Error("Invalid CAST record");
2199 Type *ResTy = getTypeByID(Record[OpNum]);
2200 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2201 if (Opc == -1 || ResTy == 0)
2202 return Error("Invalid CAST record");
2203 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2204 InstructionList.push_back(I);
2207 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2208 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2211 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2212 return Error("Invalid GEP record");
2214 SmallVector<Value*, 16> GEPIdx;
2215 while (OpNum != Record.size()) {
2217 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2218 return Error("Invalid GEP record");
2219 GEPIdx.push_back(Op);
2222 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2223 InstructionList.push_back(I);
2224 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2225 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2229 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2230 // EXTRACTVAL: [opty, opval, n x indices]
2233 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2234 return Error("Invalid EXTRACTVAL record");
2236 SmallVector<unsigned, 4> EXTRACTVALIdx;
2237 for (unsigned RecSize = Record.size();
2238 OpNum != RecSize; ++OpNum) {
2239 uint64_t Index = Record[OpNum];
2240 if ((unsigned)Index != Index)
2241 return Error("Invalid EXTRACTVAL index");
2242 EXTRACTVALIdx.push_back((unsigned)Index);
2245 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2246 InstructionList.push_back(I);
2250 case bitc::FUNC_CODE_INST_INSERTVAL: {
2251 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2254 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2255 return Error("Invalid INSERTVAL record");
2257 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2258 return Error("Invalid INSERTVAL record");
2260 SmallVector<unsigned, 4> INSERTVALIdx;
2261 for (unsigned RecSize = Record.size();
2262 OpNum != RecSize; ++OpNum) {
2263 uint64_t Index = Record[OpNum];
2264 if ((unsigned)Index != Index)
2265 return Error("Invalid INSERTVAL index");
2266 INSERTVALIdx.push_back((unsigned)Index);
2269 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2270 InstructionList.push_back(I);
2274 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2275 // obsolete form of select
2276 // handles select i1 ... in old bitcode
2278 Value *TrueVal, *FalseVal, *Cond;
2279 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2280 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2281 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2282 return Error("Invalid SELECT record");
2284 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2285 InstructionList.push_back(I);
2289 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2290 // new form of select
2291 // handles select i1 or select [N x i1]
2293 Value *TrueVal, *FalseVal, *Cond;
2294 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2295 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2296 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2297 return Error("Invalid SELECT record");
2299 // select condition can be either i1 or [N x i1]
2300 if (VectorType* vector_type =
2301 dyn_cast<VectorType>(Cond->getType())) {
2303 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2304 return Error("Invalid SELECT condition type");
2307 if (Cond->getType() != Type::getInt1Ty(Context))
2308 return Error("Invalid SELECT condition type");
2311 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2312 InstructionList.push_back(I);
2316 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2319 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2320 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2321 return Error("Invalid EXTRACTELT record");
2322 I = ExtractElementInst::Create(Vec, Idx);
2323 InstructionList.push_back(I);
2327 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2329 Value *Vec, *Elt, *Idx;
2330 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2331 getValue(Record, OpNum,
2332 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2333 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2334 return Error("Invalid INSERTELT record");
2335 I = InsertElementInst::Create(Vec, Elt, Idx);
2336 InstructionList.push_back(I);
2340 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2342 Value *Vec1, *Vec2, *Mask;
2343 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2344 getValue(Record, OpNum, Vec1->getType(), Vec2))
2345 return Error("Invalid SHUFFLEVEC record");
2347 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2348 return Error("Invalid SHUFFLEVEC record");
2349 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2350 InstructionList.push_back(I);
2354 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2355 // Old form of ICmp/FCmp returning bool
2356 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2357 // both legal on vectors but had different behaviour.
2358 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2359 // FCmp/ICmp returning bool or vector of bool
2363 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2364 getValue(Record, OpNum, LHS->getType(), RHS) ||
2365 OpNum+1 != Record.size())
2366 return Error("Invalid CMP record");
2368 if (LHS->getType()->isFPOrFPVectorTy())
2369 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2371 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2372 InstructionList.push_back(I);
2376 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2378 unsigned Size = Record.size();
2380 I = ReturnInst::Create(Context);
2381 InstructionList.push_back(I);
2387 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2388 return Error("Invalid RET record");
2389 if (OpNum != Record.size())
2390 return Error("Invalid RET record");
2392 I = ReturnInst::Create(Context, Op);
2393 InstructionList.push_back(I);
2396 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2397 if (Record.size() != 1 && Record.size() != 3)
2398 return Error("Invalid BR record");
2399 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2401 return Error("Invalid BR record");
2403 if (Record.size() == 1) {
2404 I = BranchInst::Create(TrueDest);
2405 InstructionList.push_back(I);
2408 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2409 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2410 if (FalseDest == 0 || Cond == 0)
2411 return Error("Invalid BR record");
2412 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2413 InstructionList.push_back(I);
2417 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2418 if (Record.size() < 3 || (Record.size() & 1) == 0)
2419 return Error("Invalid SWITCH record");
2420 Type *OpTy = getTypeByID(Record[0]);
2421 Value *Cond = getFnValueByID(Record[1], OpTy);
2422 BasicBlock *Default = getBasicBlock(Record[2]);
2423 if (OpTy == 0 || Cond == 0 || Default == 0)
2424 return Error("Invalid SWITCH record");
2425 unsigned NumCases = (Record.size()-3)/2;
2426 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2427 InstructionList.push_back(SI);
2428 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2429 ConstantInt *CaseVal =
2430 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2431 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2432 if (CaseVal == 0 || DestBB == 0) {
2434 return Error("Invalid SWITCH record!");
2436 SI->addCase(CaseVal, DestBB);
2441 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2442 if (Record.size() < 2)
2443 return Error("Invalid INDIRECTBR record");
2444 Type *OpTy = getTypeByID(Record[0]);
2445 Value *Address = getFnValueByID(Record[1], OpTy);
2446 if (OpTy == 0 || Address == 0)
2447 return Error("Invalid INDIRECTBR record");
2448 unsigned NumDests = Record.size()-2;
2449 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2450 InstructionList.push_back(IBI);
2451 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2452 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2453 IBI->addDestination(DestBB);
2456 return Error("Invalid INDIRECTBR record!");
2463 case bitc::FUNC_CODE_INST_INVOKE: {
2464 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2465 if (Record.size() < 4) return Error("Invalid INVOKE record");
2466 AttrListPtr PAL = getAttributes(Record[0]);
2467 unsigned CCInfo = Record[1];
2468 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2469 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2473 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2474 return Error("Invalid INVOKE record");
2476 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2477 FunctionType *FTy = !CalleeTy ? 0 :
2478 dyn_cast<FunctionType>(CalleeTy->getElementType());
2480 // Check that the right number of fixed parameters are here.
2481 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2482 Record.size() < OpNum+FTy->getNumParams())
2483 return Error("Invalid INVOKE record");
2485 SmallVector<Value*, 16> Ops;
2486 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2487 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2488 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2491 if (!FTy->isVarArg()) {
2492 if (Record.size() != OpNum)
2493 return Error("Invalid INVOKE record");
2495 // Read type/value pairs for varargs params.
2496 while (OpNum != Record.size()) {
2498 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2499 return Error("Invalid INVOKE record");
2504 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2505 InstructionList.push_back(I);
2506 cast<InvokeInst>(I)->setCallingConv(
2507 static_cast<CallingConv::ID>(CCInfo));
2508 cast<InvokeInst>(I)->setAttributes(PAL);
2511 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2514 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2515 return Error("Invalid RESUME record");
2516 I = ResumeInst::Create(Val);
2519 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2520 I = new UnwindInst(Context);
2521 InstructionList.push_back(I);
2523 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2524 I = new UnreachableInst(Context);
2525 InstructionList.push_back(I);
2527 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2528 if (Record.size() < 1 || ((Record.size()-1)&1))
2529 return Error("Invalid PHI record");
2530 Type *Ty = getTypeByID(Record[0]);
2531 if (!Ty) return Error("Invalid PHI record");
2533 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2534 InstructionList.push_back(PN);
2536 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2537 Value *V = getFnValueByID(Record[1+i], Ty);
2538 BasicBlock *BB = getBasicBlock(Record[2+i]);
2539 if (!V || !BB) return Error("Invalid PHI record");
2540 PN->addIncoming(V, BB);
2546 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2547 if (Record.size() != 4)
2548 return Error("Invalid ALLOCA record");
2550 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2551 Type *OpTy = getTypeByID(Record[1]);
2552 Value *Size = getFnValueByID(Record[2], OpTy);
2553 unsigned Align = Record[3];
2554 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2555 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2556 InstructionList.push_back(I);
2559 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2562 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2563 OpNum+2 != Record.size())
2564 return Error("Invalid LOAD record");
2566 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2567 InstructionList.push_back(I);
2570 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2573 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2574 getValue(Record, OpNum,
2575 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2576 OpNum+2 != Record.size())
2577 return Error("Invalid STORE record");
2579 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2580 InstructionList.push_back(I);
2583 case bitc::FUNC_CODE_INST_CMPXCHG: {
2584 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2586 Value *Ptr, *Cmp, *New;
2587 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2588 getValue(Record, OpNum,
2589 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2590 getValue(Record, OpNum,
2591 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2592 OpNum+3 != Record.size())
2593 return Error("Invalid CMPXCHG record");
2594 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2595 if (Ordering == NotAtomic)
2596 return Error("Invalid CMPXCHG record");
2597 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2598 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2599 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2600 InstructionList.push_back(I);
2603 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2604 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2607 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2608 getValue(Record, OpNum,
2609 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2610 OpNum+4 != Record.size())
2611 return Error("Invalid ATOMICRMW record");
2612 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2613 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2614 Operation > AtomicRMWInst::LAST_BINOP)
2615 return Error("Invalid ATOMICRMW record");
2616 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2617 if (Ordering == NotAtomic)
2618 return Error("Invalid ATOMICRMW record");
2619 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2620 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2621 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2622 InstructionList.push_back(I);
2625 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2626 if (2 != Record.size())
2627 return Error("Invalid FENCE record");
2628 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2629 if (Ordering == NotAtomic || Ordering == Unordered ||
2630 Ordering == Monotonic)
2631 return Error("Invalid FENCE record");
2632 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2633 I = new FenceInst(Context, Ordering, SynchScope);
2634 InstructionList.push_back(I);
2637 case bitc::FUNC_CODE_INST_CALL: {
2638 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2639 if (Record.size() < 3)
2640 return Error("Invalid CALL record");
2642 AttrListPtr PAL = getAttributes(Record[0]);
2643 unsigned CCInfo = Record[1];
2647 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2648 return Error("Invalid CALL record");
2650 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2651 FunctionType *FTy = 0;
2652 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2653 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2654 return Error("Invalid CALL record");
2656 SmallVector<Value*, 16> Args;
2657 // Read the fixed params.
2658 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2659 if (FTy->getParamType(i)->isLabelTy())
2660 Args.push_back(getBasicBlock(Record[OpNum]));
2662 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2663 if (Args.back() == 0) return Error("Invalid CALL record");
2666 // Read type/value pairs for varargs params.
2667 if (!FTy->isVarArg()) {
2668 if (OpNum != Record.size())
2669 return Error("Invalid CALL record");
2671 while (OpNum != Record.size()) {
2673 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2674 return Error("Invalid CALL record");
2679 I = CallInst::Create(Callee, Args);
2680 InstructionList.push_back(I);
2681 cast<CallInst>(I)->setCallingConv(
2682 static_cast<CallingConv::ID>(CCInfo>>1));
2683 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2684 cast<CallInst>(I)->setAttributes(PAL);
2687 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2688 if (Record.size() < 3)
2689 return Error("Invalid VAARG record");
2690 Type *OpTy = getTypeByID(Record[0]);
2691 Value *Op = getFnValueByID(Record[1], OpTy);
2692 Type *ResTy = getTypeByID(Record[2]);
2693 if (!OpTy || !Op || !ResTy)
2694 return Error("Invalid VAARG record");
2695 I = new VAArgInst(Op, ResTy);
2696 InstructionList.push_back(I);
2701 // Add instruction to end of current BB. If there is no current BB, reject
2705 return Error("Invalid instruction with no BB");
2707 CurBB->getInstList().push_back(I);
2709 // If this was a terminator instruction, move to the next block.
2710 if (isa<TerminatorInst>(I)) {
2712 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2715 // Non-void values get registered in the value table for future use.
2716 if (I && !I->getType()->isVoidTy())
2717 ValueList.AssignValue(I, NextValueNo++);
2720 // Check the function list for unresolved values.
2721 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2722 if (A->getParent() == 0) {
2723 // We found at least one unresolved value. Nuke them all to avoid leaks.
2724 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2725 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2726 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2730 return Error("Never resolved value found in function!");
2734 // FIXME: Check for unresolved forward-declared metadata references
2735 // and clean up leaks.
2737 // See if anything took the address of blocks in this function. If so,
2738 // resolve them now.
2739 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2740 BlockAddrFwdRefs.find(F);
2741 if (BAFRI != BlockAddrFwdRefs.end()) {
2742 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2743 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2744 unsigned BlockIdx = RefList[i].first;
2745 if (BlockIdx >= FunctionBBs.size())
2746 return Error("Invalid blockaddress block #");
2748 GlobalVariable *FwdRef = RefList[i].second;
2749 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2750 FwdRef->eraseFromParent();
2753 BlockAddrFwdRefs.erase(BAFRI);
2756 // Trim the value list down to the size it was before we parsed this function.
2757 ValueList.shrinkTo(ModuleValueListSize);
2758 MDValueList.shrinkTo(ModuleMDValueListSize);
2759 std::vector<BasicBlock*>().swap(FunctionBBs);
2763 //===----------------------------------------------------------------------===//
2764 // GVMaterializer implementation
2765 //===----------------------------------------------------------------------===//
2768 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2769 if (const Function *F = dyn_cast<Function>(GV)) {
2770 return F->isDeclaration() &&
2771 DeferredFunctionInfo.count(const_cast<Function*>(F));
2776 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2777 Function *F = dyn_cast<Function>(GV);
2778 // If it's not a function or is already material, ignore the request.
2779 if (!F || !F->isMaterializable()) return false;
2781 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2782 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2784 // Move the bit stream to the saved position of the deferred function body.
2785 Stream.JumpToBit(DFII->second);
2787 if (ParseFunctionBody(F)) {
2788 if (ErrInfo) *ErrInfo = ErrorString;
2792 // Upgrade any old intrinsic calls in the function.
2793 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2794 E = UpgradedIntrinsics.end(); I != E; ++I) {
2795 if (I->first != I->second) {
2796 for (Value::use_iterator UI = I->first->use_begin(),
2797 UE = I->first->use_end(); UI != UE; ) {
2798 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2799 UpgradeIntrinsicCall(CI, I->second);
2807 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2808 const Function *F = dyn_cast<Function>(GV);
2809 if (!F || F->isDeclaration())
2811 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2814 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2815 Function *F = dyn_cast<Function>(GV);
2816 // If this function isn't dematerializable, this is a noop.
2817 if (!F || !isDematerializable(F))
2820 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2822 // Just forget the function body, we can remat it later.
2827 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2828 assert(M == TheModule &&
2829 "Can only Materialize the Module this BitcodeReader is attached to.");
2830 // Iterate over the module, deserializing any functions that are still on
2832 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2834 if (F->isMaterializable() &&
2835 Materialize(F, ErrInfo))
2838 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2839 // delete the old functions to clean up. We can't do this unless the entire
2840 // module is materialized because there could always be another function body
2841 // with calls to the old function.
2842 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2843 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2844 if (I->first != I->second) {
2845 for (Value::use_iterator UI = I->first->use_begin(),
2846 UE = I->first->use_end(); UI != UE; ) {
2847 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2848 UpgradeIntrinsicCall(CI, I->second);
2850 if (!I->first->use_empty())
2851 I->first->replaceAllUsesWith(I->second);
2852 I->first->eraseFromParent();
2855 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2857 // Check debug info intrinsics.
2858 CheckDebugInfoIntrinsics(TheModule);
2864 //===----------------------------------------------------------------------===//
2865 // External interface
2866 //===----------------------------------------------------------------------===//
2868 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2870 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2871 LLVMContext& Context,
2872 std::string *ErrMsg) {
2873 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2874 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2875 M->setMaterializer(R);
2876 if (R->ParseBitcodeInto(M)) {
2878 *ErrMsg = R->getErrorString();
2880 delete M; // Also deletes R.
2883 // Have the BitcodeReader dtor delete 'Buffer'.
2884 R->setBufferOwned(true);
2888 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2889 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2890 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2891 std::string *ErrMsg){
2892 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2895 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2896 // there was an error.
2897 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2899 // Read in the entire module, and destroy the BitcodeReader.
2900 if (M->MaterializeAllPermanently(ErrMsg)) {
2908 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2909 LLVMContext& Context,
2910 std::string *ErrMsg) {
2911 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2912 // Don't let the BitcodeReader dtor delete 'Buffer'.
2913 R->setBufferOwned(false);
2915 std::string Triple("");
2916 if (R->ParseTriple(Triple))
2918 *ErrMsg = R->getErrorString();