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/ParamAttrsList.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"
29 void BitcodeReader::FreeState() {
32 std::vector<PATypeHolder>().swap(TypeList);
35 // Drop references to ParamAttrs.
36 for (unsigned i = 0, e = ParamAttrs.size(); i != e; ++i)
37 ParamAttrs[i]->dropRef();
39 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
40 std::vector<BasicBlock*>().swap(FunctionBBs);
41 std::vector<Function*>().swap(FunctionsWithBodies);
42 DeferredFunctionInfo.clear();
45 //===----------------------------------------------------------------------===//
46 // Helper functions to implement forward reference resolution, etc.
47 //===----------------------------------------------------------------------===//
49 /// ConvertToString - Convert a string from a record into an std::string, return
51 template<typename StrTy>
52 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
54 if (Idx > Record.size())
57 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58 Result += (char)Record[i];
62 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
64 default: // Map unknown/new linkages to external
65 case 0: return GlobalValue::ExternalLinkage;
66 case 1: return GlobalValue::WeakLinkage;
67 case 2: return GlobalValue::AppendingLinkage;
68 case 3: return GlobalValue::InternalLinkage;
69 case 4: return GlobalValue::LinkOnceLinkage;
70 case 5: return GlobalValue::DLLImportLinkage;
71 case 6: return GlobalValue::DLLExportLinkage;
72 case 7: return GlobalValue::ExternalWeakLinkage;
76 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
78 default: // Map unknown visibilities to default.
79 case 0: return GlobalValue::DefaultVisibility;
80 case 1: return GlobalValue::HiddenVisibility;
81 case 2: return GlobalValue::ProtectedVisibility;
85 static int GetDecodedCastOpcode(unsigned Val) {
88 case bitc::CAST_TRUNC : return Instruction::Trunc;
89 case bitc::CAST_ZEXT : return Instruction::ZExt;
90 case bitc::CAST_SEXT : return Instruction::SExt;
91 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
92 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
93 case bitc::CAST_UITOFP : return Instruction::UIToFP;
94 case bitc::CAST_SITOFP : return Instruction::SIToFP;
95 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
96 case bitc::CAST_FPEXT : return Instruction::FPExt;
97 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
98 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
99 case bitc::CAST_BITCAST : return Instruction::BitCast;
102 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
105 case bitc::BINOP_ADD: return Instruction::Add;
106 case bitc::BINOP_SUB: return Instruction::Sub;
107 case bitc::BINOP_MUL: return Instruction::Mul;
108 case bitc::BINOP_UDIV: return Instruction::UDiv;
109 case bitc::BINOP_SDIV:
110 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
111 case bitc::BINOP_UREM: return Instruction::URem;
112 case bitc::BINOP_SREM:
113 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
114 case bitc::BINOP_SHL: return Instruction::Shl;
115 case bitc::BINOP_LSHR: return Instruction::LShr;
116 case bitc::BINOP_ASHR: return Instruction::AShr;
117 case bitc::BINOP_AND: return Instruction::And;
118 case bitc::BINOP_OR: return Instruction::Or;
119 case bitc::BINOP_XOR: return Instruction::Xor;
125 /// @brief A class for maintaining the slot number definition
126 /// as a placeholder for the actual definition for forward constants defs.
127 class ConstantPlaceHolder : public ConstantExpr {
128 ConstantPlaceHolder(); // DO NOT IMPLEMENT
129 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
132 explicit ConstantPlaceHolder(const Type *Ty)
133 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
134 Op(UndefValue::get(Type::Int32Ty), this) {
139 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
142 // Insert a bunch of null values.
144 OperandList = &Uses[0];
148 if (Value *V = Uses[Idx]) {
149 assert(Ty == V->getType() && "Type mismatch in constant table!");
150 return cast<Constant>(V);
153 // Create and return a placeholder, which will later be RAUW'd.
154 Constant *C = new ConstantPlaceHolder(Ty);
155 Uses[Idx].init(C, this);
159 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
161 // Insert a bunch of null values.
163 OperandList = &Uses[0];
167 if (Value *V = Uses[Idx]) {
168 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
172 // No type specified, must be invalid reference.
173 if (Ty == 0) return 0;
175 // Create and return a placeholder, which will later be RAUW'd.
176 Value *V = new Argument(Ty);
177 Uses[Idx].init(V, this);
182 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
183 // If the TypeID is in range, return it.
184 if (ID < TypeList.size())
185 return TypeList[ID].get();
186 if (!isTypeTable) return 0;
188 // The type table allows forward references. Push as many Opaque types as
189 // needed to get up to ID.
190 while (TypeList.size() <= ID)
191 TypeList.push_back(OpaqueType::get());
192 return TypeList.back().get();
195 //===----------------------------------------------------------------------===//
196 // Functions for parsing blocks from the bitcode file
197 //===----------------------------------------------------------------------===//
199 bool BitcodeReader::ParseParamAttrBlock() {
200 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
201 return Error("Malformed block record");
203 if (!ParamAttrs.empty())
204 return Error("Multiple PARAMATTR blocks found!");
206 SmallVector<uint64_t, 64> Record;
208 ParamAttrsVector Attrs;
210 // Read all the records.
212 unsigned Code = Stream.ReadCode();
213 if (Code == bitc::END_BLOCK) {
214 if (Stream.ReadBlockEnd())
215 return Error("Error at end of PARAMATTR block");
219 if (Code == bitc::ENTER_SUBBLOCK) {
220 // No known subblocks, always skip them.
221 Stream.ReadSubBlockID();
222 if (Stream.SkipBlock())
223 return Error("Malformed block record");
227 if (Code == bitc::DEFINE_ABBREV) {
228 Stream.ReadAbbrevRecord();
234 switch (Stream.ReadRecord(Code, Record)) {
235 default: // Default behavior: ignore.
237 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
238 if (Record.size() & 1)
239 return Error("Invalid ENTRY record");
241 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
242 if (Record[i+1] != ParamAttr::None)
243 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
246 ParamAttrs.push_back(0);
248 ParamAttrs.push_back(ParamAttrsList::get(Attrs));
249 ParamAttrs.back()->addRef();
260 bool BitcodeReader::ParseTypeTable() {
261 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
262 return Error("Malformed block record");
264 if (!TypeList.empty())
265 return Error("Multiple TYPE_BLOCKs found!");
267 SmallVector<uint64_t, 64> Record;
268 unsigned NumRecords = 0;
270 // Read all the records for this type table.
272 unsigned Code = Stream.ReadCode();
273 if (Code == bitc::END_BLOCK) {
274 if (NumRecords != TypeList.size())
275 return Error("Invalid type forward reference in TYPE_BLOCK");
276 if (Stream.ReadBlockEnd())
277 return Error("Error at end of type table block");
281 if (Code == bitc::ENTER_SUBBLOCK) {
282 // No known subblocks, always skip them.
283 Stream.ReadSubBlockID();
284 if (Stream.SkipBlock())
285 return Error("Malformed block record");
289 if (Code == bitc::DEFINE_ABBREV) {
290 Stream.ReadAbbrevRecord();
296 const Type *ResultTy = 0;
297 switch (Stream.ReadRecord(Code, Record)) {
298 default: // Default behavior: unknown type.
301 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
302 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
303 // type list. This allows us to reserve space.
304 if (Record.size() < 1)
305 return Error("Invalid TYPE_CODE_NUMENTRY record");
306 TypeList.reserve(Record[0]);
308 case bitc::TYPE_CODE_VOID: // VOID
309 ResultTy = Type::VoidTy;
311 case bitc::TYPE_CODE_FLOAT: // FLOAT
312 ResultTy = Type::FloatTy;
314 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
315 ResultTy = Type::DoubleTy;
317 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
318 ResultTy = Type::X86_FP80Ty;
320 case bitc::TYPE_CODE_FP128: // FP128
321 ResultTy = Type::FP128Ty;
323 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
324 ResultTy = Type::PPC_FP128Ty;
326 case bitc::TYPE_CODE_LABEL: // LABEL
327 ResultTy = Type::LabelTy;
329 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
332 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
333 if (Record.size() < 1)
334 return Error("Invalid Integer type record");
336 ResultTy = IntegerType::get(Record[0]);
338 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
339 // [pointee type, address space]
340 if (Record.size() < 1)
341 return Error("Invalid POINTER type record");
342 unsigned AddressSpace = 0;
343 if (Record.size() == 2)
344 AddressSpace = Record[1];
345 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
348 case bitc::TYPE_CODE_FUNCTION: {
349 // FIXME: attrid is dead, remove it in LLVM 3.0
350 // FUNCTION: [vararg, attrid, retty, paramty x N]
351 if (Record.size() < 3)
352 return Error("Invalid FUNCTION type record");
353 std::vector<const Type*> ArgTys;
354 for (unsigned i = 3, e = Record.size(); i != e; ++i)
355 ArgTys.push_back(getTypeByID(Record[i], true));
357 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
361 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
362 if (Record.size() < 1)
363 return Error("Invalid STRUCT type record");
364 std::vector<const Type*> EltTys;
365 for (unsigned i = 1, e = Record.size(); i != e; ++i)
366 EltTys.push_back(getTypeByID(Record[i], true));
367 ResultTy = StructType::get(EltTys, Record[0]);
370 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
371 if (Record.size() < 2)
372 return Error("Invalid ARRAY type record");
373 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
375 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
376 if (Record.size() < 2)
377 return Error("Invalid VECTOR type record");
378 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
382 if (NumRecords == TypeList.size()) {
383 // If this is a new type slot, just append it.
384 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
386 } else if (ResultTy == 0) {
387 // Otherwise, this was forward referenced, so an opaque type was created,
388 // but the result type is actually just an opaque. Leave the one we
389 // created previously.
392 // Otherwise, this was forward referenced, so an opaque type was created.
393 // Resolve the opaque type to the real type now.
394 assert(NumRecords < TypeList.size() && "Typelist imbalance");
395 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
397 // Don't directly push the new type on the Tab. Instead we want to replace
398 // the opaque type we previously inserted with the new concrete value. The
399 // refinement from the abstract (opaque) type to the new type causes all
400 // uses of the abstract type to use the concrete type (NewTy). This will
401 // also cause the opaque type to be deleted.
402 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
404 // This should have replaced the old opaque type with the new type in the
405 // value table... or with a preexisting type that was already in the
406 // system. Let's just make sure it did.
407 assert(TypeList[NumRecords-1].get() != OldTy &&
408 "refineAbstractType didn't work!");
414 bool BitcodeReader::ParseTypeSymbolTable() {
415 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
416 return Error("Malformed block record");
418 SmallVector<uint64_t, 64> Record;
420 // Read all the records for this type table.
421 std::string TypeName;
423 unsigned Code = Stream.ReadCode();
424 if (Code == bitc::END_BLOCK) {
425 if (Stream.ReadBlockEnd())
426 return Error("Error at end of type symbol table block");
430 if (Code == bitc::ENTER_SUBBLOCK) {
431 // No known subblocks, always skip them.
432 Stream.ReadSubBlockID();
433 if (Stream.SkipBlock())
434 return Error("Malformed block record");
438 if (Code == bitc::DEFINE_ABBREV) {
439 Stream.ReadAbbrevRecord();
445 switch (Stream.ReadRecord(Code, Record)) {
446 default: // Default behavior: unknown type.
448 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
449 if (ConvertToString(Record, 1, TypeName))
450 return Error("Invalid TST_ENTRY record");
451 unsigned TypeID = Record[0];
452 if (TypeID >= TypeList.size())
453 return Error("Invalid Type ID in TST_ENTRY record");
455 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
462 bool BitcodeReader::ParseValueSymbolTable() {
463 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
464 return Error("Malformed block record");
466 SmallVector<uint64_t, 64> Record;
468 // Read all the records for this value table.
469 SmallString<128> ValueName;
471 unsigned Code = Stream.ReadCode();
472 if (Code == bitc::END_BLOCK) {
473 if (Stream.ReadBlockEnd())
474 return Error("Error at end of value symbol table block");
477 if (Code == bitc::ENTER_SUBBLOCK) {
478 // No known subblocks, always skip them.
479 Stream.ReadSubBlockID();
480 if (Stream.SkipBlock())
481 return Error("Malformed block record");
485 if (Code == bitc::DEFINE_ABBREV) {
486 Stream.ReadAbbrevRecord();
492 switch (Stream.ReadRecord(Code, Record)) {
493 default: // Default behavior: unknown type.
495 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
496 if (ConvertToString(Record, 1, ValueName))
497 return Error("Invalid TST_ENTRY record");
498 unsigned ValueID = Record[0];
499 if (ValueID >= ValueList.size())
500 return Error("Invalid Value ID in VST_ENTRY record");
501 Value *V = ValueList[ValueID];
503 V->setName(&ValueName[0], ValueName.size());
507 case bitc::VST_CODE_BBENTRY: {
508 if (ConvertToString(Record, 1, ValueName))
509 return Error("Invalid VST_BBENTRY record");
510 BasicBlock *BB = getBasicBlock(Record[0]);
512 return Error("Invalid BB ID in VST_BBENTRY record");
514 BB->setName(&ValueName[0], ValueName.size());
522 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
523 /// the LSB for dense VBR encoding.
524 static uint64_t DecodeSignRotatedValue(uint64_t V) {
529 // There is no such thing as -0 with integers. "-0" really means MININT.
533 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
534 /// values and aliases that we can.
535 bool BitcodeReader::ResolveGlobalAndAliasInits() {
536 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
537 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
539 GlobalInitWorklist.swap(GlobalInits);
540 AliasInitWorklist.swap(AliasInits);
542 while (!GlobalInitWorklist.empty()) {
543 unsigned ValID = GlobalInitWorklist.back().second;
544 if (ValID >= ValueList.size()) {
545 // Not ready to resolve this yet, it requires something later in the file.
546 GlobalInits.push_back(GlobalInitWorklist.back());
548 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
549 GlobalInitWorklist.back().first->setInitializer(C);
551 return Error("Global variable initializer is not a constant!");
553 GlobalInitWorklist.pop_back();
556 while (!AliasInitWorklist.empty()) {
557 unsigned ValID = AliasInitWorklist.back().second;
558 if (ValID >= ValueList.size()) {
559 AliasInits.push_back(AliasInitWorklist.back());
561 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
562 AliasInitWorklist.back().first->setAliasee(C);
564 return Error("Alias initializer is not a constant!");
566 AliasInitWorklist.pop_back();
572 bool BitcodeReader::ParseConstants() {
573 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
574 return Error("Malformed block record");
576 SmallVector<uint64_t, 64> Record;
578 // Read all the records for this value table.
579 const Type *CurTy = Type::Int32Ty;
580 unsigned NextCstNo = ValueList.size();
582 unsigned Code = Stream.ReadCode();
583 if (Code == bitc::END_BLOCK) {
584 if (NextCstNo != ValueList.size())
585 return Error("Invalid constant reference!");
587 if (Stream.ReadBlockEnd())
588 return Error("Error at end of constants block");
592 if (Code == bitc::ENTER_SUBBLOCK) {
593 // No known subblocks, always skip them.
594 Stream.ReadSubBlockID();
595 if (Stream.SkipBlock())
596 return Error("Malformed block record");
600 if (Code == bitc::DEFINE_ABBREV) {
601 Stream.ReadAbbrevRecord();
608 switch (Stream.ReadRecord(Code, Record)) {
609 default: // Default behavior: unknown constant
610 case bitc::CST_CODE_UNDEF: // UNDEF
611 V = UndefValue::get(CurTy);
613 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
615 return Error("Malformed CST_SETTYPE record");
616 if (Record[0] >= TypeList.size())
617 return Error("Invalid Type ID in CST_SETTYPE record");
618 CurTy = TypeList[Record[0]];
619 continue; // Skip the ValueList manipulation.
620 case bitc::CST_CODE_NULL: // NULL
621 V = Constant::getNullValue(CurTy);
623 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
624 if (!isa<IntegerType>(CurTy) || Record.empty())
625 return Error("Invalid CST_INTEGER record");
626 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
628 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
629 if (!isa<IntegerType>(CurTy) || Record.empty())
630 return Error("Invalid WIDE_INTEGER record");
632 unsigned NumWords = Record.size();
633 SmallVector<uint64_t, 8> Words;
634 Words.resize(NumWords);
635 for (unsigned i = 0; i != NumWords; ++i)
636 Words[i] = DecodeSignRotatedValue(Record[i]);
637 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
638 NumWords, &Words[0]));
641 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
643 return Error("Invalid FLOAT record");
644 if (CurTy == Type::FloatTy)
645 V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
646 else if (CurTy == Type::DoubleTy)
647 V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
648 else if (CurTy == Type::X86_FP80Ty)
649 V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
650 else if (CurTy == Type::FP128Ty)
651 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true));
652 else if (CurTy == Type::PPC_FP128Ty)
653 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
655 V = UndefValue::get(CurTy);
659 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
661 return Error("Invalid CST_AGGREGATE record");
663 unsigned Size = Record.size();
664 std::vector<Constant*> Elts;
666 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
667 for (unsigned i = 0; i != Size; ++i)
668 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
669 STy->getElementType(i)));
670 V = ConstantStruct::get(STy, Elts);
671 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
672 const Type *EltTy = ATy->getElementType();
673 for (unsigned i = 0; i != Size; ++i)
674 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
675 V = ConstantArray::get(ATy, Elts);
676 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
677 const Type *EltTy = VTy->getElementType();
678 for (unsigned i = 0; i != Size; ++i)
679 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
680 V = ConstantVector::get(Elts);
682 V = UndefValue::get(CurTy);
686 case bitc::CST_CODE_STRING: { // STRING: [values]
688 return Error("Invalid CST_AGGREGATE record");
690 const ArrayType *ATy = cast<ArrayType>(CurTy);
691 const Type *EltTy = ATy->getElementType();
693 unsigned Size = Record.size();
694 std::vector<Constant*> Elts;
695 for (unsigned i = 0; i != Size; ++i)
696 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
697 V = ConstantArray::get(ATy, Elts);
700 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
702 return Error("Invalid CST_AGGREGATE record");
704 const ArrayType *ATy = cast<ArrayType>(CurTy);
705 const Type *EltTy = ATy->getElementType();
707 unsigned Size = Record.size();
708 std::vector<Constant*> Elts;
709 for (unsigned i = 0; i != Size; ++i)
710 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
711 Elts.push_back(Constant::getNullValue(EltTy));
712 V = ConstantArray::get(ATy, Elts);
715 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
716 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
717 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
719 V = UndefValue::get(CurTy); // Unknown binop.
721 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
722 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
723 V = ConstantExpr::get(Opc, LHS, RHS);
727 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
728 if (Record.size() < 3) return Error("Invalid CE_CAST record");
729 int Opc = GetDecodedCastOpcode(Record[0]);
731 V = UndefValue::get(CurTy); // Unknown cast.
733 const Type *OpTy = getTypeByID(Record[1]);
734 if (!OpTy) return Error("Invalid CE_CAST record");
735 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
736 V = ConstantExpr::getCast(Opc, Op, CurTy);
740 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
741 if (Record.size() & 1) return Error("Invalid CE_GEP record");
742 SmallVector<Constant*, 16> Elts;
743 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
744 const Type *ElTy = getTypeByID(Record[i]);
745 if (!ElTy) return Error("Invalid CE_GEP record");
746 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
748 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
751 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
752 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
753 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
755 ValueList.getConstantFwdRef(Record[1],CurTy),
756 ValueList.getConstantFwdRef(Record[2],CurTy));
758 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
759 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
760 const VectorType *OpTy =
761 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
762 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
763 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
764 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
765 OpTy->getElementType());
766 V = ConstantExpr::getExtractElement(Op0, Op1);
769 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
770 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
771 if (Record.size() < 3 || OpTy == 0)
772 return Error("Invalid CE_INSERTELT record");
773 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
774 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
775 OpTy->getElementType());
776 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
777 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
780 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
781 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
782 if (Record.size() < 3 || OpTy == 0)
783 return Error("Invalid CE_INSERTELT record");
784 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
785 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
786 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
787 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
788 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
791 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
792 if (Record.size() < 4) return Error("Invalid CE_CMP record");
793 const Type *OpTy = getTypeByID(Record[0]);
794 if (OpTy == 0) return Error("Invalid CE_CMP record");
795 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
796 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
798 if (OpTy->isFloatingPoint())
799 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
801 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
804 case bitc::CST_CODE_INLINEASM: {
805 if (Record.size() < 2) return Error("Invalid INLINEASM record");
806 std::string AsmStr, ConstrStr;
807 bool HasSideEffects = Record[0];
808 unsigned AsmStrSize = Record[1];
809 if (2+AsmStrSize >= Record.size())
810 return Error("Invalid INLINEASM record");
811 unsigned ConstStrSize = Record[2+AsmStrSize];
812 if (3+AsmStrSize+ConstStrSize > Record.size())
813 return Error("Invalid INLINEASM record");
815 for (unsigned i = 0; i != AsmStrSize; ++i)
816 AsmStr += (char)Record[2+i];
817 for (unsigned i = 0; i != ConstStrSize; ++i)
818 ConstrStr += (char)Record[3+AsmStrSize+i];
819 const PointerType *PTy = cast<PointerType>(CurTy);
820 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
821 AsmStr, ConstrStr, HasSideEffects);
826 ValueList.AssignValue(V, NextCstNo);
831 /// RememberAndSkipFunctionBody - When we see the block for a function body,
832 /// remember where it is and then skip it. This lets us lazily deserialize the
834 bool BitcodeReader::RememberAndSkipFunctionBody() {
835 // Get the function we are talking about.
836 if (FunctionsWithBodies.empty())
837 return Error("Insufficient function protos");
839 Function *Fn = FunctionsWithBodies.back();
840 FunctionsWithBodies.pop_back();
842 // Save the current stream state.
843 uint64_t CurBit = Stream.GetCurrentBitNo();
844 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
846 // Set the functions linkage to GhostLinkage so we know it is lazily
848 Fn->setLinkage(GlobalValue::GhostLinkage);
850 // Skip over the function block for now.
851 if (Stream.SkipBlock())
852 return Error("Malformed block record");
856 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
857 // Reject multiple MODULE_BLOCK's in a single bitstream.
859 return Error("Multiple MODULE_BLOCKs in same stream");
861 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
862 return Error("Malformed block record");
864 // Otherwise, create the module.
865 TheModule = new Module(ModuleID);
867 SmallVector<uint64_t, 64> Record;
868 std::vector<std::string> SectionTable;
869 std::vector<std::string> CollectorTable;
871 // Read all the records for this module.
872 while (!Stream.AtEndOfStream()) {
873 unsigned Code = Stream.ReadCode();
874 if (Code == bitc::END_BLOCK) {
875 if (Stream.ReadBlockEnd())
876 return Error("Error at end of module block");
878 // Patch the initializers for globals and aliases up.
879 ResolveGlobalAndAliasInits();
880 if (!GlobalInits.empty() || !AliasInits.empty())
881 return Error("Malformed global initializer set");
882 if (!FunctionsWithBodies.empty())
883 return Error("Too few function bodies found");
885 // Look for intrinsic functions which need to be upgraded at some point
886 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
889 if (UpgradeIntrinsicFunction(FI, NewFn))
890 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
893 // Force deallocation of memory for these vectors to favor the client that
894 // want lazy deserialization.
895 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
896 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
897 std::vector<Function*>().swap(FunctionsWithBodies);
901 if (Code == bitc::ENTER_SUBBLOCK) {
902 switch (Stream.ReadSubBlockID()) {
903 default: // Skip unknown content.
904 if (Stream.SkipBlock())
905 return Error("Malformed block record");
907 case bitc::BLOCKINFO_BLOCK_ID:
908 if (Stream.ReadBlockInfoBlock())
909 return Error("Malformed BlockInfoBlock");
911 case bitc::PARAMATTR_BLOCK_ID:
912 if (ParseParamAttrBlock())
915 case bitc::TYPE_BLOCK_ID:
916 if (ParseTypeTable())
919 case bitc::TYPE_SYMTAB_BLOCK_ID:
920 if (ParseTypeSymbolTable())
923 case bitc::VALUE_SYMTAB_BLOCK_ID:
924 if (ParseValueSymbolTable())
927 case bitc::CONSTANTS_BLOCK_ID:
928 if (ParseConstants() || ResolveGlobalAndAliasInits())
931 case bitc::FUNCTION_BLOCK_ID:
932 // If this is the first function body we've seen, reverse the
933 // FunctionsWithBodies list.
934 if (!HasReversedFunctionsWithBodies) {
935 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
936 HasReversedFunctionsWithBodies = true;
939 if (RememberAndSkipFunctionBody())
946 if (Code == bitc::DEFINE_ABBREV) {
947 Stream.ReadAbbrevRecord();
952 switch (Stream.ReadRecord(Code, Record)) {
953 default: break; // Default behavior, ignore unknown content.
954 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
955 if (Record.size() < 1)
956 return Error("Malformed MODULE_CODE_VERSION");
957 // Only version #0 is supported so far.
959 return Error("Unknown bitstream version!");
961 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
963 if (ConvertToString(Record, 0, S))
964 return Error("Invalid MODULE_CODE_TRIPLE record");
965 TheModule->setTargetTriple(S);
968 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
970 if (ConvertToString(Record, 0, S))
971 return Error("Invalid MODULE_CODE_DATALAYOUT record");
972 TheModule->setDataLayout(S);
975 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
977 if (ConvertToString(Record, 0, S))
978 return Error("Invalid MODULE_CODE_ASM record");
979 TheModule->setModuleInlineAsm(S);
982 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
984 if (ConvertToString(Record, 0, S))
985 return Error("Invalid MODULE_CODE_DEPLIB record");
986 TheModule->addLibrary(S);
989 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
991 if (ConvertToString(Record, 0, S))
992 return Error("Invalid MODULE_CODE_SECTIONNAME record");
993 SectionTable.push_back(S);
996 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
998 if (ConvertToString(Record, 0, S))
999 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
1000 CollectorTable.push_back(S);
1003 // GLOBALVAR: [pointer type, isconst, initid,
1004 // linkage, alignment, section, visibility, threadlocal]
1005 case bitc::MODULE_CODE_GLOBALVAR: {
1006 if (Record.size() < 6)
1007 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1008 const Type *Ty = getTypeByID(Record[0]);
1009 if (!isa<PointerType>(Ty))
1010 return Error("Global not a pointer type!");
1011 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1012 Ty = cast<PointerType>(Ty)->getElementType();
1014 bool isConstant = Record[1];
1015 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1016 unsigned Alignment = (1 << Record[4]) >> 1;
1017 std::string Section;
1019 if (Record[5]-1 >= SectionTable.size())
1020 return Error("Invalid section ID");
1021 Section = SectionTable[Record[5]-1];
1023 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1024 if (Record.size() > 6)
1025 Visibility = GetDecodedVisibility(Record[6]);
1026 bool isThreadLocal = false;
1027 if (Record.size() > 7)
1028 isThreadLocal = Record[7];
1030 GlobalVariable *NewGV =
1031 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1032 isThreadLocal, AddressSpace);
1033 NewGV->setAlignment(Alignment);
1034 if (!Section.empty())
1035 NewGV->setSection(Section);
1036 NewGV->setVisibility(Visibility);
1037 NewGV->setThreadLocal(isThreadLocal);
1039 ValueList.push_back(NewGV);
1041 // Remember which value to use for the global initializer.
1042 if (unsigned InitID = Record[2])
1043 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1046 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1047 // alignment, section, visibility, collector]
1048 case bitc::MODULE_CODE_FUNCTION: {
1049 if (Record.size() < 8)
1050 return Error("Invalid MODULE_CODE_FUNCTION record");
1051 const Type *Ty = getTypeByID(Record[0]);
1052 if (!isa<PointerType>(Ty))
1053 return Error("Function not a pointer type!");
1054 const FunctionType *FTy =
1055 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1057 return Error("Function not a pointer to function type!");
1059 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1062 Func->setCallingConv(Record[1]);
1063 bool isProto = Record[2];
1064 Func->setLinkage(GetDecodedLinkage(Record[3]));
1065 const ParamAttrsList *PAL = getParamAttrs(Record[4]);
1066 Func->setParamAttrs(PAL);
1068 Func->setAlignment((1 << Record[5]) >> 1);
1070 if (Record[6]-1 >= SectionTable.size())
1071 return Error("Invalid section ID");
1072 Func->setSection(SectionTable[Record[6]-1]);
1074 Func->setVisibility(GetDecodedVisibility(Record[7]));
1075 if (Record.size() > 8 && Record[8]) {
1076 if (Record[8]-1 > CollectorTable.size())
1077 return Error("Invalid collector ID");
1078 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1081 ValueList.push_back(Func);
1083 // If this is a function with a body, remember the prototype we are
1084 // creating now, so that we can match up the body with them later.
1086 FunctionsWithBodies.push_back(Func);
1089 // ALIAS: [alias type, aliasee val#, linkage]
1090 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1091 case bitc::MODULE_CODE_ALIAS: {
1092 if (Record.size() < 3)
1093 return Error("Invalid MODULE_ALIAS record");
1094 const Type *Ty = getTypeByID(Record[0]);
1095 if (!isa<PointerType>(Ty))
1096 return Error("Function not a pointer type!");
1098 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1100 // Old bitcode files didn't have visibility field.
1101 if (Record.size() > 3)
1102 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1103 ValueList.push_back(NewGA);
1104 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1107 /// MODULE_CODE_PURGEVALS: [numvals]
1108 case bitc::MODULE_CODE_PURGEVALS:
1109 // Trim down the value list to the specified size.
1110 if (Record.size() < 1 || Record[0] > ValueList.size())
1111 return Error("Invalid MODULE_PURGEVALS record");
1112 ValueList.shrinkTo(Record[0]);
1118 return Error("Premature end of bitstream");
1122 bool BitcodeReader::ParseBitcode() {
1125 if (Buffer->getBufferSize() & 3)
1126 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1128 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1129 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1131 // Sniff for the signature.
1132 if (Stream.Read(8) != 'B' ||
1133 Stream.Read(8) != 'C' ||
1134 Stream.Read(4) != 0x0 ||
1135 Stream.Read(4) != 0xC ||
1136 Stream.Read(4) != 0xE ||
1137 Stream.Read(4) != 0xD)
1138 return Error("Invalid bitcode signature");
1140 // We expect a number of well-defined blocks, though we don't necessarily
1141 // need to understand them all.
1142 while (!Stream.AtEndOfStream()) {
1143 unsigned Code = Stream.ReadCode();
1145 if (Code != bitc::ENTER_SUBBLOCK)
1146 return Error("Invalid record at top-level");
1148 unsigned BlockID = Stream.ReadSubBlockID();
1150 // We only know the MODULE subblock ID.
1152 case bitc::BLOCKINFO_BLOCK_ID:
1153 if (Stream.ReadBlockInfoBlock())
1154 return Error("Malformed BlockInfoBlock");
1156 case bitc::MODULE_BLOCK_ID:
1157 if (ParseModule(Buffer->getBufferIdentifier()))
1161 if (Stream.SkipBlock())
1162 return Error("Malformed block record");
1171 /// ParseFunctionBody - Lazily parse the specified function body block.
1172 bool BitcodeReader::ParseFunctionBody(Function *F) {
1173 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1174 return Error("Malformed block record");
1176 unsigned ModuleValueListSize = ValueList.size();
1178 // Add all the function arguments to the value table.
1179 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1180 ValueList.push_back(I);
1182 unsigned NextValueNo = ValueList.size();
1183 BasicBlock *CurBB = 0;
1184 unsigned CurBBNo = 0;
1186 // Read all the records.
1187 SmallVector<uint64_t, 64> Record;
1189 unsigned Code = Stream.ReadCode();
1190 if (Code == bitc::END_BLOCK) {
1191 if (Stream.ReadBlockEnd())
1192 return Error("Error at end of function block");
1196 if (Code == bitc::ENTER_SUBBLOCK) {
1197 switch (Stream.ReadSubBlockID()) {
1198 default: // Skip unknown content.
1199 if (Stream.SkipBlock())
1200 return Error("Malformed block record");
1202 case bitc::CONSTANTS_BLOCK_ID:
1203 if (ParseConstants()) return true;
1204 NextValueNo = ValueList.size();
1206 case bitc::VALUE_SYMTAB_BLOCK_ID:
1207 if (ParseValueSymbolTable()) return true;
1213 if (Code == bitc::DEFINE_ABBREV) {
1214 Stream.ReadAbbrevRecord();
1221 switch (Stream.ReadRecord(Code, Record)) {
1222 default: // Default behavior: reject
1223 return Error("Unknown instruction");
1224 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1225 if (Record.size() < 1 || Record[0] == 0)
1226 return Error("Invalid DECLAREBLOCKS record");
1227 // Create all the basic blocks for the function.
1228 FunctionBBs.resize(Record[0]);
1229 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1230 FunctionBBs[i] = new BasicBlock("", F);
1231 CurBB = FunctionBBs[0];
1234 case bitc::FUNC_CODE_INST_BB_UNWINDDEST: // BB_UNWINDDEST: [bb#]
1235 if (CurBB->getUnwindDest())
1236 return Error("Only permit one BB_UNWINDDEST per BB");
1237 if (Record.size() != 1)
1238 return Error("Invalid BB_UNWINDDEST record");
1240 CurBB->setUnwindDest(getBasicBlock(Record[0]));
1243 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1246 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1247 getValue(Record, OpNum, LHS->getType(), RHS) ||
1248 OpNum+1 != Record.size())
1249 return Error("Invalid BINOP record");
1251 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1252 if (Opc == -1) return Error("Invalid BINOP record");
1253 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1256 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1259 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1260 OpNum+2 != Record.size())
1261 return Error("Invalid CAST record");
1263 const Type *ResTy = getTypeByID(Record[OpNum]);
1264 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1265 if (Opc == -1 || ResTy == 0)
1266 return Error("Invalid CAST record");
1267 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1270 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1273 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1274 return Error("Invalid GEP record");
1276 SmallVector<Value*, 16> GEPIdx;
1277 while (OpNum != Record.size()) {
1279 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1280 return Error("Invalid GEP record");
1281 GEPIdx.push_back(Op);
1284 I = new GetElementPtrInst(BasePtr, GEPIdx.begin(), GEPIdx.end());
1288 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1290 Value *TrueVal, *FalseVal, *Cond;
1291 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1292 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1293 getValue(Record, OpNum, Type::Int1Ty, Cond))
1294 return Error("Invalid SELECT record");
1296 I = new SelectInst(Cond, TrueVal, FalseVal);
1300 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1303 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1304 getValue(Record, OpNum, Type::Int32Ty, Idx))
1305 return Error("Invalid EXTRACTELT record");
1306 I = new ExtractElementInst(Vec, Idx);
1310 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1312 Value *Vec, *Elt, *Idx;
1313 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1314 getValue(Record, OpNum,
1315 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1316 getValue(Record, OpNum, Type::Int32Ty, Idx))
1317 return Error("Invalid INSERTELT record");
1318 I = new InsertElementInst(Vec, Elt, Idx);
1322 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1324 Value *Vec1, *Vec2, *Mask;
1325 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1326 getValue(Record, OpNum, Vec1->getType(), Vec2))
1327 return Error("Invalid SHUFFLEVEC record");
1329 const Type *MaskTy =
1330 VectorType::get(Type::Int32Ty,
1331 cast<VectorType>(Vec1->getType())->getNumElements());
1333 if (getValue(Record, OpNum, MaskTy, Mask))
1334 return Error("Invalid SHUFFLEVEC record");
1335 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1339 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1342 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1343 getValue(Record, OpNum, LHS->getType(), RHS) ||
1344 OpNum+1 != Record.size())
1345 return Error("Invalid CMP record");
1347 if (LHS->getType()->isFPOrFPVector())
1348 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1350 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1353 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1354 if (Record.size() != 2)
1355 return Error("Invalid GETRESULT record");
1358 getValueTypePair(Record, OpNum, NextValueNo, Op);
1359 unsigned Index = Record[1];
1360 I = new GetResultInst(Op, Index);
1364 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1366 unsigned Size = Record.size();
1368 I = new ReturnInst();
1372 SmallVector<Value *,4> Vs;
1375 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1376 return Error("Invalid RET record");
1378 } while(OpNum != Record.size());
1380 // SmallVector Vs has at least one element.
1381 I = new ReturnInst(&Vs[0], Vs.size());
1385 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1386 if (Record.size() != 1 && Record.size() != 3)
1387 return Error("Invalid BR record");
1388 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1390 return Error("Invalid BR record");
1392 if (Record.size() == 1)
1393 I = new BranchInst(TrueDest);
1395 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1396 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1397 if (FalseDest == 0 || Cond == 0)
1398 return Error("Invalid BR record");
1399 I = new BranchInst(TrueDest, FalseDest, Cond);
1403 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1404 if (Record.size() < 3 || (Record.size() & 1) == 0)
1405 return Error("Invalid SWITCH record");
1406 const Type *OpTy = getTypeByID(Record[0]);
1407 Value *Cond = getFnValueByID(Record[1], OpTy);
1408 BasicBlock *Default = getBasicBlock(Record[2]);
1409 if (OpTy == 0 || Cond == 0 || Default == 0)
1410 return Error("Invalid SWITCH record");
1411 unsigned NumCases = (Record.size()-3)/2;
1412 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1413 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1414 ConstantInt *CaseVal =
1415 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1416 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1417 if (CaseVal == 0 || DestBB == 0) {
1419 return Error("Invalid SWITCH record!");
1421 SI->addCase(CaseVal, DestBB);
1427 case bitc::FUNC_CODE_INST_INVOKE: {
1428 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1429 if (Record.size() < 4) return Error("Invalid INVOKE record");
1430 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
1431 unsigned CCInfo = Record[1];
1432 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1433 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1437 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1438 return Error("Invalid INVOKE record");
1440 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1441 const FunctionType *FTy = !CalleeTy ? 0 :
1442 dyn_cast<FunctionType>(CalleeTy->getElementType());
1444 // Check that the right number of fixed parameters are here.
1445 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1446 Record.size() < OpNum+FTy->getNumParams())
1447 return Error("Invalid INVOKE record");
1449 SmallVector<Value*, 16> Ops;
1450 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1451 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1452 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1455 if (!FTy->isVarArg()) {
1456 if (Record.size() != OpNum)
1457 return Error("Invalid INVOKE record");
1459 // Read type/value pairs for varargs params.
1460 while (OpNum != Record.size()) {
1462 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1463 return Error("Invalid INVOKE record");
1468 I = new InvokeInst(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
1469 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1470 cast<InvokeInst>(I)->setParamAttrs(PAL);
1473 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1474 I = new UnwindInst();
1476 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1477 I = new UnreachableInst();
1479 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1480 if (Record.size() < 1 || ((Record.size()-1)&1))
1481 return Error("Invalid PHI record");
1482 const Type *Ty = getTypeByID(Record[0]);
1483 if (!Ty) return Error("Invalid PHI record");
1485 PHINode *PN = new PHINode(Ty);
1486 PN->reserveOperandSpace(Record.size()-1);
1488 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1489 Value *V = getFnValueByID(Record[1+i], Ty);
1490 BasicBlock *BB = getBasicBlock(Record[2+i]);
1491 if (!V || !BB) return Error("Invalid PHI record");
1492 PN->addIncoming(V, BB);
1498 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1499 if (Record.size() < 3)
1500 return Error("Invalid MALLOC record");
1501 const PointerType *Ty =
1502 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1503 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1504 unsigned Align = Record[2];
1505 if (!Ty || !Size) return Error("Invalid MALLOC record");
1506 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1509 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1512 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1513 OpNum != Record.size())
1514 return Error("Invalid FREE record");
1515 I = new FreeInst(Op);
1518 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1519 if (Record.size() < 3)
1520 return Error("Invalid ALLOCA record");
1521 const PointerType *Ty =
1522 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1523 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1524 unsigned Align = Record[2];
1525 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1526 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1529 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1532 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1533 OpNum+2 != Record.size())
1534 return Error("Invalid LOAD record");
1536 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1539 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1542 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1543 getValue(Record, OpNum,
1544 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1545 OpNum+2 != Record.size())
1546 return Error("Invalid STORE record");
1548 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1551 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1552 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1555 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1556 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
1557 OpNum+2 != Record.size())
1558 return Error("Invalid STORE record");
1560 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1563 case bitc::FUNC_CODE_INST_CALL: {
1564 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1565 if (Record.size() < 3)
1566 return Error("Invalid CALL record");
1568 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
1569 unsigned CCInfo = Record[1];
1573 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1574 return Error("Invalid CALL record");
1576 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1577 const FunctionType *FTy = 0;
1578 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1579 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1580 return Error("Invalid CALL record");
1582 SmallVector<Value*, 16> Args;
1583 // Read the fixed params.
1584 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1585 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1586 Args.push_back(getBasicBlock(Record[OpNum]));
1588 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1589 if (Args.back() == 0) return Error("Invalid CALL record");
1592 // Read type/value pairs for varargs params.
1593 if (!FTy->isVarArg()) {
1594 if (OpNum != Record.size())
1595 return Error("Invalid CALL record");
1597 while (OpNum != Record.size()) {
1599 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1600 return Error("Invalid CALL record");
1605 I = new CallInst(Callee, Args.begin(), Args.end());
1606 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1607 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1608 cast<CallInst>(I)->setParamAttrs(PAL);
1611 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1612 if (Record.size() < 3)
1613 return Error("Invalid VAARG record");
1614 const Type *OpTy = getTypeByID(Record[0]);
1615 Value *Op = getFnValueByID(Record[1], OpTy);
1616 const Type *ResTy = getTypeByID(Record[2]);
1617 if (!OpTy || !Op || !ResTy)
1618 return Error("Invalid VAARG record");
1619 I = new VAArgInst(Op, ResTy);
1624 // Add instruction to end of current BB. If there is no current BB, reject
1628 return Error("Invalid instruction with no BB");
1630 CurBB->getInstList().push_back(I);
1632 // If this was a terminator instruction, move to the next block.
1633 if (isa<TerminatorInst>(I)) {
1635 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1638 // Non-void values get registered in the value table for future use.
1639 if (I && I->getType() != Type::VoidTy)
1640 ValueList.AssignValue(I, NextValueNo++);
1643 // Check the function list for unresolved values.
1644 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1645 if (A->getParent() == 0) {
1646 // We found at least one unresolved value. Nuke them all to avoid leaks.
1647 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1648 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1649 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1653 return Error("Never resolved value found in function!");
1657 // Trim the value list down to the size it was before we parsed this function.
1658 ValueList.shrinkTo(ModuleValueListSize);
1659 std::vector<BasicBlock*>().swap(FunctionBBs);
1664 //===----------------------------------------------------------------------===//
1665 // ModuleProvider implementation
1666 //===----------------------------------------------------------------------===//
1669 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1670 // If it already is material, ignore the request.
1671 if (!F->hasNotBeenReadFromBitcode()) return false;
1673 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1674 DeferredFunctionInfo.find(F);
1675 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1677 // Move the bit stream to the saved position of the deferred function body and
1678 // restore the real linkage type for the function.
1679 Stream.JumpToBit(DFII->second.first);
1680 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1682 if (ParseFunctionBody(F)) {
1683 if (ErrInfo) *ErrInfo = ErrorString;
1687 // Upgrade any old intrinsic calls in the function.
1688 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1689 E = UpgradedIntrinsics.end(); I != E; ++I) {
1690 if (I->first != I->second) {
1691 for (Value::use_iterator UI = I->first->use_begin(),
1692 UE = I->first->use_end(); UI != UE; ) {
1693 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1694 UpgradeIntrinsicCall(CI, I->second);
1702 void BitcodeReader::dematerializeFunction(Function *F) {
1703 // If this function isn't materialized, or if it is a proto, this is a noop.
1704 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1707 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1709 // Just forget the function body, we can remat it later.
1711 F->setLinkage(GlobalValue::GhostLinkage);
1715 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1716 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1717 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1719 Function *F = I->first;
1720 if (F->hasNotBeenReadFromBitcode() &&
1721 materializeFunction(F, ErrInfo))
1725 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1726 // delete the old functions to clean up. We can't do this unless the entire
1727 // module is materialized because there could always be another function body
1728 // with calls to the old function.
1729 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1730 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1731 if (I->first != I->second) {
1732 for (Value::use_iterator UI = I->first->use_begin(),
1733 UE = I->first->use_end(); UI != UE; ) {
1734 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1735 UpgradeIntrinsicCall(CI, I->second);
1737 ValueList.replaceUsesOfWith(I->first, I->second);
1738 I->first->eraseFromParent();
1741 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1747 /// This method is provided by the parent ModuleProvde class and overriden
1748 /// here. It simply releases the module from its provided and frees up our
1750 /// @brief Release our hold on the generated module
1751 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1752 // Since we're losing control of this Module, we must hand it back complete
1753 Module *M = ModuleProvider::releaseModule(ErrInfo);
1759 //===----------------------------------------------------------------------===//
1760 // External interface
1761 //===----------------------------------------------------------------------===//
1763 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1765 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1766 std::string *ErrMsg) {
1767 BitcodeReader *R = new BitcodeReader(Buffer);
1768 if (R->ParseBitcode()) {
1770 *ErrMsg = R->getErrorString();
1772 // Don't let the BitcodeReader dtor delete 'Buffer'.
1773 R->releaseMemoryBuffer();
1780 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1781 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1782 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1784 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1787 // Read in the entire module.
1788 Module *M = R->materializeModule(ErrMsg);
1790 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1791 // there was an error.
1792 R->releaseMemoryBuffer();
1794 // If there was no error, tell ModuleProvider not to delete it when its dtor
1797 M = R->releaseModule(ErrMsg);