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/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/AutoUpgrade.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/OperandTraits.h"
29 void BitcodeReader::FreeState() {
32 std::vector<PATypeHolder>().swap(TypeList);
35 std::vector<PAListPtr>().swap(ParamAttrs);
36 std::vector<BasicBlock*>().swap(FunctionBBs);
37 std::vector<Function*>().swap(FunctionsWithBodies);
38 DeferredFunctionInfo.clear();
41 //===----------------------------------------------------------------------===//
42 // Helper functions to implement forward reference resolution, etc.
43 //===----------------------------------------------------------------------===//
45 /// ConvertToString - Convert a string from a record into an std::string, return
47 template<typename StrTy>
48 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
50 if (Idx > Record.size())
53 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
54 Result += (char)Record[i];
58 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
60 default: // Map unknown/new linkages to external
61 case 0: return GlobalValue::ExternalLinkage;
62 case 1: return GlobalValue::WeakLinkage;
63 case 2: return GlobalValue::AppendingLinkage;
64 case 3: return GlobalValue::InternalLinkage;
65 case 4: return GlobalValue::LinkOnceLinkage;
66 case 5: return GlobalValue::DLLImportLinkage;
67 case 6: return GlobalValue::DLLExportLinkage;
68 case 7: return GlobalValue::ExternalWeakLinkage;
69 case 8: return GlobalValue::CommonLinkage;
73 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
75 default: // Map unknown visibilities to default.
76 case 0: return GlobalValue::DefaultVisibility;
77 case 1: return GlobalValue::HiddenVisibility;
78 case 2: return GlobalValue::ProtectedVisibility;
82 static int GetDecodedCastOpcode(unsigned Val) {
85 case bitc::CAST_TRUNC : return Instruction::Trunc;
86 case bitc::CAST_ZEXT : return Instruction::ZExt;
87 case bitc::CAST_SEXT : return Instruction::SExt;
88 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
89 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
90 case bitc::CAST_UITOFP : return Instruction::UIToFP;
91 case bitc::CAST_SITOFP : return Instruction::SIToFP;
92 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
93 case bitc::CAST_FPEXT : return Instruction::FPExt;
94 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
95 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
96 case bitc::CAST_BITCAST : return Instruction::BitCast;
99 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
102 case bitc::BINOP_ADD: return Instruction::Add;
103 case bitc::BINOP_SUB: return Instruction::Sub;
104 case bitc::BINOP_MUL: return Instruction::Mul;
105 case bitc::BINOP_UDIV: return Instruction::UDiv;
106 case bitc::BINOP_SDIV:
107 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
108 case bitc::BINOP_UREM: return Instruction::URem;
109 case bitc::BINOP_SREM:
110 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
111 case bitc::BINOP_SHL: return Instruction::Shl;
112 case bitc::BINOP_LSHR: return Instruction::LShr;
113 case bitc::BINOP_ASHR: return Instruction::AShr;
114 case bitc::BINOP_AND: return Instruction::And;
115 case bitc::BINOP_OR: return Instruction::Or;
116 case bitc::BINOP_XOR: return Instruction::Xor;
122 /// @brief A class for maintaining the slot number definition
123 /// as a placeholder for the actual definition for forward constants defs.
124 class ConstantPlaceHolder : public ConstantExpr {
125 ConstantPlaceHolder(); // DO NOT IMPLEMENT
126 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
128 // allocate space for exactly one operand
129 void *operator new(size_t s) {
130 return User::operator new(s, 1);
132 explicit ConstantPlaceHolder(const Type *Ty)
133 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
134 Op<0>() = UndefValue::get(Type::Int32Ty);
137 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
138 static inline bool classof(const ConstantPlaceHolder *) { return true; }
139 static bool classof(const Value *V) {
140 return isa<ConstantExpr>(V) &&
141 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
145 /// Provide fast operand accessors
146 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
151 // FIXME: can we inherit this from ConstantExpr?
153 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
156 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
159 void BitcodeReaderValueList::resize(unsigned Desired) {
160 if (Desired > Capacity) {
161 // Since we expect many values to come from the bitcode file we better
162 // allocate the double amount, so that the array size grows exponentially
163 // at each reallocation. Also, add a small amount of 100 extra elements
164 // each time, to reallocate less frequently when the array is still small.
166 Capacity = Desired * 2 + 100;
167 Use *New = allocHungoffUses(Capacity);
168 Use *Old = OperandList;
169 unsigned Ops = getNumOperands();
170 for (int i(Ops - 1); i >= 0; --i)
171 New[i] = Old[i].get();
173 if (Old) Use::zap(Old, Old + Ops, true);
177 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
180 // Insert a bunch of null values.
185 if (Value *V = OperandList[Idx]) {
186 assert(Ty == V->getType() && "Type mismatch in constant table!");
187 return cast<Constant>(V);
190 // Create and return a placeholder, which will later be RAUW'd.
191 Constant *C = new ConstantPlaceHolder(Ty);
192 OperandList[Idx] = C;
196 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
198 // Insert a bunch of null values.
203 if (Value *V = OperandList[Idx]) {
204 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
208 // No type specified, must be invalid reference.
209 if (Ty == 0) return 0;
211 // Create and return a placeholder, which will later be RAUW'd.
212 Value *V = new Argument(Ty);
213 OperandList[Idx] = V;
217 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
218 /// resolves any forward references. The idea behind this is that we sometimes
219 /// get constants (such as large arrays) which reference *many* forward ref
220 /// constants. Replacing each of these causes a lot of thrashing when
221 /// building/reuniquing the constant. Instead of doing this, we look at all the
222 /// uses and rewrite all the place holders at once for any constant that uses
224 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
225 // Sort the values by-pointer so that they are efficient to look up with a
227 std::sort(ResolveConstants.begin(), ResolveConstants.end());
229 SmallVector<Constant*, 64> NewOps;
231 while (!ResolveConstants.empty()) {
232 Value *RealVal = getOperand(ResolveConstants.back().second);
233 Constant *Placeholder = ResolveConstants.back().first;
234 ResolveConstants.pop_back();
236 // Loop over all users of the placeholder, updating them to reference the
237 // new value. If they reference more than one placeholder, update them all
239 while (!Placeholder->use_empty()) {
240 User *U = Placeholder->use_back();
241 // If the using object isn't uniqued, just update the operands. This
242 // handles instructions and initializers for global variables.
243 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
244 U->replaceUsesOfWith(Placeholder, RealVal);
248 // Otherwise, we have a constant that uses the placeholder. Replace that
249 // constant with a new constant that has *all* placeholder uses updated.
250 Constant *UserC = cast<Constant>(U);
251 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
254 if (!isa<ConstantPlaceHolder>(*I)) {
255 // Not a placeholder reference.
257 } else if (*I == Placeholder) {
258 // Common case is that it just references this one placeholder.
261 // Otherwise, look up the placeholder in ResolveConstants.
262 ResolveConstantsTy::iterator It =
263 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
264 std::pair<Constant*, unsigned>(cast<Constant>(*I),
266 assert(It != ResolveConstants.end() && It->first == *I);
267 NewOp = this->getOperand(It->second);
270 NewOps.push_back(cast<Constant>(NewOp));
273 // Make the new constant.
275 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
276 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
277 } else if (isa<ConstantStruct>(UserC)) {
278 NewC = ConstantStruct::get(&NewOps[0], NewOps.size());
279 } else if (isa<ConstantVector>(UserC)) {
280 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
282 // Must be a constant expression.
283 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
287 UserC->replaceAllUsesWith(NewC);
288 UserC->destroyConstant();
297 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
298 // If the TypeID is in range, return it.
299 if (ID < TypeList.size())
300 return TypeList[ID].get();
301 if (!isTypeTable) return 0;
303 // The type table allows forward references. Push as many Opaque types as
304 // needed to get up to ID.
305 while (TypeList.size() <= ID)
306 TypeList.push_back(OpaqueType::get());
307 return TypeList.back().get();
310 //===----------------------------------------------------------------------===//
311 // Functions for parsing blocks from the bitcode file
312 //===----------------------------------------------------------------------===//
314 bool BitcodeReader::ParseParamAttrBlock() {
315 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
316 return Error("Malformed block record");
318 if (!ParamAttrs.empty())
319 return Error("Multiple PARAMATTR blocks found!");
321 SmallVector<uint64_t, 64> Record;
323 SmallVector<ParamAttrsWithIndex, 8> Attrs;
325 // Read all the records.
327 unsigned Code = Stream.ReadCode();
328 if (Code == bitc::END_BLOCK) {
329 if (Stream.ReadBlockEnd())
330 return Error("Error at end of PARAMATTR block");
334 if (Code == bitc::ENTER_SUBBLOCK) {
335 // No known subblocks, always skip them.
336 Stream.ReadSubBlockID();
337 if (Stream.SkipBlock())
338 return Error("Malformed block record");
342 if (Code == bitc::DEFINE_ABBREV) {
343 Stream.ReadAbbrevRecord();
349 switch (Stream.ReadRecord(Code, Record)) {
350 default: // Default behavior: ignore.
352 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
353 if (Record.size() & 1)
354 return Error("Invalid ENTRY record");
356 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
357 if (Record[i+1] != ParamAttr::None)
358 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
361 ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end()));
370 bool BitcodeReader::ParseTypeTable() {
371 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
372 return Error("Malformed block record");
374 if (!TypeList.empty())
375 return Error("Multiple TYPE_BLOCKs found!");
377 SmallVector<uint64_t, 64> Record;
378 unsigned NumRecords = 0;
380 // Read all the records for this type table.
382 unsigned Code = Stream.ReadCode();
383 if (Code == bitc::END_BLOCK) {
384 if (NumRecords != TypeList.size())
385 return Error("Invalid type forward reference in TYPE_BLOCK");
386 if (Stream.ReadBlockEnd())
387 return Error("Error at end of type table 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 const Type *ResultTy = 0;
407 switch (Stream.ReadRecord(Code, Record)) {
408 default: // Default behavior: unknown type.
411 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
412 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
413 // type list. This allows us to reserve space.
414 if (Record.size() < 1)
415 return Error("Invalid TYPE_CODE_NUMENTRY record");
416 TypeList.reserve(Record[0]);
418 case bitc::TYPE_CODE_VOID: // VOID
419 ResultTy = Type::VoidTy;
421 case bitc::TYPE_CODE_FLOAT: // FLOAT
422 ResultTy = Type::FloatTy;
424 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
425 ResultTy = Type::DoubleTy;
427 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
428 ResultTy = Type::X86_FP80Ty;
430 case bitc::TYPE_CODE_FP128: // FP128
431 ResultTy = Type::FP128Ty;
433 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
434 ResultTy = Type::PPC_FP128Ty;
436 case bitc::TYPE_CODE_LABEL: // LABEL
437 ResultTy = Type::LabelTy;
439 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
442 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
443 if (Record.size() < 1)
444 return Error("Invalid Integer type record");
446 ResultTy = IntegerType::get(Record[0]);
448 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
449 // [pointee type, address space]
450 if (Record.size() < 1)
451 return Error("Invalid POINTER type record");
452 unsigned AddressSpace = 0;
453 if (Record.size() == 2)
454 AddressSpace = Record[1];
455 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
458 case bitc::TYPE_CODE_FUNCTION: {
459 // FIXME: attrid is dead, remove it in LLVM 3.0
460 // FUNCTION: [vararg, attrid, retty, paramty x N]
461 if (Record.size() < 3)
462 return Error("Invalid FUNCTION type record");
463 std::vector<const Type*> ArgTys;
464 for (unsigned i = 3, e = Record.size(); i != e; ++i)
465 ArgTys.push_back(getTypeByID(Record[i], true));
467 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
471 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
472 if (Record.size() < 1)
473 return Error("Invalid STRUCT type record");
474 std::vector<const Type*> EltTys;
475 for (unsigned i = 1, e = Record.size(); i != e; ++i)
476 EltTys.push_back(getTypeByID(Record[i], true));
477 ResultTy = StructType::get(EltTys, Record[0]);
480 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
481 if (Record.size() < 2)
482 return Error("Invalid ARRAY type record");
483 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
485 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
486 if (Record.size() < 2)
487 return Error("Invalid VECTOR type record");
488 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
492 if (NumRecords == TypeList.size()) {
493 // If this is a new type slot, just append it.
494 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
496 } else if (ResultTy == 0) {
497 // Otherwise, this was forward referenced, so an opaque type was created,
498 // but the result type is actually just an opaque. Leave the one we
499 // created previously.
502 // Otherwise, this was forward referenced, so an opaque type was created.
503 // Resolve the opaque type to the real type now.
504 assert(NumRecords < TypeList.size() && "Typelist imbalance");
505 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
507 // Don't directly push the new type on the Tab. Instead we want to replace
508 // the opaque type we previously inserted with the new concrete value. The
509 // refinement from the abstract (opaque) type to the new type causes all
510 // uses of the abstract type to use the concrete type (NewTy). This will
511 // also cause the opaque type to be deleted.
512 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
514 // This should have replaced the old opaque type with the new type in the
515 // value table... or with a preexisting type that was already in the
516 // system. Let's just make sure it did.
517 assert(TypeList[NumRecords-1].get() != OldTy &&
518 "refineAbstractType didn't work!");
524 bool BitcodeReader::ParseTypeSymbolTable() {
525 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
526 return Error("Malformed block record");
528 SmallVector<uint64_t, 64> Record;
530 // Read all the records for this type table.
531 std::string TypeName;
533 unsigned Code = Stream.ReadCode();
534 if (Code == bitc::END_BLOCK) {
535 if (Stream.ReadBlockEnd())
536 return Error("Error at end of type symbol table block");
540 if (Code == bitc::ENTER_SUBBLOCK) {
541 // No known subblocks, always skip them.
542 Stream.ReadSubBlockID();
543 if (Stream.SkipBlock())
544 return Error("Malformed block record");
548 if (Code == bitc::DEFINE_ABBREV) {
549 Stream.ReadAbbrevRecord();
555 switch (Stream.ReadRecord(Code, Record)) {
556 default: // Default behavior: unknown type.
558 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
559 if (ConvertToString(Record, 1, TypeName))
560 return Error("Invalid TST_ENTRY record");
561 unsigned TypeID = Record[0];
562 if (TypeID >= TypeList.size())
563 return Error("Invalid Type ID in TST_ENTRY record");
565 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
572 bool BitcodeReader::ParseValueSymbolTable() {
573 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
574 return Error("Malformed block record");
576 SmallVector<uint64_t, 64> Record;
578 // Read all the records for this value table.
579 SmallString<128> ValueName;
581 unsigned Code = Stream.ReadCode();
582 if (Code == bitc::END_BLOCK) {
583 if (Stream.ReadBlockEnd())
584 return Error("Error at end of value symbol table block");
587 if (Code == bitc::ENTER_SUBBLOCK) {
588 // No known subblocks, always skip them.
589 Stream.ReadSubBlockID();
590 if (Stream.SkipBlock())
591 return Error("Malformed block record");
595 if (Code == bitc::DEFINE_ABBREV) {
596 Stream.ReadAbbrevRecord();
602 switch (Stream.ReadRecord(Code, Record)) {
603 default: // Default behavior: unknown type.
605 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
606 if (ConvertToString(Record, 1, ValueName))
607 return Error("Invalid TST_ENTRY record");
608 unsigned ValueID = Record[0];
609 if (ValueID >= ValueList.size())
610 return Error("Invalid Value ID in VST_ENTRY record");
611 Value *V = ValueList[ValueID];
613 V->setName(&ValueName[0], ValueName.size());
617 case bitc::VST_CODE_BBENTRY: {
618 if (ConvertToString(Record, 1, ValueName))
619 return Error("Invalid VST_BBENTRY record");
620 BasicBlock *BB = getBasicBlock(Record[0]);
622 return Error("Invalid BB ID in VST_BBENTRY record");
624 BB->setName(&ValueName[0], ValueName.size());
632 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
633 /// the LSB for dense VBR encoding.
634 static uint64_t DecodeSignRotatedValue(uint64_t V) {
639 // There is no such thing as -0 with integers. "-0" really means MININT.
643 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
644 /// values and aliases that we can.
645 bool BitcodeReader::ResolveGlobalAndAliasInits() {
646 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
647 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
649 GlobalInitWorklist.swap(GlobalInits);
650 AliasInitWorklist.swap(AliasInits);
652 while (!GlobalInitWorklist.empty()) {
653 unsigned ValID = GlobalInitWorklist.back().second;
654 if (ValID >= ValueList.size()) {
655 // Not ready to resolve this yet, it requires something later in the file.
656 GlobalInits.push_back(GlobalInitWorklist.back());
658 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
659 GlobalInitWorklist.back().first->setInitializer(C);
661 return Error("Global variable initializer is not a constant!");
663 GlobalInitWorklist.pop_back();
666 while (!AliasInitWorklist.empty()) {
667 unsigned ValID = AliasInitWorklist.back().second;
668 if (ValID >= ValueList.size()) {
669 AliasInits.push_back(AliasInitWorklist.back());
671 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
672 AliasInitWorklist.back().first->setAliasee(C);
674 return Error("Alias initializer is not a constant!");
676 AliasInitWorklist.pop_back();
682 bool BitcodeReader::ParseConstants() {
683 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
684 return Error("Malformed block record");
686 SmallVector<uint64_t, 64> Record;
688 // Read all the records for this value table.
689 const Type *CurTy = Type::Int32Ty;
690 unsigned NextCstNo = ValueList.size();
692 unsigned Code = Stream.ReadCode();
693 if (Code == bitc::END_BLOCK)
696 if (Code == bitc::ENTER_SUBBLOCK) {
697 // No known subblocks, always skip them.
698 Stream.ReadSubBlockID();
699 if (Stream.SkipBlock())
700 return Error("Malformed block record");
704 if (Code == bitc::DEFINE_ABBREV) {
705 Stream.ReadAbbrevRecord();
712 switch (Stream.ReadRecord(Code, Record)) {
713 default: // Default behavior: unknown constant
714 case bitc::CST_CODE_UNDEF: // UNDEF
715 V = UndefValue::get(CurTy);
717 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
719 return Error("Malformed CST_SETTYPE record");
720 if (Record[0] >= TypeList.size())
721 return Error("Invalid Type ID in CST_SETTYPE record");
722 CurTy = TypeList[Record[0]];
723 continue; // Skip the ValueList manipulation.
724 case bitc::CST_CODE_NULL: // NULL
725 V = Constant::getNullValue(CurTy);
727 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
728 if (!isa<IntegerType>(CurTy) || Record.empty())
729 return Error("Invalid CST_INTEGER record");
730 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
732 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
733 if (!isa<IntegerType>(CurTy) || Record.empty())
734 return Error("Invalid WIDE_INTEGER record");
736 unsigned NumWords = Record.size();
737 SmallVector<uint64_t, 8> Words;
738 Words.resize(NumWords);
739 for (unsigned i = 0; i != NumWords; ++i)
740 Words[i] = DecodeSignRotatedValue(Record[i]);
741 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
742 NumWords, &Words[0]));
745 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
747 return Error("Invalid FLOAT record");
748 if (CurTy == Type::FloatTy)
749 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
750 else if (CurTy == Type::DoubleTy)
751 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
752 else if (CurTy == Type::X86_FP80Ty)
753 V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
754 else if (CurTy == Type::FP128Ty)
755 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
756 else if (CurTy == Type::PPC_FP128Ty)
757 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
759 V = UndefValue::get(CurTy);
763 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
765 return Error("Invalid CST_AGGREGATE record");
767 unsigned Size = Record.size();
768 std::vector<Constant*> Elts;
770 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
771 for (unsigned i = 0; i != Size; ++i)
772 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
773 STy->getElementType(i)));
774 V = ConstantStruct::get(STy, Elts);
775 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
776 const Type *EltTy = ATy->getElementType();
777 for (unsigned i = 0; i != Size; ++i)
778 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
779 V = ConstantArray::get(ATy, Elts);
780 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
781 const Type *EltTy = VTy->getElementType();
782 for (unsigned i = 0; i != Size; ++i)
783 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
784 V = ConstantVector::get(Elts);
786 V = UndefValue::get(CurTy);
790 case bitc::CST_CODE_STRING: { // STRING: [values]
792 return Error("Invalid CST_AGGREGATE record");
794 const ArrayType *ATy = cast<ArrayType>(CurTy);
795 const Type *EltTy = ATy->getElementType();
797 unsigned Size = Record.size();
798 std::vector<Constant*> Elts;
799 for (unsigned i = 0; i != Size; ++i)
800 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
801 V = ConstantArray::get(ATy, Elts);
804 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
806 return Error("Invalid CST_AGGREGATE record");
808 const ArrayType *ATy = cast<ArrayType>(CurTy);
809 const Type *EltTy = ATy->getElementType();
811 unsigned Size = Record.size();
812 std::vector<Constant*> Elts;
813 for (unsigned i = 0; i != Size; ++i)
814 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
815 Elts.push_back(Constant::getNullValue(EltTy));
816 V = ConstantArray::get(ATy, Elts);
819 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
820 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
821 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
823 V = UndefValue::get(CurTy); // Unknown binop.
825 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
826 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
827 V = ConstantExpr::get(Opc, LHS, RHS);
831 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
832 if (Record.size() < 3) return Error("Invalid CE_CAST record");
833 int Opc = GetDecodedCastOpcode(Record[0]);
835 V = UndefValue::get(CurTy); // Unknown cast.
837 const Type *OpTy = getTypeByID(Record[1]);
838 if (!OpTy) return Error("Invalid CE_CAST record");
839 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
840 V = ConstantExpr::getCast(Opc, Op, CurTy);
844 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
845 if (Record.size() & 1) return Error("Invalid CE_GEP record");
846 SmallVector<Constant*, 16> Elts;
847 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
848 const Type *ElTy = getTypeByID(Record[i]);
849 if (!ElTy) return Error("Invalid CE_GEP record");
850 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
852 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
855 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
856 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
857 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
859 ValueList.getConstantFwdRef(Record[1],CurTy),
860 ValueList.getConstantFwdRef(Record[2],CurTy));
862 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
863 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
864 const VectorType *OpTy =
865 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
866 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
867 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
868 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
869 OpTy->getElementType());
870 V = ConstantExpr::getExtractElement(Op0, Op1);
873 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
874 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
875 if (Record.size() < 3 || OpTy == 0)
876 return Error("Invalid CE_INSERTELT record");
877 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
878 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
879 OpTy->getElementType());
880 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
881 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
884 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
885 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
886 if (Record.size() < 3 || OpTy == 0)
887 return Error("Invalid CE_INSERTELT record");
888 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
889 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
890 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
891 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
892 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
895 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
896 if (Record.size() < 4) return Error("Invalid CE_CMP record");
897 const Type *OpTy = getTypeByID(Record[0]);
898 if (OpTy == 0) return Error("Invalid CE_CMP record");
899 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
900 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
902 if (OpTy->isFloatingPoint())
903 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
904 else if (!isa<VectorType>(OpTy))
905 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
906 else if (OpTy->isFPOrFPVector())
907 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
909 V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
912 case bitc::CST_CODE_INLINEASM: {
913 if (Record.size() < 2) return Error("Invalid INLINEASM record");
914 std::string AsmStr, ConstrStr;
915 bool HasSideEffects = Record[0];
916 unsigned AsmStrSize = Record[1];
917 if (2+AsmStrSize >= Record.size())
918 return Error("Invalid INLINEASM record");
919 unsigned ConstStrSize = Record[2+AsmStrSize];
920 if (3+AsmStrSize+ConstStrSize > Record.size())
921 return Error("Invalid INLINEASM record");
923 for (unsigned i = 0; i != AsmStrSize; ++i)
924 AsmStr += (char)Record[2+i];
925 for (unsigned i = 0; i != ConstStrSize; ++i)
926 ConstrStr += (char)Record[3+AsmStrSize+i];
927 const PointerType *PTy = cast<PointerType>(CurTy);
928 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
929 AsmStr, ConstrStr, HasSideEffects);
934 ValueList.AssignValue(V, NextCstNo);
938 if (NextCstNo != ValueList.size())
939 return Error("Invalid constant reference!");
941 if (Stream.ReadBlockEnd())
942 return Error("Error at end of constants block");
944 // Once all the constants have been read, go through and resolve forward
946 ValueList.ResolveConstantForwardRefs();
950 /// RememberAndSkipFunctionBody - When we see the block for a function body,
951 /// remember where it is and then skip it. This lets us lazily deserialize the
953 bool BitcodeReader::RememberAndSkipFunctionBody() {
954 // Get the function we are talking about.
955 if (FunctionsWithBodies.empty())
956 return Error("Insufficient function protos");
958 Function *Fn = FunctionsWithBodies.back();
959 FunctionsWithBodies.pop_back();
961 // Save the current stream state.
962 uint64_t CurBit = Stream.GetCurrentBitNo();
963 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
965 // Set the functions linkage to GhostLinkage so we know it is lazily
967 Fn->setLinkage(GlobalValue::GhostLinkage);
969 // Skip over the function block for now.
970 if (Stream.SkipBlock())
971 return Error("Malformed block record");
975 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
976 // Reject multiple MODULE_BLOCK's in a single bitstream.
978 return Error("Multiple MODULE_BLOCKs in same stream");
980 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
981 return Error("Malformed block record");
983 // Otherwise, create the module.
984 TheModule = new Module(ModuleID);
986 SmallVector<uint64_t, 64> Record;
987 std::vector<std::string> SectionTable;
988 std::vector<std::string> GCTable;
990 // Read all the records for this module.
991 while (!Stream.AtEndOfStream()) {
992 unsigned Code = Stream.ReadCode();
993 if (Code == bitc::END_BLOCK) {
994 if (Stream.ReadBlockEnd())
995 return Error("Error at end of module block");
997 // Patch the initializers for globals and aliases up.
998 ResolveGlobalAndAliasInits();
999 if (!GlobalInits.empty() || !AliasInits.empty())
1000 return Error("Malformed global initializer set");
1001 if (!FunctionsWithBodies.empty())
1002 return Error("Too few function bodies found");
1004 // Look for intrinsic functions which need to be upgraded at some point
1005 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1008 if (UpgradeIntrinsicFunction(FI, NewFn))
1009 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1012 // Force deallocation of memory for these vectors to favor the client that
1013 // want lazy deserialization.
1014 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1015 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1016 std::vector<Function*>().swap(FunctionsWithBodies);
1020 if (Code == bitc::ENTER_SUBBLOCK) {
1021 switch (Stream.ReadSubBlockID()) {
1022 default: // Skip unknown content.
1023 if (Stream.SkipBlock())
1024 return Error("Malformed block record");
1026 case bitc::BLOCKINFO_BLOCK_ID:
1027 if (Stream.ReadBlockInfoBlock())
1028 return Error("Malformed BlockInfoBlock");
1030 case bitc::PARAMATTR_BLOCK_ID:
1031 if (ParseParamAttrBlock())
1034 case bitc::TYPE_BLOCK_ID:
1035 if (ParseTypeTable())
1038 case bitc::TYPE_SYMTAB_BLOCK_ID:
1039 if (ParseTypeSymbolTable())
1042 case bitc::VALUE_SYMTAB_BLOCK_ID:
1043 if (ParseValueSymbolTable())
1046 case bitc::CONSTANTS_BLOCK_ID:
1047 if (ParseConstants() || ResolveGlobalAndAliasInits())
1050 case bitc::FUNCTION_BLOCK_ID:
1051 // If this is the first function body we've seen, reverse the
1052 // FunctionsWithBodies list.
1053 if (!HasReversedFunctionsWithBodies) {
1054 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1055 HasReversedFunctionsWithBodies = true;
1058 if (RememberAndSkipFunctionBody())
1065 if (Code == bitc::DEFINE_ABBREV) {
1066 Stream.ReadAbbrevRecord();
1071 switch (Stream.ReadRecord(Code, Record)) {
1072 default: break; // Default behavior, ignore unknown content.
1073 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1074 if (Record.size() < 1)
1075 return Error("Malformed MODULE_CODE_VERSION");
1076 // Only version #0 is supported so far.
1078 return Error("Unknown bitstream version!");
1080 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1082 if (ConvertToString(Record, 0, S))
1083 return Error("Invalid MODULE_CODE_TRIPLE record");
1084 TheModule->setTargetTriple(S);
1087 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1089 if (ConvertToString(Record, 0, S))
1090 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1091 TheModule->setDataLayout(S);
1094 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1096 if (ConvertToString(Record, 0, S))
1097 return Error("Invalid MODULE_CODE_ASM record");
1098 TheModule->setModuleInlineAsm(S);
1101 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1103 if (ConvertToString(Record, 0, S))
1104 return Error("Invalid MODULE_CODE_DEPLIB record");
1105 TheModule->addLibrary(S);
1108 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1110 if (ConvertToString(Record, 0, S))
1111 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1112 SectionTable.push_back(S);
1115 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1117 if (ConvertToString(Record, 0, S))
1118 return Error("Invalid MODULE_CODE_GCNAME record");
1119 GCTable.push_back(S);
1122 // GLOBALVAR: [pointer type, isconst, initid,
1123 // linkage, alignment, section, visibility, threadlocal]
1124 case bitc::MODULE_CODE_GLOBALVAR: {
1125 if (Record.size() < 6)
1126 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1127 const Type *Ty = getTypeByID(Record[0]);
1128 if (!isa<PointerType>(Ty))
1129 return Error("Global not a pointer type!");
1130 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1131 Ty = cast<PointerType>(Ty)->getElementType();
1133 bool isConstant = Record[1];
1134 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1135 unsigned Alignment = (1 << Record[4]) >> 1;
1136 std::string Section;
1138 if (Record[5]-1 >= SectionTable.size())
1139 return Error("Invalid section ID");
1140 Section = SectionTable[Record[5]-1];
1142 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1143 if (Record.size() > 6)
1144 Visibility = GetDecodedVisibility(Record[6]);
1145 bool isThreadLocal = false;
1146 if (Record.size() > 7)
1147 isThreadLocal = Record[7];
1149 GlobalVariable *NewGV =
1150 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1151 isThreadLocal, AddressSpace);
1152 NewGV->setAlignment(Alignment);
1153 if (!Section.empty())
1154 NewGV->setSection(Section);
1155 NewGV->setVisibility(Visibility);
1156 NewGV->setThreadLocal(isThreadLocal);
1158 ValueList.push_back(NewGV);
1160 // Remember which value to use for the global initializer.
1161 if (unsigned InitID = Record[2])
1162 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1165 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1166 // alignment, section, visibility, gc]
1167 case bitc::MODULE_CODE_FUNCTION: {
1168 if (Record.size() < 8)
1169 return Error("Invalid MODULE_CODE_FUNCTION record");
1170 const Type *Ty = getTypeByID(Record[0]);
1171 if (!isa<PointerType>(Ty))
1172 return Error("Function not a pointer type!");
1173 const FunctionType *FTy =
1174 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1176 return Error("Function not a pointer to function type!");
1178 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1181 Func->setCallingConv(Record[1]);
1182 bool isProto = Record[2];
1183 Func->setLinkage(GetDecodedLinkage(Record[3]));
1184 Func->setParamAttrs(getParamAttrs(Record[4]));
1186 Func->setAlignment((1 << Record[5]) >> 1);
1188 if (Record[6]-1 >= SectionTable.size())
1189 return Error("Invalid section ID");
1190 Func->setSection(SectionTable[Record[6]-1]);
1192 Func->setVisibility(GetDecodedVisibility(Record[7]));
1193 if (Record.size() > 8 && Record[8]) {
1194 if (Record[8]-1 > GCTable.size())
1195 return Error("Invalid GC ID");
1196 Func->setGC(GCTable[Record[8]-1].c_str());
1199 ValueList.push_back(Func);
1201 // If this is a function with a body, remember the prototype we are
1202 // creating now, so that we can match up the body with them later.
1204 FunctionsWithBodies.push_back(Func);
1207 // ALIAS: [alias type, aliasee val#, linkage]
1208 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1209 case bitc::MODULE_CODE_ALIAS: {
1210 if (Record.size() < 3)
1211 return Error("Invalid MODULE_ALIAS record");
1212 const Type *Ty = getTypeByID(Record[0]);
1213 if (!isa<PointerType>(Ty))
1214 return Error("Function not a pointer type!");
1216 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1218 // Old bitcode files didn't have visibility field.
1219 if (Record.size() > 3)
1220 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1221 ValueList.push_back(NewGA);
1222 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1225 /// MODULE_CODE_PURGEVALS: [numvals]
1226 case bitc::MODULE_CODE_PURGEVALS:
1227 // Trim down the value list to the specified size.
1228 if (Record.size() < 1 || Record[0] > ValueList.size())
1229 return Error("Invalid MODULE_PURGEVALS record");
1230 ValueList.shrinkTo(Record[0]);
1236 return Error("Premature end of bitstream");
1239 /// SkipWrapperHeader - Some systems wrap bc files with a special header for
1240 /// padding or other reasons. The format of this header is:
1242 /// struct bc_header {
1243 /// uint32_t Magic; // 0x0B17C0DE
1244 /// uint32_t Version; // Version, currently always 0.
1245 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1246 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1247 /// ... potentially other gunk ...
1250 /// This function is called when we find a file with a matching magic number.
1251 /// In this case, skip down to the subsection of the file that is actually a BC
1253 static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
1255 KnownHeaderSize = 4*4, // Size of header we read.
1256 OffsetField = 2*4, // Offset in bytes to Offset field.
1257 SizeField = 3*4 // Offset in bytes to Size field.
1261 // Must contain the header!
1262 if (BufEnd-BufPtr < KnownHeaderSize) return true;
1264 unsigned Offset = ( BufPtr[OffsetField ] |
1265 (BufPtr[OffsetField+1] << 8) |
1266 (BufPtr[OffsetField+2] << 16) |
1267 (BufPtr[OffsetField+3] << 24));
1268 unsigned Size = ( BufPtr[SizeField ] |
1269 (BufPtr[SizeField +1] << 8) |
1270 (BufPtr[SizeField +2] << 16) |
1271 (BufPtr[SizeField +3] << 24));
1273 // Verify that Offset+Size fits in the file.
1274 if (Offset+Size > unsigned(BufEnd-BufPtr))
1277 BufEnd = BufPtr+Size;
1281 bool BitcodeReader::ParseBitcode() {
1284 if (Buffer->getBufferSize() & 3)
1285 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1287 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1288 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1290 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1291 // The magic number is 0x0B17C0DE stored in little endian.
1292 if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 &&
1293 BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
1294 if (SkipWrapperHeader(BufPtr, BufEnd))
1295 return Error("Invalid bitcode wrapper header");
1297 Stream.init(BufPtr, BufEnd);
1299 // Sniff for the signature.
1300 if (Stream.Read(8) != 'B' ||
1301 Stream.Read(8) != 'C' ||
1302 Stream.Read(4) != 0x0 ||
1303 Stream.Read(4) != 0xC ||
1304 Stream.Read(4) != 0xE ||
1305 Stream.Read(4) != 0xD)
1306 return Error("Invalid bitcode signature");
1308 // We expect a number of well-defined blocks, though we don't necessarily
1309 // need to understand them all.
1310 while (!Stream.AtEndOfStream()) {
1311 unsigned Code = Stream.ReadCode();
1313 if (Code != bitc::ENTER_SUBBLOCK)
1314 return Error("Invalid record at top-level");
1316 unsigned BlockID = Stream.ReadSubBlockID();
1318 // We only know the MODULE subblock ID.
1320 case bitc::BLOCKINFO_BLOCK_ID:
1321 if (Stream.ReadBlockInfoBlock())
1322 return Error("Malformed BlockInfoBlock");
1324 case bitc::MODULE_BLOCK_ID:
1325 if (ParseModule(Buffer->getBufferIdentifier()))
1329 if (Stream.SkipBlock())
1330 return Error("Malformed block record");
1339 /// ParseFunctionBody - Lazily parse the specified function body block.
1340 bool BitcodeReader::ParseFunctionBody(Function *F) {
1341 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1342 return Error("Malformed block record");
1344 unsigned ModuleValueListSize = ValueList.size();
1346 // Add all the function arguments to the value table.
1347 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1348 ValueList.push_back(I);
1350 unsigned NextValueNo = ValueList.size();
1351 BasicBlock *CurBB = 0;
1352 unsigned CurBBNo = 0;
1354 // Read all the records.
1355 SmallVector<uint64_t, 64> Record;
1357 unsigned Code = Stream.ReadCode();
1358 if (Code == bitc::END_BLOCK) {
1359 if (Stream.ReadBlockEnd())
1360 return Error("Error at end of function block");
1364 if (Code == bitc::ENTER_SUBBLOCK) {
1365 switch (Stream.ReadSubBlockID()) {
1366 default: // Skip unknown content.
1367 if (Stream.SkipBlock())
1368 return Error("Malformed block record");
1370 case bitc::CONSTANTS_BLOCK_ID:
1371 if (ParseConstants()) return true;
1372 NextValueNo = ValueList.size();
1374 case bitc::VALUE_SYMTAB_BLOCK_ID:
1375 if (ParseValueSymbolTable()) return true;
1381 if (Code == bitc::DEFINE_ABBREV) {
1382 Stream.ReadAbbrevRecord();
1389 switch (Stream.ReadRecord(Code, Record)) {
1390 default: // Default behavior: reject
1391 return Error("Unknown instruction");
1392 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1393 if (Record.size() < 1 || Record[0] == 0)
1394 return Error("Invalid DECLAREBLOCKS record");
1395 // Create all the basic blocks for the function.
1396 FunctionBBs.resize(Record[0]);
1397 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1398 FunctionBBs[i] = BasicBlock::Create("", F);
1399 CurBB = FunctionBBs[0];
1402 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1405 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1406 getValue(Record, OpNum, LHS->getType(), RHS) ||
1407 OpNum+1 != Record.size())
1408 return Error("Invalid BINOP record");
1410 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1411 if (Opc == -1) return Error("Invalid BINOP record");
1412 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1415 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1418 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1419 OpNum+2 != Record.size())
1420 return Error("Invalid CAST record");
1422 const Type *ResTy = getTypeByID(Record[OpNum]);
1423 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1424 if (Opc == -1 || ResTy == 0)
1425 return Error("Invalid CAST record");
1426 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1429 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1432 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1433 return Error("Invalid GEP record");
1435 SmallVector<Value*, 16> GEPIdx;
1436 while (OpNum != Record.size()) {
1438 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1439 return Error("Invalid GEP record");
1440 GEPIdx.push_back(Op);
1443 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1447 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1448 // EXTRACTVAL: [opty, opval, n x indices]
1451 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1452 return Error("Invalid EXTRACTVAL record");
1454 SmallVector<unsigned, 4> EXTRACTVALIdx;
1455 for (unsigned RecSize = Record.size();
1456 OpNum != RecSize; ++OpNum) {
1457 uint64_t Index = Record[OpNum];
1458 if ((unsigned)Index != Index)
1459 return Error("Invalid EXTRACTVAL index");
1460 EXTRACTVALIdx.push_back((unsigned)Index);
1463 I = ExtractValueInst::Create(Agg,
1464 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1468 case bitc::FUNC_CODE_INST_INSERTVAL: {
1469 // INSERTVAL: [opty, opval, opty, opval, n x indices]
1472 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1473 return Error("Invalid INSERTVAL record");
1475 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1476 return Error("Invalid INSERTVAL record");
1478 SmallVector<unsigned, 4> INSERTVALIdx;
1479 for (unsigned RecSize = Record.size();
1480 OpNum != RecSize; ++OpNum) {
1481 uint64_t Index = Record[OpNum];
1482 if ((unsigned)Index != Index)
1483 return Error("Invalid INSERTVAL index");
1484 INSERTVALIdx.push_back((unsigned)Index);
1487 I = InsertValueInst::Create(Agg, Val,
1488 INSERTVALIdx.begin(), INSERTVALIdx.end());
1492 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1494 Value *TrueVal, *FalseVal, *Cond;
1495 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1496 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1497 getValue(Record, OpNum, Type::Int1Ty, Cond))
1498 return Error("Invalid SELECT record");
1500 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1504 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1507 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1508 getValue(Record, OpNum, Type::Int32Ty, Idx))
1509 return Error("Invalid EXTRACTELT record");
1510 I = new ExtractElementInst(Vec, Idx);
1514 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1516 Value *Vec, *Elt, *Idx;
1517 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1518 getValue(Record, OpNum,
1519 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1520 getValue(Record, OpNum, Type::Int32Ty, Idx))
1521 return Error("Invalid INSERTELT record");
1522 I = InsertElementInst::Create(Vec, Elt, Idx);
1526 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1528 Value *Vec1, *Vec2, *Mask;
1529 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1530 getValue(Record, OpNum, Vec1->getType(), Vec2))
1531 return Error("Invalid SHUFFLEVEC record");
1533 const Type *MaskTy =
1534 VectorType::get(Type::Int32Ty,
1535 cast<VectorType>(Vec1->getType())->getNumElements());
1537 if (getValue(Record, OpNum, MaskTy, Mask))
1538 return Error("Invalid SHUFFLEVEC record");
1539 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1543 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1546 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1547 getValue(Record, OpNum, LHS->getType(), RHS) ||
1548 OpNum+1 != Record.size())
1549 return Error("Invalid CMP record");
1551 if (LHS->getType()->isFloatingPoint())
1552 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1553 else if (!isa<VectorType>(LHS->getType()))
1554 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1555 else if (LHS->getType()->isFPOrFPVector())
1556 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1558 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1561 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1562 if (Record.size() != 2)
1563 return Error("Invalid GETRESULT record");
1566 getValueTypePair(Record, OpNum, NextValueNo, Op);
1567 unsigned Index = Record[1];
1568 I = ExtractValueInst::Create(Op, Index);
1572 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1574 unsigned Size = Record.size();
1576 I = ReturnInst::Create();
1581 SmallVector<Value *,4> Vs;
1584 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1585 return Error("Invalid RET record");
1587 } while(OpNum != Record.size());
1589 const Type *ReturnType = F->getReturnType();
1590 if (Vs.size() > 1 ||
1591 (isa<StructType>(ReturnType) &&
1592 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1593 Value *RV = UndefValue::get(ReturnType);
1594 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1595 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1596 CurBB->getInstList().push_back(I);
1597 ValueList.AssignValue(I, NextValueNo++);
1600 I = ReturnInst::Create(RV);
1604 I = ReturnInst::Create(Vs[0]);
1607 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1608 if (Record.size() != 1 && Record.size() != 3)
1609 return Error("Invalid BR record");
1610 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1612 return Error("Invalid BR record");
1614 if (Record.size() == 1)
1615 I = BranchInst::Create(TrueDest);
1617 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1618 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1619 if (FalseDest == 0 || Cond == 0)
1620 return Error("Invalid BR record");
1621 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1625 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1626 if (Record.size() < 3 || (Record.size() & 1) == 0)
1627 return Error("Invalid SWITCH record");
1628 const Type *OpTy = getTypeByID(Record[0]);
1629 Value *Cond = getFnValueByID(Record[1], OpTy);
1630 BasicBlock *Default = getBasicBlock(Record[2]);
1631 if (OpTy == 0 || Cond == 0 || Default == 0)
1632 return Error("Invalid SWITCH record");
1633 unsigned NumCases = (Record.size()-3)/2;
1634 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1635 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1636 ConstantInt *CaseVal =
1637 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1638 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1639 if (CaseVal == 0 || DestBB == 0) {
1641 return Error("Invalid SWITCH record!");
1643 SI->addCase(CaseVal, DestBB);
1649 case bitc::FUNC_CODE_INST_INVOKE: {
1650 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1651 if (Record.size() < 4) return Error("Invalid INVOKE record");
1652 PAListPtr PAL = getParamAttrs(Record[0]);
1653 unsigned CCInfo = Record[1];
1654 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1655 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1659 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1660 return Error("Invalid INVOKE record");
1662 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1663 const FunctionType *FTy = !CalleeTy ? 0 :
1664 dyn_cast<FunctionType>(CalleeTy->getElementType());
1666 // Check that the right number of fixed parameters are here.
1667 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1668 Record.size() < OpNum+FTy->getNumParams())
1669 return Error("Invalid INVOKE record");
1671 SmallVector<Value*, 16> Ops;
1672 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1673 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1674 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1677 if (!FTy->isVarArg()) {
1678 if (Record.size() != OpNum)
1679 return Error("Invalid INVOKE record");
1681 // Read type/value pairs for varargs params.
1682 while (OpNum != Record.size()) {
1684 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1685 return Error("Invalid INVOKE record");
1690 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1691 Ops.begin(), Ops.end());
1692 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1693 cast<InvokeInst>(I)->setParamAttrs(PAL);
1696 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1697 I = new UnwindInst();
1699 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1700 I = new UnreachableInst();
1702 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1703 if (Record.size() < 1 || ((Record.size()-1)&1))
1704 return Error("Invalid PHI record");
1705 const Type *Ty = getTypeByID(Record[0]);
1706 if (!Ty) return Error("Invalid PHI record");
1708 PHINode *PN = PHINode::Create(Ty);
1709 PN->reserveOperandSpace((Record.size()-1)/2);
1711 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1712 Value *V = getFnValueByID(Record[1+i], Ty);
1713 BasicBlock *BB = getBasicBlock(Record[2+i]);
1714 if (!V || !BB) return Error("Invalid PHI record");
1715 PN->addIncoming(V, BB);
1721 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1722 if (Record.size() < 3)
1723 return Error("Invalid MALLOC record");
1724 const PointerType *Ty =
1725 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1726 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1727 unsigned Align = Record[2];
1728 if (!Ty || !Size) return Error("Invalid MALLOC record");
1729 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1732 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1735 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1736 OpNum != Record.size())
1737 return Error("Invalid FREE record");
1738 I = new FreeInst(Op);
1741 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1742 if (Record.size() < 3)
1743 return Error("Invalid ALLOCA record");
1744 const PointerType *Ty =
1745 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1746 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1747 unsigned Align = Record[2];
1748 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1749 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1752 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1755 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1756 OpNum+2 != Record.size())
1757 return Error("Invalid LOAD record");
1759 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1762 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1765 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1766 getValue(Record, OpNum,
1767 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1768 OpNum+2 != Record.size())
1769 return Error("Invalid STORE record");
1771 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1774 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1775 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1778 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1779 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
1780 OpNum+2 != Record.size())
1781 return Error("Invalid STORE record");
1783 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1786 case bitc::FUNC_CODE_INST_CALL: {
1787 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1788 if (Record.size() < 3)
1789 return Error("Invalid CALL record");
1791 PAListPtr PAL = getParamAttrs(Record[0]);
1792 unsigned CCInfo = Record[1];
1796 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1797 return Error("Invalid CALL record");
1799 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1800 const FunctionType *FTy = 0;
1801 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1802 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1803 return Error("Invalid CALL record");
1805 SmallVector<Value*, 16> Args;
1806 // Read the fixed params.
1807 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1808 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1809 Args.push_back(getBasicBlock(Record[OpNum]));
1811 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1812 if (Args.back() == 0) return Error("Invalid CALL record");
1815 // Read type/value pairs for varargs params.
1816 if (!FTy->isVarArg()) {
1817 if (OpNum != Record.size())
1818 return Error("Invalid CALL record");
1820 while (OpNum != Record.size()) {
1822 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1823 return Error("Invalid CALL record");
1828 I = CallInst::Create(Callee, Args.begin(), Args.end());
1829 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1830 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1831 cast<CallInst>(I)->setParamAttrs(PAL);
1834 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1835 if (Record.size() < 3)
1836 return Error("Invalid VAARG record");
1837 const Type *OpTy = getTypeByID(Record[0]);
1838 Value *Op = getFnValueByID(Record[1], OpTy);
1839 const Type *ResTy = getTypeByID(Record[2]);
1840 if (!OpTy || !Op || !ResTy)
1841 return Error("Invalid VAARG record");
1842 I = new VAArgInst(Op, ResTy);
1847 // Add instruction to end of current BB. If there is no current BB, reject
1851 return Error("Invalid instruction with no BB");
1853 CurBB->getInstList().push_back(I);
1855 // If this was a terminator instruction, move to the next block.
1856 if (isa<TerminatorInst>(I)) {
1858 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1861 // Non-void values get registered in the value table for future use.
1862 if (I && I->getType() != Type::VoidTy)
1863 ValueList.AssignValue(I, NextValueNo++);
1866 // Check the function list for unresolved values.
1867 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1868 if (A->getParent() == 0) {
1869 // We found at least one unresolved value. Nuke them all to avoid leaks.
1870 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1871 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1872 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1876 return Error("Never resolved value found in function!");
1880 // Trim the value list down to the size it was before we parsed this function.
1881 ValueList.shrinkTo(ModuleValueListSize);
1882 std::vector<BasicBlock*>().swap(FunctionBBs);
1887 //===----------------------------------------------------------------------===//
1888 // ModuleProvider implementation
1889 //===----------------------------------------------------------------------===//
1892 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1893 // If it already is material, ignore the request.
1894 if (!F->hasNotBeenReadFromBitcode()) return false;
1896 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1897 DeferredFunctionInfo.find(F);
1898 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1900 // Move the bit stream to the saved position of the deferred function body and
1901 // restore the real linkage type for the function.
1902 Stream.JumpToBit(DFII->second.first);
1903 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1905 if (ParseFunctionBody(F)) {
1906 if (ErrInfo) *ErrInfo = ErrorString;
1910 // Upgrade any old intrinsic calls in the function.
1911 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1912 E = UpgradedIntrinsics.end(); I != E; ++I) {
1913 if (I->first != I->second) {
1914 for (Value::use_iterator UI = I->first->use_begin(),
1915 UE = I->first->use_end(); UI != UE; ) {
1916 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1917 UpgradeIntrinsicCall(CI, I->second);
1925 void BitcodeReader::dematerializeFunction(Function *F) {
1926 // If this function isn't materialized, or if it is a proto, this is a noop.
1927 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1930 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1932 // Just forget the function body, we can remat it later.
1934 F->setLinkage(GlobalValue::GhostLinkage);
1938 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1939 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1940 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1942 Function *F = I->first;
1943 if (F->hasNotBeenReadFromBitcode() &&
1944 materializeFunction(F, ErrInfo))
1948 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1949 // delete the old functions to clean up. We can't do this unless the entire
1950 // module is materialized because there could always be another function body
1951 // with calls to the old function.
1952 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1953 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1954 if (I->first != I->second) {
1955 for (Value::use_iterator UI = I->first->use_begin(),
1956 UE = I->first->use_end(); UI != UE; ) {
1957 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1958 UpgradeIntrinsicCall(CI, I->second);
1960 ValueList.replaceUsesOfWith(I->first, I->second);
1961 I->first->eraseFromParent();
1964 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1970 /// This method is provided by the parent ModuleProvde class and overriden
1971 /// here. It simply releases the module from its provided and frees up our
1973 /// @brief Release our hold on the generated module
1974 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1975 // Since we're losing control of this Module, we must hand it back complete
1976 Module *M = ModuleProvider::releaseModule(ErrInfo);
1982 //===----------------------------------------------------------------------===//
1983 // External interface
1984 //===----------------------------------------------------------------------===//
1986 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1988 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1989 std::string *ErrMsg) {
1990 BitcodeReader *R = new BitcodeReader(Buffer);
1991 if (R->ParseBitcode()) {
1993 *ErrMsg = R->getErrorString();
1995 // Don't let the BitcodeReader dtor delete 'Buffer'.
1996 R->releaseMemoryBuffer();
2003 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2004 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2005 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
2007 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
2010 // Read in the entire module.
2011 Module *M = R->materializeModule(ErrMsg);
2013 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2014 // there was an error.
2015 R->releaseMemoryBuffer();
2017 // If there was no error, tell ModuleProvider not to delete it when its dtor
2020 M = R->releaseModule(ErrMsg);