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<PATypeHolder>().swap(TypeList);
38 std::vector<AttrListPtr>().swap(MAttributes);
39 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
44 //===----------------------------------------------------------------------===//
45 // Helper functions to implement forward reference resolution, etc.
46 //===----------------------------------------------------------------------===//
48 /// ConvertToString - Convert a string from a record into an std::string, return
50 template<typename StrTy>
51 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
53 if (Idx > Record.size())
56 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
57 Result += (char)Record[i];
61 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
63 default: // Map unknown/new linkages to external
64 case 0: return GlobalValue::ExternalLinkage;
65 case 1: return GlobalValue::WeakAnyLinkage;
66 case 2: return GlobalValue::AppendingLinkage;
67 case 3: return GlobalValue::InternalLinkage;
68 case 4: return GlobalValue::LinkOnceAnyLinkage;
69 case 5: return GlobalValue::DLLImportLinkage;
70 case 6: return GlobalValue::DLLExportLinkage;
71 case 7: return GlobalValue::ExternalWeakLinkage;
72 case 8: return GlobalValue::CommonLinkage;
73 case 9: return GlobalValue::PrivateLinkage;
74 case 10: return GlobalValue::WeakODRLinkage;
75 case 11: return GlobalValue::LinkOnceODRLinkage;
76 case 12: return GlobalValue::AvailableExternallyLinkage;
77 case 13: return GlobalValue::LinkerPrivateLinkage;
81 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
83 default: // Map unknown visibilities to default.
84 case 0: return GlobalValue::DefaultVisibility;
85 case 1: return GlobalValue::HiddenVisibility;
86 case 2: return GlobalValue::ProtectedVisibility;
90 static int GetDecodedCastOpcode(unsigned Val) {
93 case bitc::CAST_TRUNC : return Instruction::Trunc;
94 case bitc::CAST_ZEXT : return Instruction::ZExt;
95 case bitc::CAST_SEXT : return Instruction::SExt;
96 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
97 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
98 case bitc::CAST_UITOFP : return Instruction::UIToFP;
99 case bitc::CAST_SITOFP : return Instruction::SIToFP;
100 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
101 case bitc::CAST_FPEXT : return Instruction::FPExt;
102 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
103 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
104 case bitc::CAST_BITCAST : return Instruction::BitCast;
107 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
110 case bitc::BINOP_ADD:
111 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
112 case bitc::BINOP_SUB:
113 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
114 case bitc::BINOP_MUL:
115 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
116 case bitc::BINOP_UDIV: return Instruction::UDiv;
117 case bitc::BINOP_SDIV:
118 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
119 case bitc::BINOP_UREM: return Instruction::URem;
120 case bitc::BINOP_SREM:
121 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
122 case bitc::BINOP_SHL: return Instruction::Shl;
123 case bitc::BINOP_LSHR: return Instruction::LShr;
124 case bitc::BINOP_ASHR: return Instruction::AShr;
125 case bitc::BINOP_AND: return Instruction::And;
126 case bitc::BINOP_OR: return Instruction::Or;
127 case bitc::BINOP_XOR: return Instruction::Xor;
133 /// @brief A class for maintaining the slot number definition
134 /// as a placeholder for the actual definition for forward constants defs.
135 class ConstantPlaceHolder : public ConstantExpr {
136 ConstantPlaceHolder(); // DO NOT IMPLEMENT
137 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
139 // allocate space for exactly one operand
140 void *operator new(size_t s) {
141 return User::operator new(s, 1);
143 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
144 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
145 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
148 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
149 static inline bool classof(const ConstantPlaceHolder *) { return true; }
150 static bool classof(const Value *V) {
151 return isa<ConstantExpr>(V) &&
152 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
156 /// Provide fast operand accessors
157 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
161 // FIXME: can we inherit this from ConstantExpr?
163 struct OperandTraits<ConstantPlaceHolder> : public FixedNumOperandTraits<1> {
168 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
177 WeakVH &OldV = ValuePtrs[Idx];
183 // Handle constants and non-constants (e.g. instrs) differently for
185 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
186 ResolveConstants.push_back(std::make_pair(PHC, Idx));
189 // If there was a forward reference to this value, replace it.
190 Value *PrevVal = OldV;
191 OldV->replaceAllUsesWith(V);
197 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
202 if (Value *V = ValuePtrs[Idx]) {
203 assert(Ty == V->getType() && "Type mismatch in constant table!");
204 return cast<Constant>(V);
207 // Create and return a placeholder, which will later be RAUW'd.
208 Constant *C = new ConstantPlaceHolder(Ty, Context);
213 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
217 if (Value *V = ValuePtrs[Idx]) {
218 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
222 // No type specified, must be invalid reference.
223 if (Ty == 0) return 0;
225 // Create and return a placeholder, which will later be RAUW'd.
226 Value *V = new Argument(Ty);
231 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
232 /// resolves any forward references. The idea behind this is that we sometimes
233 /// get constants (such as large arrays) which reference *many* forward ref
234 /// constants. Replacing each of these causes a lot of thrashing when
235 /// building/reuniquing the constant. Instead of doing this, we look at all the
236 /// uses and rewrite all the place holders at once for any constant that uses
238 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
239 // Sort the values by-pointer so that they are efficient to look up with a
241 std::sort(ResolveConstants.begin(), ResolveConstants.end());
243 SmallVector<Constant*, 64> NewOps;
245 while (!ResolveConstants.empty()) {
246 Value *RealVal = operator[](ResolveConstants.back().second);
247 Constant *Placeholder = ResolveConstants.back().first;
248 ResolveConstants.pop_back();
250 // Loop over all users of the placeholder, updating them to reference the
251 // new value. If they reference more than one placeholder, update them all
253 while (!Placeholder->use_empty()) {
254 Value::use_iterator UI = Placeholder->use_begin();
256 // If the using object isn't uniqued, just update the operands. This
257 // handles instructions and initializers for global variables.
258 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
259 UI.getUse().set(RealVal);
263 // Otherwise, we have a constant that uses the placeholder. Replace that
264 // constant with a new constant that has *all* placeholder uses updated.
265 Constant *UserC = cast<Constant>(*UI);
266 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
269 if (!isa<ConstantPlaceHolder>(*I)) {
270 // Not a placeholder reference.
272 } else if (*I == Placeholder) {
273 // Common case is that it just references this one placeholder.
276 // Otherwise, look up the placeholder in ResolveConstants.
277 ResolveConstantsTy::iterator It =
278 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
279 std::pair<Constant*, unsigned>(cast<Constant>(*I),
281 assert(It != ResolveConstants.end() && It->first == *I);
282 NewOp = operator[](It->second);
285 NewOps.push_back(cast<Constant>(NewOp));
288 // Make the new constant.
290 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
291 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
293 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
294 NewC = ConstantStruct::get(Context, &NewOps[0], NewOps.size(),
295 UserCS->getType()->isPacked());
296 } else if (isa<ConstantVector>(UserC)) {
297 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
299 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
300 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
304 UserC->replaceAllUsesWith(NewC);
305 UserC->destroyConstant();
309 // Update all ValueHandles, they should be the only users at this point.
310 Placeholder->replaceAllUsesWith(RealVal);
315 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
324 WeakVH &OldV = MDValuePtrs[Idx];
330 // If there was a forward reference to this value, replace it.
331 Value *PrevVal = OldV;
332 OldV->replaceAllUsesWith(V);
334 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
336 MDValuePtrs[Idx] = V;
339 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
343 if (Value *V = MDValuePtrs[Idx]) {
344 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
348 // Create and return a placeholder, which will later be RAUW'd.
349 Value *V = new Argument(Type::getMetadataTy(Context));
350 MDValuePtrs[Idx] = V;
354 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
355 // If the TypeID is in range, return it.
356 if (ID < TypeList.size())
357 return TypeList[ID].get();
358 if (!isTypeTable) return 0;
360 // The type table allows forward references. Push as many Opaque types as
361 // needed to get up to ID.
362 while (TypeList.size() <= ID)
363 TypeList.push_back(OpaqueType::get(Context));
364 return TypeList.back().get();
367 //===----------------------------------------------------------------------===//
368 // Functions for parsing blocks from the bitcode file
369 //===----------------------------------------------------------------------===//
371 bool BitcodeReader::ParseAttributeBlock() {
372 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
373 return Error("Malformed block record");
375 if (!MAttributes.empty())
376 return Error("Multiple PARAMATTR blocks found!");
378 SmallVector<uint64_t, 64> Record;
380 SmallVector<AttributeWithIndex, 8> Attrs;
382 // Read all the records.
384 unsigned Code = Stream.ReadCode();
385 if (Code == bitc::END_BLOCK) {
386 if (Stream.ReadBlockEnd())
387 return Error("Error at end of PARAMATTR block");
391 if (Code == bitc::ENTER_SUBBLOCK) {
392 // No known subblocks, always skip them.
393 Stream.ReadSubBlockID();
394 if (Stream.SkipBlock())
395 return Error("Malformed block record");
399 if (Code == bitc::DEFINE_ABBREV) {
400 Stream.ReadAbbrevRecord();
406 switch (Stream.ReadRecord(Code, Record)) {
407 default: // Default behavior: ignore.
409 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
410 if (Record.size() & 1)
411 return Error("Invalid ENTRY record");
413 // FIXME : Remove this autoupgrade code in LLVM 3.0.
414 // If Function attributes are using index 0 then transfer them
415 // to index ~0. Index 0 is used for return value attributes but used to be
416 // used for function attributes.
417 Attributes RetAttribute = Attribute::None;
418 Attributes FnAttribute = Attribute::None;
419 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
420 // FIXME: remove in LLVM 3.0
421 // The alignment is stored as a 16-bit raw value from bits 31--16.
422 // We shift the bits above 31 down by 11 bits.
424 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
425 if (Alignment && !isPowerOf2_32(Alignment))
426 return Error("Alignment is not a power of two.");
428 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
430 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
431 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
432 Record[i+1] = ReconstitutedAttr;
435 RetAttribute = Record[i+1];
436 else if (Record[i] == ~0U)
437 FnAttribute = Record[i+1];
440 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
441 Attribute::ReadOnly|Attribute::ReadNone);
443 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
444 (RetAttribute & OldRetAttrs) != 0) {
445 if (FnAttribute == Attribute::None) { // add a slot so they get added.
446 Record.push_back(~0U);
450 FnAttribute |= RetAttribute & OldRetAttrs;
451 RetAttribute &= ~OldRetAttrs;
454 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
455 if (Record[i] == 0) {
456 if (RetAttribute != Attribute::None)
457 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
458 } else if (Record[i] == ~0U) {
459 if (FnAttribute != Attribute::None)
460 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
461 } else if (Record[i+1] != Attribute::None)
462 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
465 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
474 bool BitcodeReader::ParseTypeTable() {
475 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
476 return Error("Malformed block record");
478 if (!TypeList.empty())
479 return Error("Multiple TYPE_BLOCKs found!");
481 SmallVector<uint64_t, 64> Record;
482 unsigned NumRecords = 0;
484 // Read all the records for this type table.
486 unsigned Code = Stream.ReadCode();
487 if (Code == bitc::END_BLOCK) {
488 if (NumRecords != TypeList.size())
489 return Error("Invalid type forward reference in TYPE_BLOCK");
490 if (Stream.ReadBlockEnd())
491 return Error("Error at end of type table block");
495 if (Code == bitc::ENTER_SUBBLOCK) {
496 // No known subblocks, always skip them.
497 Stream.ReadSubBlockID();
498 if (Stream.SkipBlock())
499 return Error("Malformed block record");
503 if (Code == bitc::DEFINE_ABBREV) {
504 Stream.ReadAbbrevRecord();
510 const Type *ResultTy = 0;
511 switch (Stream.ReadRecord(Code, Record)) {
512 default: // Default behavior: unknown type.
515 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
516 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
517 // type list. This allows us to reserve space.
518 if (Record.size() < 1)
519 return Error("Invalid TYPE_CODE_NUMENTRY record");
520 TypeList.reserve(Record[0]);
522 case bitc::TYPE_CODE_VOID: // VOID
523 ResultTy = Type::getVoidTy(Context);
525 case bitc::TYPE_CODE_FLOAT: // FLOAT
526 ResultTy = Type::getFloatTy(Context);
528 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
529 ResultTy = Type::getDoubleTy(Context);
531 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
532 ResultTy = Type::getX86_FP80Ty(Context);
534 case bitc::TYPE_CODE_FP128: // FP128
535 ResultTy = Type::getFP128Ty(Context);
537 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
538 ResultTy = Type::getPPC_FP128Ty(Context);
540 case bitc::TYPE_CODE_LABEL: // LABEL
541 ResultTy = Type::getLabelTy(Context);
543 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
546 case bitc::TYPE_CODE_METADATA: // METADATA
547 ResultTy = Type::getMetadataTy(Context);
549 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
550 if (Record.size() < 1)
551 return Error("Invalid Integer type record");
553 ResultTy = IntegerType::get(Context, Record[0]);
555 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
556 // [pointee type, address space]
557 if (Record.size() < 1)
558 return Error("Invalid POINTER type record");
559 unsigned AddressSpace = 0;
560 if (Record.size() == 2)
561 AddressSpace = Record[1];
562 ResultTy = PointerType::get(getTypeByID(Record[0], true),
566 case bitc::TYPE_CODE_FUNCTION: {
567 // FIXME: attrid is dead, remove it in LLVM 3.0
568 // FUNCTION: [vararg, attrid, retty, paramty x N]
569 if (Record.size() < 3)
570 return Error("Invalid FUNCTION type record");
571 std::vector<const Type*> ArgTys;
572 for (unsigned i = 3, e = Record.size(); i != e; ++i)
573 ArgTys.push_back(getTypeByID(Record[i], true));
575 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
579 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
580 if (Record.size() < 1)
581 return Error("Invalid STRUCT type record");
582 std::vector<const Type*> EltTys;
583 for (unsigned i = 1, e = Record.size(); i != e; ++i)
584 EltTys.push_back(getTypeByID(Record[i], true));
585 ResultTy = StructType::get(Context, EltTys, Record[0]);
588 case bitc::TYPE_CODE_UNION: { // UNION: [eltty x N]
589 SmallVector<const Type*, 8> EltTys;
590 for (unsigned i = 0, e = Record.size(); i != e; ++i)
591 EltTys.push_back(getTypeByID(Record[i], true));
592 ResultTy = UnionType::get(&EltTys[0], EltTys.size());
595 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
596 if (Record.size() < 2)
597 return Error("Invalid ARRAY type record");
598 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
600 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
601 if (Record.size() < 2)
602 return Error("Invalid VECTOR type record");
603 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
607 if (NumRecords == TypeList.size()) {
608 // If this is a new type slot, just append it.
609 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
611 } else if (ResultTy == 0) {
612 // Otherwise, this was forward referenced, so an opaque type was created,
613 // but the result type is actually just an opaque. Leave the one we
614 // created previously.
617 // Otherwise, this was forward referenced, so an opaque type was created.
618 // Resolve the opaque type to the real type now.
619 assert(NumRecords < TypeList.size() && "Typelist imbalance");
620 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
622 // Don't directly push the new type on the Tab. Instead we want to replace
623 // the opaque type we previously inserted with the new concrete value. The
624 // refinement from the abstract (opaque) type to the new type causes all
625 // uses of the abstract type to use the concrete type (NewTy). This will
626 // also cause the opaque type to be deleted.
627 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
629 // This should have replaced the old opaque type with the new type in the
630 // value table... or with a preexisting type that was already in the
631 // system. Let's just make sure it did.
632 assert(TypeList[NumRecords-1].get() != OldTy &&
633 "refineAbstractType didn't work!");
639 bool BitcodeReader::ParseTypeSymbolTable() {
640 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
641 return Error("Malformed block record");
643 SmallVector<uint64_t, 64> Record;
645 // Read all the records for this type table.
646 std::string TypeName;
648 unsigned Code = Stream.ReadCode();
649 if (Code == bitc::END_BLOCK) {
650 if (Stream.ReadBlockEnd())
651 return Error("Error at end of type symbol table block");
655 if (Code == bitc::ENTER_SUBBLOCK) {
656 // No known subblocks, always skip them.
657 Stream.ReadSubBlockID();
658 if (Stream.SkipBlock())
659 return Error("Malformed block record");
663 if (Code == bitc::DEFINE_ABBREV) {
664 Stream.ReadAbbrevRecord();
670 switch (Stream.ReadRecord(Code, Record)) {
671 default: // Default behavior: unknown type.
673 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
674 if (ConvertToString(Record, 1, TypeName))
675 return Error("Invalid TST_ENTRY record");
676 unsigned TypeID = Record[0];
677 if (TypeID >= TypeList.size())
678 return Error("Invalid Type ID in TST_ENTRY record");
680 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
687 bool BitcodeReader::ParseValueSymbolTable() {
688 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
689 return Error("Malformed block record");
691 SmallVector<uint64_t, 64> Record;
693 // Read all the records for this value table.
694 SmallString<128> ValueName;
696 unsigned Code = Stream.ReadCode();
697 if (Code == bitc::END_BLOCK) {
698 if (Stream.ReadBlockEnd())
699 return Error("Error at end of value symbol table block");
702 if (Code == bitc::ENTER_SUBBLOCK) {
703 // No known subblocks, always skip them.
704 Stream.ReadSubBlockID();
705 if (Stream.SkipBlock())
706 return Error("Malformed block record");
710 if (Code == bitc::DEFINE_ABBREV) {
711 Stream.ReadAbbrevRecord();
717 switch (Stream.ReadRecord(Code, Record)) {
718 default: // Default behavior: unknown type.
720 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
721 if (ConvertToString(Record, 1, ValueName))
722 return Error("Invalid VST_ENTRY record");
723 unsigned ValueID = Record[0];
724 if (ValueID >= ValueList.size())
725 return Error("Invalid Value ID in VST_ENTRY record");
726 Value *V = ValueList[ValueID];
728 V->setName(StringRef(ValueName.data(), ValueName.size()));
732 case bitc::VST_CODE_BBENTRY: {
733 if (ConvertToString(Record, 1, ValueName))
734 return Error("Invalid VST_BBENTRY record");
735 BasicBlock *BB = getBasicBlock(Record[0]);
737 return Error("Invalid BB ID in VST_BBENTRY record");
739 BB->setName(StringRef(ValueName.data(), ValueName.size()));
747 bool BitcodeReader::ParseMetadata() {
748 unsigned NextMDValueNo = MDValueList.size();
750 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
751 return Error("Malformed block record");
753 SmallVector<uint64_t, 64> Record;
755 // Read all the records.
757 unsigned Code = Stream.ReadCode();
758 if (Code == bitc::END_BLOCK) {
759 if (Stream.ReadBlockEnd())
760 return Error("Error at end of PARAMATTR block");
764 if (Code == bitc::ENTER_SUBBLOCK) {
765 // No known subblocks, always skip them.
766 Stream.ReadSubBlockID();
767 if (Stream.SkipBlock())
768 return Error("Malformed block record");
772 if (Code == bitc::DEFINE_ABBREV) {
773 Stream.ReadAbbrevRecord();
777 bool IsFunctionLocal = false;
780 switch (Stream.ReadRecord(Code, Record)) {
781 default: // Default behavior: ignore.
783 case bitc::METADATA_NAME: {
784 // Read named of the named metadata.
785 unsigned NameLength = Record.size();
787 Name.resize(NameLength);
788 for (unsigned i = 0; i != NameLength; ++i)
791 Code = Stream.ReadCode();
793 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
794 if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
795 assert ( 0 && "Inavlid Named Metadata record");
797 // Read named metadata elements.
798 unsigned Size = Record.size();
799 SmallVector<MDNode *, 8> Elts;
800 for (unsigned i = 0; i != Size; ++i) {
801 if (Record[i] == ~0U) {
802 Elts.push_back(NULL);
805 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
807 return Error("Malformed metadata record");
810 Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(),
811 Elts.size(), TheModule);
812 MDValueList.AssignValue(V, NextMDValueNo++);
815 case bitc::METADATA_FN_NODE:
816 IsFunctionLocal = true;
818 case bitc::METADATA_NODE: {
819 if (Record.empty() || Record.size() % 2 == 1)
820 return Error("Invalid METADATA_NODE record");
822 unsigned Size = Record.size();
823 SmallVector<Value*, 8> Elts;
824 for (unsigned i = 0; i != Size; i += 2) {
825 const Type *Ty = getTypeByID(Record[i], false);
826 if (Ty->isMetadataTy())
827 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
828 else if (!Ty->isVoidTy())
829 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
831 Elts.push_back(NULL);
833 Value *V = MDNode::getWhenValsUnresolved(Context, &Elts[0], Elts.size(),
835 IsFunctionLocal = false;
836 MDValueList.AssignValue(V, NextMDValueNo++);
839 case bitc::METADATA_STRING: {
840 unsigned MDStringLength = Record.size();
841 SmallString<8> String;
842 String.resize(MDStringLength);
843 for (unsigned i = 0; i != MDStringLength; ++i)
844 String[i] = Record[i];
845 Value *V = MDString::get(Context,
846 StringRef(String.data(), String.size()));
847 MDValueList.AssignValue(V, NextMDValueNo++);
850 case bitc::METADATA_KIND: {
851 unsigned RecordLength = Record.size();
852 if (Record.empty() || RecordLength < 2)
853 return Error("Invalid METADATA_KIND record");
855 Name.resize(RecordLength-1);
856 unsigned Kind = Record[0];
858 for (unsigned i = 1; i != RecordLength; ++i)
859 Name[i-1] = Record[i];
861 unsigned NewKind = TheModule->getMDKindID(Name.str());
862 assert(Kind == NewKind &&
863 "FIXME: Unable to handle custom metadata mismatch!");(void)NewKind;
870 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
871 /// the LSB for dense VBR encoding.
872 static uint64_t DecodeSignRotatedValue(uint64_t V) {
877 // There is no such thing as -0 with integers. "-0" really means MININT.
881 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
882 /// values and aliases that we can.
883 bool BitcodeReader::ResolveGlobalAndAliasInits() {
884 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
885 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
887 GlobalInitWorklist.swap(GlobalInits);
888 AliasInitWorklist.swap(AliasInits);
890 while (!GlobalInitWorklist.empty()) {
891 unsigned ValID = GlobalInitWorklist.back().second;
892 if (ValID >= ValueList.size()) {
893 // Not ready to resolve this yet, it requires something later in the file.
894 GlobalInits.push_back(GlobalInitWorklist.back());
896 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
897 GlobalInitWorklist.back().first->setInitializer(C);
899 return Error("Global variable initializer is not a constant!");
901 GlobalInitWorklist.pop_back();
904 while (!AliasInitWorklist.empty()) {
905 unsigned ValID = AliasInitWorklist.back().second;
906 if (ValID >= ValueList.size()) {
907 AliasInits.push_back(AliasInitWorklist.back());
909 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
910 AliasInitWorklist.back().first->setAliasee(C);
912 return Error("Alias initializer is not a constant!");
914 AliasInitWorklist.pop_back();
919 bool BitcodeReader::ParseConstants() {
920 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
921 return Error("Malformed block record");
923 SmallVector<uint64_t, 64> Record;
925 // Read all the records for this value table.
926 const Type *CurTy = Type::getInt32Ty(Context);
927 unsigned NextCstNo = ValueList.size();
929 unsigned Code = Stream.ReadCode();
930 if (Code == bitc::END_BLOCK)
933 if (Code == bitc::ENTER_SUBBLOCK) {
934 // No known subblocks, always skip them.
935 Stream.ReadSubBlockID();
936 if (Stream.SkipBlock())
937 return Error("Malformed block record");
941 if (Code == bitc::DEFINE_ABBREV) {
942 Stream.ReadAbbrevRecord();
949 unsigned BitCode = Stream.ReadRecord(Code, Record);
951 default: // Default behavior: unknown constant
952 case bitc::CST_CODE_UNDEF: // UNDEF
953 V = UndefValue::get(CurTy);
955 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
957 return Error("Malformed CST_SETTYPE record");
958 if (Record[0] >= TypeList.size())
959 return Error("Invalid Type ID in CST_SETTYPE record");
960 CurTy = TypeList[Record[0]];
961 continue; // Skip the ValueList manipulation.
962 case bitc::CST_CODE_NULL: // NULL
963 V = Constant::getNullValue(CurTy);
965 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
966 if (!CurTy->isIntegerTy() || Record.empty())
967 return Error("Invalid CST_INTEGER record");
968 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
970 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
971 if (!CurTy->isIntegerTy() || Record.empty())
972 return Error("Invalid WIDE_INTEGER record");
974 unsigned NumWords = Record.size();
975 SmallVector<uint64_t, 8> Words;
976 Words.resize(NumWords);
977 for (unsigned i = 0; i != NumWords; ++i)
978 Words[i] = DecodeSignRotatedValue(Record[i]);
979 V = ConstantInt::get(Context,
980 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
981 NumWords, &Words[0]));
984 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
986 return Error("Invalid FLOAT record");
987 if (CurTy->isFloatTy())
988 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
989 else if (CurTy->isDoubleTy())
990 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
991 else if (CurTy->isX86_FP80Ty()) {
992 // Bits are not stored the same way as a normal i80 APInt, compensate.
993 uint64_t Rearrange[2];
994 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
995 Rearrange[1] = Record[0] >> 48;
996 V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
997 } else if (CurTy->isFP128Ty())
998 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
999 else if (CurTy->isPPC_FP128Ty())
1000 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
1002 V = UndefValue::get(CurTy);
1006 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1008 return Error("Invalid CST_AGGREGATE record");
1010 unsigned Size = Record.size();
1011 std::vector<Constant*> Elts;
1013 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
1014 for (unsigned i = 0; i != Size; ++i)
1015 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1016 STy->getElementType(i)));
1017 V = ConstantStruct::get(STy, Elts);
1018 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1019 const Type *EltTy = ATy->getElementType();
1020 for (unsigned i = 0; i != Size; ++i)
1021 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1022 V = ConstantArray::get(ATy, Elts);
1023 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1024 const Type *EltTy = VTy->getElementType();
1025 for (unsigned i = 0; i != Size; ++i)
1026 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1027 V = ConstantVector::get(Elts);
1029 V = UndefValue::get(CurTy);
1033 case bitc::CST_CODE_STRING: { // STRING: [values]
1035 return Error("Invalid CST_AGGREGATE record");
1037 const ArrayType *ATy = cast<ArrayType>(CurTy);
1038 const Type *EltTy = ATy->getElementType();
1040 unsigned Size = Record.size();
1041 std::vector<Constant*> Elts;
1042 for (unsigned i = 0; i != Size; ++i)
1043 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1044 V = ConstantArray::get(ATy, Elts);
1047 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1049 return Error("Invalid CST_AGGREGATE record");
1051 const ArrayType *ATy = cast<ArrayType>(CurTy);
1052 const Type *EltTy = ATy->getElementType();
1054 unsigned Size = Record.size();
1055 std::vector<Constant*> Elts;
1056 for (unsigned i = 0; i != Size; ++i)
1057 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1058 Elts.push_back(Constant::getNullValue(EltTy));
1059 V = ConstantArray::get(ATy, Elts);
1062 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1063 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1064 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1066 V = UndefValue::get(CurTy); // Unknown binop.
1068 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1069 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1071 if (Record.size() >= 4) {
1072 if (Opc == Instruction::Add ||
1073 Opc == Instruction::Sub ||
1074 Opc == Instruction::Mul) {
1075 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1076 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1077 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1078 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1079 } else if (Opc == Instruction::SDiv) {
1080 if (Record[3] & (1 << bitc::SDIV_EXACT))
1081 Flags |= SDivOperator::IsExact;
1084 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1088 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1089 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1090 int Opc = GetDecodedCastOpcode(Record[0]);
1092 V = UndefValue::get(CurTy); // Unknown cast.
1094 const Type *OpTy = getTypeByID(Record[1]);
1095 if (!OpTy) return Error("Invalid CE_CAST record");
1096 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1097 V = ConstantExpr::getCast(Opc, Op, CurTy);
1101 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1102 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1103 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1104 SmallVector<Constant*, 16> Elts;
1105 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1106 const Type *ElTy = getTypeByID(Record[i]);
1107 if (!ElTy) return Error("Invalid CE_GEP record");
1108 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1110 if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1111 V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
1114 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
1118 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1119 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1120 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1121 Type::getInt1Ty(Context)),
1122 ValueList.getConstantFwdRef(Record[1],CurTy),
1123 ValueList.getConstantFwdRef(Record[2],CurTy));
1125 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1126 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1127 const VectorType *OpTy =
1128 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1129 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1130 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1131 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1132 V = ConstantExpr::getExtractElement(Op0, Op1);
1135 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1136 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1137 if (Record.size() < 3 || OpTy == 0)
1138 return Error("Invalid CE_INSERTELT record");
1139 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1140 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1141 OpTy->getElementType());
1142 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1143 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1146 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1147 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1148 if (Record.size() < 3 || OpTy == 0)
1149 return Error("Invalid CE_SHUFFLEVEC record");
1150 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1151 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1152 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1153 OpTy->getNumElements());
1154 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1155 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1158 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1159 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1160 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
1161 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1162 return Error("Invalid CE_SHUFVEC_EX record");
1163 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1164 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1165 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1166 RTy->getNumElements());
1167 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1168 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1171 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1172 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1173 const Type *OpTy = getTypeByID(Record[0]);
1174 if (OpTy == 0) return Error("Invalid CE_CMP record");
1175 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1176 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1178 if (OpTy->isFPOrFPVectorTy())
1179 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1181 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1184 case bitc::CST_CODE_INLINEASM: {
1185 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1186 std::string AsmStr, ConstrStr;
1187 bool HasSideEffects = Record[0] & 1;
1188 bool IsAlignStack = Record[0] >> 1;
1189 unsigned AsmStrSize = Record[1];
1190 if (2+AsmStrSize >= Record.size())
1191 return Error("Invalid INLINEASM record");
1192 unsigned ConstStrSize = Record[2+AsmStrSize];
1193 if (3+AsmStrSize+ConstStrSize > Record.size())
1194 return Error("Invalid INLINEASM record");
1196 for (unsigned i = 0; i != AsmStrSize; ++i)
1197 AsmStr += (char)Record[2+i];
1198 for (unsigned i = 0; i != ConstStrSize; ++i)
1199 ConstrStr += (char)Record[3+AsmStrSize+i];
1200 const PointerType *PTy = cast<PointerType>(CurTy);
1201 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1202 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1205 case bitc::CST_CODE_BLOCKADDRESS:{
1206 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1207 const Type *FnTy = getTypeByID(Record[0]);
1208 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1210 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1211 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1213 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1214 Type::getInt8Ty(Context),
1215 false, GlobalValue::InternalLinkage,
1217 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1223 ValueList.AssignValue(V, NextCstNo);
1227 if (NextCstNo != ValueList.size())
1228 return Error("Invalid constant reference!");
1230 if (Stream.ReadBlockEnd())
1231 return Error("Error at end of constants block");
1233 // Once all the constants have been read, go through and resolve forward
1235 ValueList.ResolveConstantForwardRefs();
1239 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1240 /// remember where it is and then skip it. This lets us lazily deserialize the
1242 bool BitcodeReader::RememberAndSkipFunctionBody() {
1243 // Get the function we are talking about.
1244 if (FunctionsWithBodies.empty())
1245 return Error("Insufficient function protos");
1247 Function *Fn = FunctionsWithBodies.back();
1248 FunctionsWithBodies.pop_back();
1250 // Save the current stream state.
1251 uint64_t CurBit = Stream.GetCurrentBitNo();
1252 DeferredFunctionInfo[Fn] = CurBit;
1254 // Skip over the function block for now.
1255 if (Stream.SkipBlock())
1256 return Error("Malformed block record");
1260 bool BitcodeReader::ParseModule() {
1261 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1262 return Error("Malformed block record");
1264 SmallVector<uint64_t, 64> Record;
1265 std::vector<std::string> SectionTable;
1266 std::vector<std::string> GCTable;
1268 // Read all the records for this module.
1269 while (!Stream.AtEndOfStream()) {
1270 unsigned Code = Stream.ReadCode();
1271 if (Code == bitc::END_BLOCK) {
1272 if (Stream.ReadBlockEnd())
1273 return Error("Error at end of module block");
1275 // Patch the initializers for globals and aliases up.
1276 ResolveGlobalAndAliasInits();
1277 if (!GlobalInits.empty() || !AliasInits.empty())
1278 return Error("Malformed global initializer set");
1279 if (!FunctionsWithBodies.empty())
1280 return Error("Too few function bodies found");
1282 // Look for intrinsic functions which need to be upgraded at some point
1283 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1286 if (UpgradeIntrinsicFunction(FI, NewFn))
1287 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1290 // Force deallocation of memory for these vectors to favor the client that
1291 // want lazy deserialization.
1292 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1293 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1294 std::vector<Function*>().swap(FunctionsWithBodies);
1298 if (Code == bitc::ENTER_SUBBLOCK) {
1299 switch (Stream.ReadSubBlockID()) {
1300 default: // Skip unknown content.
1301 if (Stream.SkipBlock())
1302 return Error("Malformed block record");
1304 case bitc::BLOCKINFO_BLOCK_ID:
1305 if (Stream.ReadBlockInfoBlock())
1306 return Error("Malformed BlockInfoBlock");
1308 case bitc::PARAMATTR_BLOCK_ID:
1309 if (ParseAttributeBlock())
1312 case bitc::TYPE_BLOCK_ID:
1313 if (ParseTypeTable())
1316 case bitc::TYPE_SYMTAB_BLOCK_ID:
1317 if (ParseTypeSymbolTable())
1320 case bitc::VALUE_SYMTAB_BLOCK_ID:
1321 if (ParseValueSymbolTable())
1324 case bitc::CONSTANTS_BLOCK_ID:
1325 if (ParseConstants() || ResolveGlobalAndAliasInits())
1328 case bitc::METADATA_BLOCK_ID:
1329 if (ParseMetadata())
1332 case bitc::FUNCTION_BLOCK_ID:
1333 // If this is the first function body we've seen, reverse the
1334 // FunctionsWithBodies list.
1335 if (!HasReversedFunctionsWithBodies) {
1336 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1337 HasReversedFunctionsWithBodies = true;
1340 if (RememberAndSkipFunctionBody())
1347 if (Code == bitc::DEFINE_ABBREV) {
1348 Stream.ReadAbbrevRecord();
1353 switch (Stream.ReadRecord(Code, Record)) {
1354 default: break; // Default behavior, ignore unknown content.
1355 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1356 if (Record.size() < 1)
1357 return Error("Malformed MODULE_CODE_VERSION");
1358 // Only version #0 is supported so far.
1360 return Error("Unknown bitstream version!");
1362 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1364 if (ConvertToString(Record, 0, S))
1365 return Error("Invalid MODULE_CODE_TRIPLE record");
1366 TheModule->setTargetTriple(S);
1369 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1371 if (ConvertToString(Record, 0, S))
1372 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1373 TheModule->setDataLayout(S);
1376 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1378 if (ConvertToString(Record, 0, S))
1379 return Error("Invalid MODULE_CODE_ASM record");
1380 TheModule->setModuleInlineAsm(S);
1383 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1385 if (ConvertToString(Record, 0, S))
1386 return Error("Invalid MODULE_CODE_DEPLIB record");
1387 TheModule->addLibrary(S);
1390 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1392 if (ConvertToString(Record, 0, S))
1393 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1394 SectionTable.push_back(S);
1397 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1399 if (ConvertToString(Record, 0, S))
1400 return Error("Invalid MODULE_CODE_GCNAME record");
1401 GCTable.push_back(S);
1404 // GLOBALVAR: [pointer type, isconst, initid,
1405 // linkage, alignment, section, visibility, threadlocal]
1406 case bitc::MODULE_CODE_GLOBALVAR: {
1407 if (Record.size() < 6)
1408 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1409 const Type *Ty = getTypeByID(Record[0]);
1410 if (!Ty->isPointerTy())
1411 return Error("Global not a pointer type!");
1412 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1413 Ty = cast<PointerType>(Ty)->getElementType();
1415 bool isConstant = Record[1];
1416 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1417 unsigned Alignment = (1 << Record[4]) >> 1;
1418 std::string Section;
1420 if (Record[5]-1 >= SectionTable.size())
1421 return Error("Invalid section ID");
1422 Section = SectionTable[Record[5]-1];
1424 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1425 if (Record.size() > 6)
1426 Visibility = GetDecodedVisibility(Record[6]);
1427 bool isThreadLocal = false;
1428 if (Record.size() > 7)
1429 isThreadLocal = Record[7];
1431 GlobalVariable *NewGV =
1432 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1433 isThreadLocal, AddressSpace);
1434 NewGV->setAlignment(Alignment);
1435 if (!Section.empty())
1436 NewGV->setSection(Section);
1437 NewGV->setVisibility(Visibility);
1438 NewGV->setThreadLocal(isThreadLocal);
1440 ValueList.push_back(NewGV);
1442 // Remember which value to use for the global initializer.
1443 if (unsigned InitID = Record[2])
1444 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1447 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1448 // alignment, section, visibility, gc]
1449 case bitc::MODULE_CODE_FUNCTION: {
1450 if (Record.size() < 8)
1451 return Error("Invalid MODULE_CODE_FUNCTION record");
1452 const Type *Ty = getTypeByID(Record[0]);
1453 if (!Ty->isPointerTy())
1454 return Error("Function not a pointer type!");
1455 const FunctionType *FTy =
1456 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1458 return Error("Function not a pointer to function type!");
1460 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1463 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1464 bool isProto = Record[2];
1465 Func->setLinkage(GetDecodedLinkage(Record[3]));
1466 Func->setAttributes(getAttributes(Record[4]));
1468 Func->setAlignment((1 << Record[5]) >> 1);
1470 if (Record[6]-1 >= SectionTable.size())
1471 return Error("Invalid section ID");
1472 Func->setSection(SectionTable[Record[6]-1]);
1474 Func->setVisibility(GetDecodedVisibility(Record[7]));
1475 if (Record.size() > 8 && Record[8]) {
1476 if (Record[8]-1 > GCTable.size())
1477 return Error("Invalid GC ID");
1478 Func->setGC(GCTable[Record[8]-1].c_str());
1480 ValueList.push_back(Func);
1482 // If this is a function with a body, remember the prototype we are
1483 // creating now, so that we can match up the body with them later.
1485 FunctionsWithBodies.push_back(Func);
1488 // ALIAS: [alias type, aliasee val#, linkage]
1489 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1490 case bitc::MODULE_CODE_ALIAS: {
1491 if (Record.size() < 3)
1492 return Error("Invalid MODULE_ALIAS record");
1493 const Type *Ty = getTypeByID(Record[0]);
1494 if (!Ty->isPointerTy())
1495 return Error("Function not a pointer type!");
1497 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1499 // Old bitcode files didn't have visibility field.
1500 if (Record.size() > 3)
1501 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1502 ValueList.push_back(NewGA);
1503 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1506 /// MODULE_CODE_PURGEVALS: [numvals]
1507 case bitc::MODULE_CODE_PURGEVALS:
1508 // Trim down the value list to the specified size.
1509 if (Record.size() < 1 || Record[0] > ValueList.size())
1510 return Error("Invalid MODULE_PURGEVALS record");
1511 ValueList.shrinkTo(Record[0]);
1517 return Error("Premature end of bitstream");
1520 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1523 if (Buffer->getBufferSize() & 3)
1524 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1526 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1527 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1529 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1530 // The magic number is 0x0B17C0DE stored in little endian.
1531 if (isBitcodeWrapper(BufPtr, BufEnd))
1532 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1533 return Error("Invalid bitcode wrapper header");
1535 StreamFile.init(BufPtr, BufEnd);
1536 Stream.init(StreamFile);
1538 // Sniff for the signature.
1539 if (Stream.Read(8) != 'B' ||
1540 Stream.Read(8) != 'C' ||
1541 Stream.Read(4) != 0x0 ||
1542 Stream.Read(4) != 0xC ||
1543 Stream.Read(4) != 0xE ||
1544 Stream.Read(4) != 0xD)
1545 return Error("Invalid bitcode signature");
1547 // We expect a number of well-defined blocks, though we don't necessarily
1548 // need to understand them all.
1549 while (!Stream.AtEndOfStream()) {
1550 unsigned Code = Stream.ReadCode();
1552 if (Code != bitc::ENTER_SUBBLOCK)
1553 return Error("Invalid record at top-level");
1555 unsigned BlockID = Stream.ReadSubBlockID();
1557 // We only know the MODULE subblock ID.
1559 case bitc::BLOCKINFO_BLOCK_ID:
1560 if (Stream.ReadBlockInfoBlock())
1561 return Error("Malformed BlockInfoBlock");
1563 case bitc::MODULE_BLOCK_ID:
1564 // Reject multiple MODULE_BLOCK's in a single bitstream.
1566 return Error("Multiple MODULE_BLOCKs in same stream");
1572 if (Stream.SkipBlock())
1573 return Error("Malformed block record");
1581 /// ParseMetadataAttachment - Parse metadata attachments.
1582 bool BitcodeReader::ParseMetadataAttachment() {
1583 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1584 return Error("Malformed block record");
1586 SmallVector<uint64_t, 64> Record;
1588 unsigned Code = Stream.ReadCode();
1589 if (Code == bitc::END_BLOCK) {
1590 if (Stream.ReadBlockEnd())
1591 return Error("Error at end of PARAMATTR block");
1594 if (Code == bitc::DEFINE_ABBREV) {
1595 Stream.ReadAbbrevRecord();
1598 // Read a metadata attachment record.
1600 switch (Stream.ReadRecord(Code, Record)) {
1601 default: // Default behavior: ignore.
1603 case bitc::METADATA_ATTACHMENT: {
1604 unsigned RecordLength = Record.size();
1605 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1606 return Error ("Invalid METADATA_ATTACHMENT reader!");
1607 Instruction *Inst = InstructionList[Record[0]];
1608 for (unsigned i = 1; i != RecordLength; i = i+2) {
1609 unsigned Kind = Record[i];
1610 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1611 Inst->setMetadata(Kind, cast<MDNode>(Node));
1620 /// ParseFunctionBody - Lazily parse the specified function body block.
1621 bool BitcodeReader::ParseFunctionBody(Function *F) {
1622 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1623 return Error("Malformed block record");
1625 InstructionList.clear();
1626 unsigned ModuleValueListSize = ValueList.size();
1628 // Add all the function arguments to the value table.
1629 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1630 ValueList.push_back(I);
1632 unsigned NextValueNo = ValueList.size();
1633 BasicBlock *CurBB = 0;
1634 unsigned CurBBNo = 0;
1636 // Read all the records.
1637 SmallVector<uint64_t, 64> Record;
1639 unsigned Code = Stream.ReadCode();
1640 if (Code == bitc::END_BLOCK) {
1641 if (Stream.ReadBlockEnd())
1642 return Error("Error at end of function block");
1646 if (Code == bitc::ENTER_SUBBLOCK) {
1647 switch (Stream.ReadSubBlockID()) {
1648 default: // Skip unknown content.
1649 if (Stream.SkipBlock())
1650 return Error("Malformed block record");
1652 case bitc::CONSTANTS_BLOCK_ID:
1653 if (ParseConstants()) return true;
1654 NextValueNo = ValueList.size();
1656 case bitc::VALUE_SYMTAB_BLOCK_ID:
1657 if (ParseValueSymbolTable()) return true;
1659 case bitc::METADATA_ATTACHMENT_ID:
1660 if (ParseMetadataAttachment()) return true;
1662 case bitc::METADATA_BLOCK_ID:
1663 if (ParseMetadata()) return true;
1669 if (Code == bitc::DEFINE_ABBREV) {
1670 Stream.ReadAbbrevRecord();
1677 unsigned BitCode = Stream.ReadRecord(Code, Record);
1679 default: // Default behavior: reject
1680 return Error("Unknown instruction");
1681 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1682 if (Record.size() < 1 || Record[0] == 0)
1683 return Error("Invalid DECLAREBLOCKS record");
1684 // Create all the basic blocks for the function.
1685 FunctionBBs.resize(Record[0]);
1686 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1687 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1688 CurBB = FunctionBBs[0];
1691 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1694 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1695 getValue(Record, OpNum, LHS->getType(), RHS) ||
1696 OpNum+1 > Record.size())
1697 return Error("Invalid BINOP record");
1699 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1700 if (Opc == -1) return Error("Invalid BINOP record");
1701 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1702 InstructionList.push_back(I);
1703 if (OpNum < Record.size()) {
1704 if (Opc == Instruction::Add ||
1705 Opc == Instruction::Sub ||
1706 Opc == Instruction::Mul) {
1707 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1708 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1709 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1710 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1711 } else if (Opc == Instruction::SDiv) {
1712 if (Record[OpNum] & (1 << bitc::SDIV_EXACT))
1713 cast<BinaryOperator>(I)->setIsExact(true);
1718 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1721 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1722 OpNum+2 != Record.size())
1723 return Error("Invalid CAST record");
1725 const Type *ResTy = getTypeByID(Record[OpNum]);
1726 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1727 if (Opc == -1 || ResTy == 0)
1728 return Error("Invalid CAST record");
1729 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1730 InstructionList.push_back(I);
1733 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
1734 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1737 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1738 return Error("Invalid GEP record");
1740 SmallVector<Value*, 16> GEPIdx;
1741 while (OpNum != Record.size()) {
1743 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1744 return Error("Invalid GEP record");
1745 GEPIdx.push_back(Op);
1748 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1749 InstructionList.push_back(I);
1750 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1751 cast<GetElementPtrInst>(I)->setIsInBounds(true);
1755 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1756 // EXTRACTVAL: [opty, opval, n x indices]
1759 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1760 return Error("Invalid EXTRACTVAL record");
1762 SmallVector<unsigned, 4> EXTRACTVALIdx;
1763 for (unsigned RecSize = Record.size();
1764 OpNum != RecSize; ++OpNum) {
1765 uint64_t Index = Record[OpNum];
1766 if ((unsigned)Index != Index)
1767 return Error("Invalid EXTRACTVAL index");
1768 EXTRACTVALIdx.push_back((unsigned)Index);
1771 I = ExtractValueInst::Create(Agg,
1772 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1773 InstructionList.push_back(I);
1777 case bitc::FUNC_CODE_INST_INSERTVAL: {
1778 // INSERTVAL: [opty, opval, opty, opval, n x indices]
1781 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1782 return Error("Invalid INSERTVAL record");
1784 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1785 return Error("Invalid INSERTVAL record");
1787 SmallVector<unsigned, 4> INSERTVALIdx;
1788 for (unsigned RecSize = Record.size();
1789 OpNum != RecSize; ++OpNum) {
1790 uint64_t Index = Record[OpNum];
1791 if ((unsigned)Index != Index)
1792 return Error("Invalid INSERTVAL index");
1793 INSERTVALIdx.push_back((unsigned)Index);
1796 I = InsertValueInst::Create(Agg, Val,
1797 INSERTVALIdx.begin(), INSERTVALIdx.end());
1798 InstructionList.push_back(I);
1802 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1803 // obsolete form of select
1804 // handles select i1 ... in old bitcode
1806 Value *TrueVal, *FalseVal, *Cond;
1807 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1808 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1809 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
1810 return Error("Invalid SELECT record");
1812 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1813 InstructionList.push_back(I);
1817 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1818 // new form of select
1819 // handles select i1 or select [N x i1]
1821 Value *TrueVal, *FalseVal, *Cond;
1822 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1823 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1824 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1825 return Error("Invalid SELECT record");
1827 // select condition can be either i1 or [N x i1]
1828 if (const VectorType* vector_type =
1829 dyn_cast<const VectorType>(Cond->getType())) {
1831 if (vector_type->getElementType() != Type::getInt1Ty(Context))
1832 return Error("Invalid SELECT condition type");
1835 if (Cond->getType() != Type::getInt1Ty(Context))
1836 return Error("Invalid SELECT condition type");
1839 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1840 InstructionList.push_back(I);
1844 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1847 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1848 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
1849 return Error("Invalid EXTRACTELT record");
1850 I = ExtractElementInst::Create(Vec, Idx);
1851 InstructionList.push_back(I);
1855 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1857 Value *Vec, *Elt, *Idx;
1858 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1859 getValue(Record, OpNum,
1860 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1861 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
1862 return Error("Invalid INSERTELT record");
1863 I = InsertElementInst::Create(Vec, Elt, Idx);
1864 InstructionList.push_back(I);
1868 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1870 Value *Vec1, *Vec2, *Mask;
1871 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1872 getValue(Record, OpNum, Vec1->getType(), Vec2))
1873 return Error("Invalid SHUFFLEVEC record");
1875 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
1876 return Error("Invalid SHUFFLEVEC record");
1877 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1878 InstructionList.push_back(I);
1882 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
1883 // Old form of ICmp/FCmp returning bool
1884 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1885 // both legal on vectors but had different behaviour.
1886 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1887 // FCmp/ICmp returning bool or vector of bool
1891 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1892 getValue(Record, OpNum, LHS->getType(), RHS) ||
1893 OpNum+1 != Record.size())
1894 return Error("Invalid CMP record");
1896 if (LHS->getType()->isFPOrFPVectorTy())
1897 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1899 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1900 InstructionList.push_back(I);
1904 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1905 if (Record.size() != 2)
1906 return Error("Invalid GETRESULT record");
1909 getValueTypePair(Record, OpNum, NextValueNo, Op);
1910 unsigned Index = Record[1];
1911 I = ExtractValueInst::Create(Op, Index);
1912 InstructionList.push_back(I);
1916 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1918 unsigned Size = Record.size();
1920 I = ReturnInst::Create(Context);
1921 InstructionList.push_back(I);
1926 SmallVector<Value *,4> Vs;
1929 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1930 return Error("Invalid RET record");
1932 } while(OpNum != Record.size());
1934 const Type *ReturnType = F->getReturnType();
1935 if (Vs.size() > 1 ||
1936 (ReturnType->isStructTy() &&
1937 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1938 Value *RV = UndefValue::get(ReturnType);
1939 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1940 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1941 InstructionList.push_back(I);
1942 CurBB->getInstList().push_back(I);
1943 ValueList.AssignValue(I, NextValueNo++);
1946 I = ReturnInst::Create(Context, RV);
1947 InstructionList.push_back(I);
1951 I = ReturnInst::Create(Context, Vs[0]);
1952 InstructionList.push_back(I);
1955 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1956 if (Record.size() != 1 && Record.size() != 3)
1957 return Error("Invalid BR record");
1958 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1960 return Error("Invalid BR record");
1962 if (Record.size() == 1) {
1963 I = BranchInst::Create(TrueDest);
1964 InstructionList.push_back(I);
1967 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1968 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
1969 if (FalseDest == 0 || Cond == 0)
1970 return Error("Invalid BR record");
1971 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1972 InstructionList.push_back(I);
1976 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
1977 if (Record.size() < 3 || (Record.size() & 1) == 0)
1978 return Error("Invalid SWITCH record");
1979 const Type *OpTy = getTypeByID(Record[0]);
1980 Value *Cond = getFnValueByID(Record[1], OpTy);
1981 BasicBlock *Default = getBasicBlock(Record[2]);
1982 if (OpTy == 0 || Cond == 0 || Default == 0)
1983 return Error("Invalid SWITCH record");
1984 unsigned NumCases = (Record.size()-3)/2;
1985 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1986 InstructionList.push_back(SI);
1987 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1988 ConstantInt *CaseVal =
1989 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1990 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1991 if (CaseVal == 0 || DestBB == 0) {
1993 return Error("Invalid SWITCH record!");
1995 SI->addCase(CaseVal, DestBB);
2000 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2001 if (Record.size() < 2)
2002 return Error("Invalid INDIRECTBR record");
2003 const Type *OpTy = getTypeByID(Record[0]);
2004 Value *Address = getFnValueByID(Record[1], OpTy);
2005 if (OpTy == 0 || Address == 0)
2006 return Error("Invalid INDIRECTBR record");
2007 unsigned NumDests = Record.size()-2;
2008 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2009 InstructionList.push_back(IBI);
2010 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2011 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2012 IBI->addDestination(DestBB);
2015 return Error("Invalid INDIRECTBR record!");
2022 case bitc::FUNC_CODE_INST_INVOKE: {
2023 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2024 if (Record.size() < 4) return Error("Invalid INVOKE record");
2025 AttrListPtr PAL = getAttributes(Record[0]);
2026 unsigned CCInfo = Record[1];
2027 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2028 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2032 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2033 return Error("Invalid INVOKE record");
2035 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2036 const FunctionType *FTy = !CalleeTy ? 0 :
2037 dyn_cast<FunctionType>(CalleeTy->getElementType());
2039 // Check that the right number of fixed parameters are here.
2040 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2041 Record.size() < OpNum+FTy->getNumParams())
2042 return Error("Invalid INVOKE record");
2044 SmallVector<Value*, 16> Ops;
2045 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2046 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2047 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2050 if (!FTy->isVarArg()) {
2051 if (Record.size() != OpNum)
2052 return Error("Invalid INVOKE record");
2054 // Read type/value pairs for varargs params.
2055 while (OpNum != Record.size()) {
2057 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2058 return Error("Invalid INVOKE record");
2063 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
2064 Ops.begin(), Ops.end());
2065 InstructionList.push_back(I);
2066 cast<InvokeInst>(I)->setCallingConv(
2067 static_cast<CallingConv::ID>(CCInfo));
2068 cast<InvokeInst>(I)->setAttributes(PAL);
2071 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2072 I = new UnwindInst(Context);
2073 InstructionList.push_back(I);
2075 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2076 I = new UnreachableInst(Context);
2077 InstructionList.push_back(I);
2079 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2080 if (Record.size() < 1 || ((Record.size()-1)&1))
2081 return Error("Invalid PHI record");
2082 const Type *Ty = getTypeByID(Record[0]);
2083 if (!Ty) return Error("Invalid PHI record");
2085 PHINode *PN = PHINode::Create(Ty);
2086 InstructionList.push_back(PN);
2087 PN->reserveOperandSpace((Record.size()-1)/2);
2089 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2090 Value *V = getFnValueByID(Record[1+i], Ty);
2091 BasicBlock *BB = getBasicBlock(Record[2+i]);
2092 if (!V || !BB) return Error("Invalid PHI record");
2093 PN->addIncoming(V, BB);
2099 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
2100 // Autoupgrade malloc instruction to malloc call.
2101 // FIXME: Remove in LLVM 3.0.
2102 if (Record.size() < 3)
2103 return Error("Invalid MALLOC record");
2104 const PointerType *Ty =
2105 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2106 Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
2107 if (!Ty || !Size) return Error("Invalid MALLOC record");
2108 if (!CurBB) return Error("Invalid malloc instruction with no BB");
2109 const Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext());
2110 Constant *AllocSize = ConstantExpr::getSizeOf(Ty->getElementType());
2111 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, Int32Ty);
2112 I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(),
2113 AllocSize, Size, NULL);
2114 InstructionList.push_back(I);
2117 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
2120 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2121 OpNum != Record.size())
2122 return Error("Invalid FREE record");
2123 if (!CurBB) return Error("Invalid free instruction with no BB");
2124 I = CallInst::CreateFree(Op, CurBB);
2125 InstructionList.push_back(I);
2128 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
2129 if (Record.size() < 3)
2130 return Error("Invalid ALLOCA record");
2131 const PointerType *Ty =
2132 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2133 Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
2134 unsigned Align = Record[2];
2135 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2136 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2137 InstructionList.push_back(I);
2140 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2143 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2144 OpNum+2 != Record.size())
2145 return Error("Invalid LOAD record");
2147 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2148 InstructionList.push_back(I);
2151 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
2154 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2155 getValue(Record, OpNum,
2156 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2157 OpNum+2 != Record.size())
2158 return Error("Invalid STORE record");
2160 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2161 InstructionList.push_back(I);
2164 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
2165 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
2168 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
2169 getValue(Record, OpNum,
2170 PointerType::getUnqual(Val->getType()), Ptr)||
2171 OpNum+2 != Record.size())
2172 return Error("Invalid STORE record");
2174 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2175 InstructionList.push_back(I);
2178 case bitc::FUNC_CODE_INST_CALL: {
2179 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2180 if (Record.size() < 3)
2181 return Error("Invalid CALL record");
2183 AttrListPtr PAL = getAttributes(Record[0]);
2184 unsigned CCInfo = Record[1];
2188 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2189 return Error("Invalid CALL record");
2191 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2192 const FunctionType *FTy = 0;
2193 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2194 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2195 return Error("Invalid CALL record");
2197 SmallVector<Value*, 16> Args;
2198 // Read the fixed params.
2199 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2200 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2201 Args.push_back(getBasicBlock(Record[OpNum]));
2203 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2204 if (Args.back() == 0) return Error("Invalid CALL record");
2207 // Read type/value pairs for varargs params.
2208 if (!FTy->isVarArg()) {
2209 if (OpNum != Record.size())
2210 return Error("Invalid CALL record");
2212 while (OpNum != Record.size()) {
2214 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2215 return Error("Invalid CALL record");
2220 I = CallInst::Create(Callee, Args.begin(), Args.end());
2221 InstructionList.push_back(I);
2222 cast<CallInst>(I)->setCallingConv(
2223 static_cast<CallingConv::ID>(CCInfo>>1));
2224 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2225 cast<CallInst>(I)->setAttributes(PAL);
2228 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2229 if (Record.size() < 3)
2230 return Error("Invalid VAARG record");
2231 const Type *OpTy = getTypeByID(Record[0]);
2232 Value *Op = getFnValueByID(Record[1], OpTy);
2233 const Type *ResTy = getTypeByID(Record[2]);
2234 if (!OpTy || !Op || !ResTy)
2235 return Error("Invalid VAARG record");
2236 I = new VAArgInst(Op, ResTy);
2237 InstructionList.push_back(I);
2242 // Add instruction to end of current BB. If there is no current BB, reject
2246 return Error("Invalid instruction with no BB");
2248 CurBB->getInstList().push_back(I);
2250 // If this was a terminator instruction, move to the next block.
2251 if (isa<TerminatorInst>(I)) {
2253 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2256 // Non-void values get registered in the value table for future use.
2257 if (I && !I->getType()->isVoidTy())
2258 ValueList.AssignValue(I, NextValueNo++);
2261 // Check the function list for unresolved values.
2262 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2263 if (A->getParent() == 0) {
2264 // We found at least one unresolved value. Nuke them all to avoid leaks.
2265 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2266 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
2267 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2271 return Error("Never resolved value found in function!");
2275 // See if anything took the address of blocks in this function. If so,
2276 // resolve them now.
2277 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
2278 /// are resolved lazily when functions are loaded.
2279 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2280 BlockAddrFwdRefs.find(F);
2281 if (BAFRI != BlockAddrFwdRefs.end()) {
2282 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2283 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2284 unsigned BlockIdx = RefList[i].first;
2285 if (BlockIdx >= FunctionBBs.size())
2286 return Error("Invalid blockaddress block #");
2288 GlobalVariable *FwdRef = RefList[i].second;
2289 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2290 FwdRef->eraseFromParent();
2293 BlockAddrFwdRefs.erase(BAFRI);
2296 // Trim the value list down to the size it was before we parsed this function.
2297 ValueList.shrinkTo(ModuleValueListSize);
2298 std::vector<BasicBlock*>().swap(FunctionBBs);
2303 //===----------------------------------------------------------------------===//
2304 // GVMaterializer implementation
2305 //===----------------------------------------------------------------------===//
2308 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2309 if (const Function *F = dyn_cast<Function>(GV)) {
2310 return F->isDeclaration() &&
2311 DeferredFunctionInfo.count(const_cast<Function*>(F));
2316 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2317 Function *F = dyn_cast<Function>(GV);
2318 // If it's not a function or is already material, ignore the request.
2319 if (!F || !F->isMaterializable()) return false;
2321 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2322 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2324 // Move the bit stream to the saved position of the deferred function body.
2325 Stream.JumpToBit(DFII->second);
2327 if (ParseFunctionBody(F)) {
2328 if (ErrInfo) *ErrInfo = ErrorString;
2332 // Upgrade any old intrinsic calls in the function.
2333 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2334 E = UpgradedIntrinsics.end(); I != E; ++I) {
2335 if (I->first != I->second) {
2336 for (Value::use_iterator UI = I->first->use_begin(),
2337 UE = I->first->use_end(); UI != UE; ) {
2338 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2339 UpgradeIntrinsicCall(CI, I->second);
2347 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2348 const Function *F = dyn_cast<Function>(GV);
2349 if (!F || F->isDeclaration())
2351 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2354 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2355 Function *F = dyn_cast<Function>(GV);
2356 // If this function isn't dematerializable, this is a noop.
2357 if (!F || !isDematerializable(F))
2360 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2362 // Just forget the function body, we can remat it later.
2367 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2368 assert(M == TheModule &&
2369 "Can only Materialize the Module this BitcodeReader is attached to.");
2370 // Iterate over the module, deserializing any functions that are still on
2372 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2374 if (F->isMaterializable() &&
2375 Materialize(F, ErrInfo))
2378 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2379 // delete the old functions to clean up. We can't do this unless the entire
2380 // module is materialized because there could always be another function body
2381 // with calls to the old function.
2382 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2383 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2384 if (I->first != I->second) {
2385 for (Value::use_iterator UI = I->first->use_begin(),
2386 UE = I->first->use_end(); UI != UE; ) {
2387 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2388 UpgradeIntrinsicCall(CI, I->second);
2390 if (!I->first->use_empty())
2391 I->first->replaceAllUsesWith(I->second);
2392 I->first->eraseFromParent();
2395 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2397 // Check debug info intrinsics.
2398 CheckDebugInfoIntrinsics(TheModule);
2404 //===----------------------------------------------------------------------===//
2405 // External interface
2406 //===----------------------------------------------------------------------===//
2408 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2410 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2411 LLVMContext& Context,
2412 std::string *ErrMsg) {
2413 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2414 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2415 M->setMaterializer(R);
2416 if (R->ParseBitcodeInto(M)) {
2418 *ErrMsg = R->getErrorString();
2420 delete M; // Also deletes R.
2423 // Have the BitcodeReader dtor delete 'Buffer'.
2424 R->setBufferOwned(true);
2428 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2429 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2430 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2431 std::string *ErrMsg){
2432 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2435 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2436 // there was an error.
2437 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2439 // Read in the entire module, and destroy the BitcodeReader.
2440 if (M->MaterializeAllPermanently(ErrMsg)) {