1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/MemoryBuffer.h"
25 BitcodeReader::~BitcodeReader() {
30 /// ConvertToString - Convert a string from a record into an std::string, return
32 template<typename StrTy>
33 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
35 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
38 for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
39 Result += (char)Record[Idx+i+1];
43 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
45 default: // Map unknown/new linkages to external
46 case 0: return GlobalValue::ExternalLinkage;
47 case 1: return GlobalValue::WeakLinkage;
48 case 2: return GlobalValue::AppendingLinkage;
49 case 3: return GlobalValue::InternalLinkage;
50 case 4: return GlobalValue::LinkOnceLinkage;
51 case 5: return GlobalValue::DLLImportLinkage;
52 case 6: return GlobalValue::DLLExportLinkage;
53 case 7: return GlobalValue::ExternalWeakLinkage;
57 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
59 default: // Map unknown visibilities to default.
60 case 0: return GlobalValue::DefaultVisibility;
61 case 1: return GlobalValue::HiddenVisibility;
62 case 2: return GlobalValue::ProtectedVisibility;
66 static int GetDecodedCastOpcode(unsigned Val) {
69 case bitc::CAST_TRUNC : return Instruction::Trunc;
70 case bitc::CAST_ZEXT : return Instruction::ZExt;
71 case bitc::CAST_SEXT : return Instruction::SExt;
72 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
73 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
74 case bitc::CAST_UITOFP : return Instruction::UIToFP;
75 case bitc::CAST_SITOFP : return Instruction::SIToFP;
76 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
77 case bitc::CAST_FPEXT : return Instruction::FPExt;
78 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
79 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
80 case bitc::CAST_BITCAST : return Instruction::BitCast;
83 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
86 case bitc::BINOP_ADD: return Instruction::Add;
87 case bitc::BINOP_SUB: return Instruction::Sub;
88 case bitc::BINOP_MUL: return Instruction::Mul;
89 case bitc::BINOP_UDIV: return Instruction::UDiv;
90 case bitc::BINOP_SDIV:
91 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
92 case bitc::BINOP_UREM: return Instruction::URem;
93 case bitc::BINOP_SREM:
94 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
95 case bitc::BINOP_SHL: return Instruction::Shl;
96 case bitc::BINOP_LSHR: return Instruction::LShr;
97 case bitc::BINOP_ASHR: return Instruction::AShr;
98 case bitc::BINOP_AND: return Instruction::And;
99 case bitc::BINOP_OR: return Instruction::Or;
100 case bitc::BINOP_XOR: return Instruction::Xor;
106 /// @brief A class for maintaining the slot number definition
107 /// as a placeholder for the actual definition for forward constants defs.
108 class ConstantPlaceHolder : public ConstantExpr {
109 ConstantPlaceHolder(); // DO NOT IMPLEMENT
110 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
113 ConstantPlaceHolder(const Type *Ty)
114 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
115 Op(UndefValue::get(Type::Int32Ty), this) {
120 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
123 // Insert a bunch of null values.
125 OperandList = &Uses[0];
129 if (Value *V = Uses[Idx]) {
130 assert(Ty == V->getType() && "Type mismatch in constant table!");
131 return cast<Constant>(V);
134 // Create and return a placeholder, which will later be RAUW'd.
135 Constant *C = new ConstantPlaceHolder(Ty);
136 Uses[Idx].init(C, this);
140 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
142 // Insert a bunch of null values.
144 OperandList = &Uses[0];
148 if (Value *V = Uses[Idx]) {
149 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
153 // No type specified, must be invalid reference.
154 if (Ty == 0) return 0;
156 // Create and return a placeholder, which will later be RAUW'd.
157 Value *V = new Argument(Ty);
158 Uses[Idx].init(V, this);
163 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
164 // If the TypeID is in range, return it.
165 if (ID < TypeList.size())
166 return TypeList[ID].get();
167 if (!isTypeTable) return 0;
169 // The type table allows forward references. Push as many Opaque types as
170 // needed to get up to ID.
171 while (TypeList.size() <= ID)
172 TypeList.push_back(OpaqueType::get());
173 return TypeList.back().get();
176 bool BitcodeReader::ParseTypeTable() {
177 if (Stream.EnterSubBlock())
178 return Error("Malformed block record");
180 if (!TypeList.empty())
181 return Error("Multiple TYPE_BLOCKs found!");
183 SmallVector<uint64_t, 64> Record;
184 unsigned NumRecords = 0;
186 // Read all the records for this type table.
188 unsigned Code = Stream.ReadCode();
189 if (Code == bitc::END_BLOCK) {
190 if (NumRecords != TypeList.size())
191 return Error("Invalid type forward reference in TYPE_BLOCK");
192 if (Stream.ReadBlockEnd())
193 return Error("Error at end of type table block");
197 if (Code == bitc::ENTER_SUBBLOCK) {
198 // No known subblocks, always skip them.
199 Stream.ReadSubBlockID();
200 if (Stream.SkipBlock())
201 return Error("Malformed block record");
205 if (Code == bitc::DEFINE_ABBREV) {
206 Stream.ReadAbbrevRecord();
212 const Type *ResultTy = 0;
213 switch (Stream.ReadRecord(Code, Record)) {
214 default: // Default behavior: unknown type.
217 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
218 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
219 // type list. This allows us to reserve space.
220 if (Record.size() < 1)
221 return Error("Invalid TYPE_CODE_NUMENTRY record");
222 TypeList.reserve(Record[0]);
224 case bitc::TYPE_CODE_META: // TYPE_CODE_META: [metacode]...
225 // No metadata supported yet.
226 if (Record.size() < 1)
227 return Error("Invalid TYPE_CODE_META record");
230 case bitc::TYPE_CODE_VOID: // VOID
231 ResultTy = Type::VoidTy;
233 case bitc::TYPE_CODE_FLOAT: // FLOAT
234 ResultTy = Type::FloatTy;
236 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
237 ResultTy = Type::DoubleTy;
239 case bitc::TYPE_CODE_LABEL: // LABEL
240 ResultTy = Type::LabelTy;
242 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
245 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
246 if (Record.size() < 1)
247 return Error("Invalid Integer type record");
249 ResultTy = IntegerType::get(Record[0]);
251 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
252 if (Record.size() < 1)
253 return Error("Invalid POINTER type record");
254 ResultTy = PointerType::get(getTypeByID(Record[0], true));
256 case bitc::TYPE_CODE_FUNCTION: {
257 // FUNCTION: [vararg, retty, #pararms, paramty N]
258 if (Record.size() < 3 || Record.size() < Record[2]+3)
259 return Error("Invalid FUNCTION type record");
260 std::vector<const Type*> ArgTys;
261 for (unsigned i = 0, e = Record[2]; i != e; ++i)
262 ArgTys.push_back(getTypeByID(Record[3+i], true));
265 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
269 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
270 if (Record.size() < 2 || Record.size() < Record[1]+2)
271 return Error("Invalid STRUCT type record");
272 std::vector<const Type*> EltTys;
273 for (unsigned i = 0, e = Record[1]; i != e; ++i)
274 EltTys.push_back(getTypeByID(Record[2+i], true));
275 ResultTy = StructType::get(EltTys, Record[0]);
278 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
279 if (Record.size() < 2)
280 return Error("Invalid ARRAY type record");
281 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
283 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
284 if (Record.size() < 2)
285 return Error("Invalid VECTOR type record");
286 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
290 if (NumRecords == TypeList.size()) {
291 // If this is a new type slot, just append it.
292 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
294 } else if (ResultTy == 0) {
295 // Otherwise, this was forward referenced, so an opaque type was created,
296 // but the result type is actually just an opaque. Leave the one we
297 // created previously.
300 // Otherwise, this was forward referenced, so an opaque type was created.
301 // Resolve the opaque type to the real type now.
302 assert(NumRecords < TypeList.size() && "Typelist imbalance");
303 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
305 // Don't directly push the new type on the Tab. Instead we want to replace
306 // the opaque type we previously inserted with the new concrete value. The
307 // refinement from the abstract (opaque) type to the new type causes all
308 // uses of the abstract type to use the concrete type (NewTy). This will
309 // also cause the opaque type to be deleted.
310 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
312 // This should have replaced the old opaque type with the new type in the
313 // value table... or with a preexisting type that was already in the
314 // system. Let's just make sure it did.
315 assert(TypeList[NumRecords-1].get() != OldTy &&
316 "refineAbstractType didn't work!");
322 bool BitcodeReader::ParseTypeSymbolTable() {
323 if (Stream.EnterSubBlock())
324 return Error("Malformed block record");
326 SmallVector<uint64_t, 64> Record;
328 // Read all the records for this type table.
329 std::string TypeName;
331 unsigned Code = Stream.ReadCode();
332 if (Code == bitc::END_BLOCK) {
333 if (Stream.ReadBlockEnd())
334 return Error("Error at end of type symbol table block");
338 if (Code == bitc::ENTER_SUBBLOCK) {
339 // No known subblocks, always skip them.
340 Stream.ReadSubBlockID();
341 if (Stream.SkipBlock())
342 return Error("Malformed block record");
346 if (Code == bitc::DEFINE_ABBREV) {
347 Stream.ReadAbbrevRecord();
353 switch (Stream.ReadRecord(Code, Record)) {
354 default: // Default behavior: unknown type.
356 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
357 if (ConvertToString(Record, 1, TypeName))
358 return Error("Invalid TST_ENTRY record");
359 unsigned TypeID = Record[0];
360 if (TypeID >= TypeList.size())
361 return Error("Invalid Type ID in TST_ENTRY record");
363 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
370 bool BitcodeReader::ParseValueSymbolTable() {
371 if (Stream.EnterSubBlock())
372 return Error("Malformed block record");
374 SmallVector<uint64_t, 64> Record;
376 // Read all the records for this value table.
377 SmallString<128> ValueName;
379 unsigned Code = Stream.ReadCode();
380 if (Code == bitc::END_BLOCK) {
381 if (Stream.ReadBlockEnd())
382 return Error("Error at end of value symbol table block");
385 if (Code == bitc::ENTER_SUBBLOCK) {
386 // No known subblocks, always skip them.
387 Stream.ReadSubBlockID();
388 if (Stream.SkipBlock())
389 return Error("Malformed block record");
393 if (Code == bitc::DEFINE_ABBREV) {
394 Stream.ReadAbbrevRecord();
400 switch (Stream.ReadRecord(Code, Record)) {
401 default: // Default behavior: unknown type.
403 case bitc::TST_CODE_ENTRY: // VST_ENTRY: [valueid, namelen, namechar x N]
404 if (ConvertToString(Record, 1, ValueName))
405 return Error("Invalid TST_ENTRY record");
406 unsigned ValueID = Record[0];
407 if (ValueID >= ValueList.size())
408 return Error("Invalid Value ID in VST_ENTRY record");
409 Value *V = ValueList[ValueID];
411 V->setName(&ValueName[0], ValueName.size());
418 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
419 /// the LSB for dense VBR encoding.
420 static uint64_t DecodeSignRotatedValue(uint64_t V) {
425 // There is no such thing as -0 with integers. "-0" really means MININT.
429 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
430 /// values and aliases that we can.
431 bool BitcodeReader::ResolveGlobalAndAliasInits() {
432 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
433 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
435 GlobalInitWorklist.swap(GlobalInits);
436 AliasInitWorklist.swap(AliasInits);
438 while (!GlobalInitWorklist.empty()) {
439 unsigned ValID = GlobalInitWorklist.back().second;
440 if (ValID >= ValueList.size()) {
441 // Not ready to resolve this yet, it requires something later in the file.
442 GlobalInits.push_back(GlobalInitWorklist.back());
444 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
445 GlobalInitWorklist.back().first->setInitializer(C);
447 return Error("Global variable initializer is not a constant!");
449 GlobalInitWorklist.pop_back();
452 while (!AliasInitWorklist.empty()) {
453 unsigned ValID = AliasInitWorklist.back().second;
454 if (ValID >= ValueList.size()) {
455 AliasInits.push_back(AliasInitWorklist.back());
457 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
458 AliasInitWorklist.back().first->setAliasee(C);
460 return Error("Alias initializer is not a constant!");
462 AliasInitWorklist.pop_back();
468 bool BitcodeReader::ParseConstants() {
469 if (Stream.EnterSubBlock())
470 return Error("Malformed block record");
472 SmallVector<uint64_t, 64> Record;
474 // Read all the records for this value table.
475 const Type *CurTy = Type::Int32Ty;
476 unsigned NextCstNo = ValueList.size();
478 unsigned Code = Stream.ReadCode();
479 if (Code == bitc::END_BLOCK) {
480 if (NextCstNo != ValueList.size())
481 return Error("Invalid constant reference!");
483 if (Stream.ReadBlockEnd())
484 return Error("Error at end of constants block");
488 if (Code == bitc::ENTER_SUBBLOCK) {
489 // No known subblocks, always skip them.
490 Stream.ReadSubBlockID();
491 if (Stream.SkipBlock())
492 return Error("Malformed block record");
496 if (Code == bitc::DEFINE_ABBREV) {
497 Stream.ReadAbbrevRecord();
504 switch (Stream.ReadRecord(Code, Record)) {
505 default: // Default behavior: unknown constant
506 case bitc::CST_CODE_UNDEF: // UNDEF
507 V = UndefValue::get(CurTy);
509 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
511 return Error("Malformed CST_SETTYPE record");
512 if (Record[0] >= TypeList.size())
513 return Error("Invalid Type ID in CST_SETTYPE record");
514 CurTy = TypeList[Record[0]];
515 continue; // Skip the ValueList manipulation.
516 case bitc::CST_CODE_NULL: // NULL
517 V = Constant::getNullValue(CurTy);
519 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
520 if (!isa<IntegerType>(CurTy) || Record.empty())
521 return Error("Invalid CST_INTEGER record");
522 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
524 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
525 if (!isa<IntegerType>(CurTy) || Record.empty() ||
526 Record.size() < Record[0]+1)
527 return Error("Invalid WIDE_INTEGER record");
529 unsigned NumWords = Record[0];
530 SmallVector<uint64_t, 8> Words;
531 Words.resize(NumWords);
532 for (unsigned i = 0; i != NumWords; ++i)
533 Words[i] = DecodeSignRotatedValue(Record[i+1]);
534 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
535 NumWords, &Words[0]));
538 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
540 return Error("Invalid FLOAT record");
541 if (CurTy == Type::FloatTy)
542 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
543 else if (CurTy == Type::DoubleTy)
544 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
546 V = UndefValue::get(CurTy);
549 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
550 if (Record.empty() || Record.size() < Record[0]+1)
551 return Error("Invalid CST_AGGREGATE record");
553 unsigned Size = Record[0];
554 std::vector<Constant*> Elts;
556 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
557 for (unsigned i = 0; i != Size; ++i)
558 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
559 STy->getElementType(i)));
560 V = ConstantStruct::get(STy, Elts);
561 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
562 const Type *EltTy = ATy->getElementType();
563 for (unsigned i = 0; i != Size; ++i)
564 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
565 V = ConstantArray::get(ATy, Elts);
566 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
567 const Type *EltTy = VTy->getElementType();
568 for (unsigned i = 0; i != Size; ++i)
569 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
570 V = ConstantVector::get(Elts);
572 V = UndefValue::get(CurTy);
577 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
578 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
579 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
581 V = UndefValue::get(CurTy); // Unknown binop.
583 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
584 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
585 V = ConstantExpr::get(Opc, LHS, RHS);
589 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
590 if (Record.size() < 3) return Error("Invalid CE_CAST record");
591 int Opc = GetDecodedCastOpcode(Record[0]);
593 V = UndefValue::get(CurTy); // Unknown cast.
595 const Type *OpTy = getTypeByID(Record[1]);
596 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
597 V = ConstantExpr::getCast(Opc, Op, CurTy);
601 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
602 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
603 SmallVector<Constant*, 16> Elts;
604 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
605 const Type *ElTy = getTypeByID(Record[i]);
606 if (!ElTy) return Error("Invalid CE_GEP record");
607 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
609 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
612 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
613 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
614 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
616 ValueList.getConstantFwdRef(Record[1],CurTy),
617 ValueList.getConstantFwdRef(Record[2],CurTy));
619 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
620 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
621 const VectorType *OpTy =
622 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
623 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
624 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
625 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
626 OpTy->getElementType());
627 V = ConstantExpr::getExtractElement(Op0, Op1);
630 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
631 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
632 if (Record.size() < 3 || OpTy == 0)
633 return Error("Invalid CE_INSERTELT record");
634 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
635 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
636 OpTy->getElementType());
637 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
638 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
641 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
642 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
643 if (Record.size() < 3 || OpTy == 0)
644 return Error("Invalid CE_INSERTELT record");
645 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
646 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
647 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
648 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
649 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
652 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
653 if (Record.size() < 4) return Error("Invalid CE_CMP record");
654 const Type *OpTy = getTypeByID(Record[0]);
655 if (OpTy == 0) return Error("Invalid CE_CMP record");
656 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
657 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
659 if (OpTy->isFloatingPoint())
660 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
662 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
667 ValueList.AssignValue(V, NextCstNo);
672 /// RememberAndSkipFunctionBody - When we see the block for a function body,
673 /// remember where it is and then skip it. This lets us lazily deserialize the
675 bool BitcodeReader::RememberAndSkipFunctionBody() {
676 // Get the function we are talking about.
677 if (FunctionsWithBodies.empty())
678 return Error("Insufficient function protos");
680 Function *Fn = FunctionsWithBodies.back();
681 FunctionsWithBodies.pop_back();
683 // Save the current stream state.
684 uint64_t CurBit = Stream.GetCurrentBitNo();
685 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
687 // Set the functions linkage to GhostLinkage so we know it is lazily
689 Fn->setLinkage(GlobalValue::GhostLinkage);
691 // Skip over the function block for now.
692 if (Stream.SkipBlock())
693 return Error("Malformed block record");
697 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
698 // Reject multiple MODULE_BLOCK's in a single bitstream.
700 return Error("Multiple MODULE_BLOCKs in same stream");
702 if (Stream.EnterSubBlock())
703 return Error("Malformed block record");
705 // Otherwise, create the module.
706 TheModule = new Module(ModuleID);
708 SmallVector<uint64_t, 64> Record;
709 std::vector<std::string> SectionTable;
711 // Read all the records for this module.
712 while (!Stream.AtEndOfStream()) {
713 unsigned Code = Stream.ReadCode();
714 if (Code == bitc::END_BLOCK) {
715 if (Stream.ReadBlockEnd())
716 return Error("Error at end of module block");
718 // Patch the initializers for globals and aliases up.
719 ResolveGlobalAndAliasInits();
720 if (!GlobalInits.empty() || !AliasInits.empty())
721 return Error("Malformed global initializer set");
722 if (!FunctionsWithBodies.empty())
723 return Error("Too few function bodies found");
725 // Force deallocation of memory for these vectors to favor the client that
726 // want lazy deserialization.
727 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
728 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
729 std::vector<Function*>().swap(FunctionsWithBodies);
733 if (Code == bitc::ENTER_SUBBLOCK) {
734 switch (Stream.ReadSubBlockID()) {
735 default: // Skip unknown content.
736 if (Stream.SkipBlock())
737 return Error("Malformed block record");
739 case bitc::TYPE_BLOCK_ID:
740 if (ParseTypeTable())
743 case bitc::TYPE_SYMTAB_BLOCK_ID:
744 if (ParseTypeSymbolTable())
747 case bitc::VALUE_SYMTAB_BLOCK_ID:
748 if (ParseValueSymbolTable())
751 case bitc::CONSTANTS_BLOCK_ID:
752 if (ParseConstants() || ResolveGlobalAndAliasInits())
755 case bitc::FUNCTION_BLOCK_ID:
756 // If this is the first function body we've seen, reverse the
757 // FunctionsWithBodies list.
758 if (!HasReversedFunctionsWithBodies) {
759 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
760 HasReversedFunctionsWithBodies = true;
763 if (RememberAndSkipFunctionBody())
770 if (Code == bitc::DEFINE_ABBREV) {
771 Stream.ReadAbbrevRecord();
776 switch (Stream.ReadRecord(Code, Record)) {
777 default: break; // Default behavior, ignore unknown content.
778 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
779 if (Record.size() < 1)
780 return Error("Malformed MODULE_CODE_VERSION");
781 // Only version #0 is supported so far.
783 return Error("Unknown bitstream version!");
785 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
787 if (ConvertToString(Record, 0, S))
788 return Error("Invalid MODULE_CODE_TRIPLE record");
789 TheModule->setTargetTriple(S);
792 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
794 if (ConvertToString(Record, 0, S))
795 return Error("Invalid MODULE_CODE_DATALAYOUT record");
796 TheModule->setDataLayout(S);
799 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
801 if (ConvertToString(Record, 0, S))
802 return Error("Invalid MODULE_CODE_ASM record");
803 TheModule->setModuleInlineAsm(S);
806 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
808 if (ConvertToString(Record, 0, S))
809 return Error("Invalid MODULE_CODE_DEPLIB record");
810 TheModule->addLibrary(S);
813 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
815 if (ConvertToString(Record, 0, S))
816 return Error("Invalid MODULE_CODE_SECTIONNAME record");
817 SectionTable.push_back(S);
820 // GLOBALVAR: [type, isconst, initid,
821 // linkage, alignment, section, visibility, threadlocal]
822 case bitc::MODULE_CODE_GLOBALVAR: {
823 if (Record.size() < 6)
824 return Error("Invalid MODULE_CODE_GLOBALVAR record");
825 const Type *Ty = getTypeByID(Record[0]);
826 if (!isa<PointerType>(Ty))
827 return Error("Global not a pointer type!");
828 Ty = cast<PointerType>(Ty)->getElementType();
830 bool isConstant = Record[1];
831 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
832 unsigned Alignment = (1 << Record[4]) >> 1;
835 if (Record[5]-1 >= SectionTable.size())
836 return Error("Invalid section ID");
837 Section = SectionTable[Record[5]-1];
839 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
840 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
841 bool isThreadLocal = false;
842 if (Record.size() >= 7) isThreadLocal = Record[7];
844 GlobalVariable *NewGV =
845 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
846 NewGV->setAlignment(Alignment);
847 if (!Section.empty())
848 NewGV->setSection(Section);
849 NewGV->setVisibility(Visibility);
850 NewGV->setThreadLocal(isThreadLocal);
852 ValueList.push_back(NewGV);
854 // Remember which value to use for the global initializer.
855 if (unsigned InitID = Record[2])
856 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
859 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
861 case bitc::MODULE_CODE_FUNCTION: {
862 if (Record.size() < 7)
863 return Error("Invalid MODULE_CODE_FUNCTION record");
864 const Type *Ty = getTypeByID(Record[0]);
865 if (!isa<PointerType>(Ty))
866 return Error("Function not a pointer type!");
867 const FunctionType *FTy =
868 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
870 return Error("Function not a pointer to function type!");
872 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
875 Func->setCallingConv(Record[1]);
876 bool isProto = Record[2];
877 Func->setLinkage(GetDecodedLinkage(Record[3]));
878 Func->setAlignment((1 << Record[4]) >> 1);
880 if (Record[5]-1 >= SectionTable.size())
881 return Error("Invalid section ID");
882 Func->setSection(SectionTable[Record[5]-1]);
884 Func->setVisibility(GetDecodedVisibility(Record[6]));
886 ValueList.push_back(Func);
888 // If this is a function with a body, remember the prototype we are
889 // creating now, so that we can match up the body with them later.
891 FunctionsWithBodies.push_back(Func);
894 // ALIAS: [alias type, aliasee val#, linkage]
895 case bitc::MODULE_CODE_ALIAS: {
896 if (Record.size() < 3)
897 return Error("Invalid MODULE_ALIAS record");
898 const Type *Ty = getTypeByID(Record[0]);
899 if (!isa<PointerType>(Ty))
900 return Error("Function not a pointer type!");
902 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
904 ValueList.push_back(NewGA);
905 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
908 /// MODULE_CODE_PURGEVALS: [numvals]
909 case bitc::MODULE_CODE_PURGEVALS:
910 // Trim down the value list to the specified size.
911 if (Record.size() < 1 || Record[0] > ValueList.size())
912 return Error("Invalid MODULE_PURGEVALS record");
913 ValueList.shrinkTo(Record[0]);
919 return Error("Premature end of bitstream");
923 bool BitcodeReader::ParseBitcode() {
926 if (Buffer->getBufferSize() & 3)
927 return Error("Bitcode stream should be a multiple of 4 bytes in length");
929 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
930 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
932 // Sniff for the signature.
933 if (Stream.Read(8) != 'B' ||
934 Stream.Read(8) != 'C' ||
935 Stream.Read(4) != 0x0 ||
936 Stream.Read(4) != 0xC ||
937 Stream.Read(4) != 0xE ||
938 Stream.Read(4) != 0xD)
939 return Error("Invalid bitcode signature");
941 // We expect a number of well-defined blocks, though we don't necessarily
942 // need to understand them all.
943 while (!Stream.AtEndOfStream()) {
944 unsigned Code = Stream.ReadCode();
946 if (Code != bitc::ENTER_SUBBLOCK)
947 return Error("Invalid record at top-level");
949 unsigned BlockID = Stream.ReadSubBlockID();
951 // We only know the MODULE subblock ID.
952 if (BlockID == bitc::MODULE_BLOCK_ID) {
953 if (ParseModule(Buffer->getBufferIdentifier()))
955 } else if (Stream.SkipBlock()) {
956 return Error("Malformed block record");
964 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
965 // If it already is material, ignore the request.
966 if (!F->hasNotBeenReadFromBytecode()) return false;
968 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
969 DeferredFunctionInfo.find(F);
970 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
972 // Move the bit stream to the saved position of the deferred function body and
973 // restore the real linkage type for the function.
974 Stream.JumpToBit(DFII->second.first);
975 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
976 DeferredFunctionInfo.erase(DFII);
978 if (ParseFunctionBody(F)) {
979 if (ErrInfo) *ErrInfo = ErrorString;
986 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
987 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
988 DeferredFunctionInfo.begin();
989 while (!DeferredFunctionInfo.empty()) {
990 Function *F = (*I++).first;
991 assert(F->hasNotBeenReadFromBytecode() &&
992 "Deserialized function found in map!");
993 if (materializeFunction(F, ErrInfo))
1000 /// ParseFunctionBody - Lazily parse the specified function body block.
1001 bool BitcodeReader::ParseFunctionBody(Function *F) {
1002 if (Stream.EnterSubBlock())
1003 return Error("Malformed block record");
1005 unsigned ModuleValueListSize = ValueList.size();
1007 // Add all the function arguments to the value table.
1008 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1009 ValueList.push_back(I);
1011 unsigned NextValueNo = ValueList.size();
1012 BasicBlock *CurBB = 0;
1013 unsigned CurBBNo = 0;
1015 // Read all the records.
1016 SmallVector<uint64_t, 64> Record;
1018 unsigned Code = Stream.ReadCode();
1019 if (Code == bitc::END_BLOCK) {
1020 if (Stream.ReadBlockEnd())
1021 return Error("Error at end of function block");
1025 if (Code == bitc::ENTER_SUBBLOCK) {
1026 switch (Stream.ReadSubBlockID()) {
1027 default: // Skip unknown content.
1028 if (Stream.SkipBlock())
1029 return Error("Malformed block record");
1031 case bitc::CONSTANTS_BLOCK_ID:
1032 if (ParseConstants()) return true;
1033 NextValueNo = ValueList.size();
1035 case bitc::VALUE_SYMTAB_BLOCK_ID:
1036 if (ParseValueSymbolTable()) return true;
1042 if (Code == bitc::DEFINE_ABBREV) {
1043 Stream.ReadAbbrevRecord();
1050 switch (Stream.ReadRecord(Code, Record)) {
1051 default: // Default behavior: reject
1052 return Error("Unknown instruction");
1053 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1054 if (Record.size() < 1 || Record[0] == 0)
1055 return Error("Invalid DECLAREBLOCKS record");
1056 // Create all the basic blocks for the function.
1057 FunctionBBs.resize(Record.size());
1058 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1059 FunctionBBs[i] = new BasicBlock("", F);
1060 CurBB = FunctionBBs[0];
1063 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
1064 if (Record.size() < 4) return Error("Invalid BINOP record");
1065 const Type *Ty = getTypeByID(Record[1]);
1066 int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1067 Value *LHS = getFnValueByID(Record[2], Ty);
1068 Value *RHS = getFnValueByID(Record[3], Ty);
1069 if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1070 return Error("Invalid BINOP record");
1071 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1074 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
1075 if (Record.size() < 4) return Error("Invalid CAST record");
1076 int Opc = GetDecodedCastOpcode(Record[0]);
1077 const Type *ResTy = getTypeByID(Record[1]);
1078 const Type *OpTy = getTypeByID(Record[2]);
1079 Value *Op = getFnValueByID(Record[3], OpTy);
1080 if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1081 return Error("Invalid CAST record");
1082 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1085 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n, n x operands]
1086 if (Record.size() < 2 || (Record.size() & 1))
1087 return Error("Invalid GEP record");
1088 const Type *OpTy = getTypeByID(Record[0]);
1089 Value *Op = getFnValueByID(Record[1], OpTy);
1090 if (OpTy == 0 || Op == 0)
1091 return Error("Invalid GEP record");
1093 SmallVector<Value*, 16> GEPIdx;
1094 for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
1095 const Type *IdxTy = getTypeByID(Record[i*2]);
1096 Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
1097 if (IdxTy == 0 || Idx == 0)
1098 return Error("Invalid GEP record");
1099 GEPIdx.push_back(Idx);
1102 I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
1106 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
1107 if (Record.size() < 4) return Error("Invalid SELECT record");
1108 const Type *Ty = getTypeByID(Record[0]);
1109 Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
1110 Value *LHS = getFnValueByID(Record[2], Ty);
1111 Value *RHS = getFnValueByID(Record[3], Ty);
1112 if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
1113 return Error("Invalid SELECT record");
1114 I = new SelectInst(Cond, LHS, RHS);
1118 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1119 if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
1120 const Type *OpTy = getTypeByID(Record[0]);
1121 Value *Vec = getFnValueByID(Record[1], OpTy);
1122 Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
1123 if (OpTy == 0 || Vec == 0 || Idx == 0)
1124 return Error("Invalid EXTRACTELT record");
1125 I = new ExtractElementInst(Vec, Idx);
1129 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1130 if (Record.size() < 4) return Error("Invalid INSERTELT record");
1131 const VectorType *OpTy =
1132 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1133 if (OpTy == 0) return Error("Invalid INSERTELT record");
1134 Value *Vec = getFnValueByID(Record[1], OpTy);
1135 Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
1136 Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
1137 if (Vec == 0 || Elt == 0 || Idx == 0)
1138 return Error("Invalid INSERTELT record");
1139 I = new InsertElementInst(Vec, Elt, Idx);
1143 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
1144 if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
1145 const VectorType *OpTy =
1146 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1147 if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
1148 Value *Vec1 = getFnValueByID(Record[1], OpTy);
1149 Value *Vec2 = getFnValueByID(Record[2], OpTy);
1150 Value *Mask = getFnValueByID(Record[3],
1151 VectorType::get(Type::Int32Ty,
1152 OpTy->getNumElements()));
1153 if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
1154 return Error("Invalid SHUFFLEVEC record");
1155 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1159 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1160 if (Record.size() < 4) return Error("Invalid CMP record");
1161 const Type *OpTy = getTypeByID(Record[0]);
1162 Value *LHS = getFnValueByID(Record[1], OpTy);
1163 Value *RHS = getFnValueByID(Record[2], OpTy);
1164 if (OpTy == 0 || LHS == 0 || RHS == 0)
1165 return Error("Invalid CMP record");
1166 if (OpTy->isFPOrFPVector())
1167 I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
1169 I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
1173 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1174 if (Record.size() == 0) {
1175 I = new ReturnInst();
1178 if (Record.size() == 2) {
1179 const Type *OpTy = getTypeByID(Record[0]);
1180 Value *Op = getFnValueByID(Record[1], OpTy);
1182 return Error("Invalid RET record");
1183 I = new ReturnInst(Op);
1186 return Error("Invalid RET record");
1187 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1188 if (Record.size() != 1 || Record.size() != 3)
1189 return Error("Invalid BR record");
1190 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1192 return Error("Invalid BR record");
1194 if (Record.size() == 1)
1195 I = new BranchInst(TrueDest);
1197 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1198 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1199 if (FalseDest == 0 || Cond == 0)
1200 return Error("Invalid BR record");
1201 I = new BranchInst(TrueDest, FalseDest, Cond);
1205 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1206 if (Record.size() < 3 || (Record.size() & 1) == 0)
1207 return Error("Invalid SWITCH record");
1208 const Type *OpTy = getTypeByID(Record[0]);
1209 Value *Cond = getFnValueByID(Record[1], OpTy);
1210 BasicBlock *Default = getBasicBlock(Record[2]);
1211 if (OpTy == 0 || Cond == 0 || Default == 0)
1212 return Error("Invalid SWITCH record");
1213 unsigned NumCases = (Record.size()-3)/2;
1214 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1215 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1216 ConstantInt *CaseVal =
1217 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1218 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1219 if (CaseVal == 0 || DestBB == 0) {
1221 return Error("Invalid SWITCH record!");
1223 SI->addCase(CaseVal, DestBB);
1229 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [fnty, op0,op1,op2, ...]
1230 if (Record.size() < 4)
1231 return Error("Invalid INVOKE record");
1232 const PointerType *CalleeTy =
1233 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1234 Value *Callee = getFnValueByID(Record[1], CalleeTy);
1235 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1236 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1237 if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
1238 return Error("Invalid INVOKE record");
1240 const FunctionType *FTy =
1241 dyn_cast<FunctionType>(CalleeTy->getElementType());
1243 // Check that the right number of fixed parameters are here.
1244 if (FTy == 0 || Record.size() < 4+FTy->getNumParams())
1245 return Error("Invalid INVOKE record");
1247 SmallVector<Value*, 16> Ops;
1248 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1249 Ops.push_back(getFnValueByID(Record[4+i], FTy->getParamType(4+i)));
1250 if (Ops.back() == 0)
1251 return Error("Invalid INVOKE record");
1254 unsigned FirstVarargParam = 4+FTy->getNumParams();
1255 if (FTy->isVarArg()) {
1256 // Read type/value pairs for varargs params.
1257 if ((Record.size()-FirstVarargParam) & 1)
1258 return Error("Invalid INVOKE record");
1260 for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
1261 const Type *ArgTy = getTypeByID(Record[i]);
1262 Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
1263 if (Ops.back() == 0 || ArgTy == 0)
1264 return Error("Invalid INVOKE record");
1267 if (Record.size() != FirstVarargParam)
1268 return Error("Invalid INVOKE record");
1271 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1274 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1275 I = new UnwindInst();
1277 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1278 I = new UnreachableInst();
1280 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
1281 if (Record.size() < 2 || Record.size() < 2+Record[1] || (Record[1]&1))
1282 return Error("Invalid PHI record");
1283 const Type *Ty = getTypeByID(Record[0]);
1284 if (!Ty) return Error("Invalid PHI record");
1286 PHINode *PN = new PHINode(Ty);
1287 PN->reserveOperandSpace(Record[1]);
1289 for (unsigned i = 0, e = Record[1]; i != e; i += 2) {
1290 Value *V = getFnValueByID(Record[2+i], Ty);
1291 BasicBlock *BB = getBasicBlock(Record[3+i]);
1292 if (!V || !BB) return Error("Invalid PHI record");
1293 PN->addIncoming(V, BB);
1299 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1300 if (Record.size() < 3)
1301 return Error("Invalid MALLOC record");
1302 const PointerType *Ty =
1303 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1304 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1305 unsigned Align = Record[2];
1306 if (!Ty || !Size) return Error("Invalid MALLOC record");
1307 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1310 case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
1311 if (Record.size() < 2)
1312 return Error("Invalid FREE record");
1313 const Type *OpTy = getTypeByID(Record[0]);
1314 Value *Op = getFnValueByID(Record[1], OpTy);
1316 return Error("Invalid FREE record");
1317 I = new FreeInst(Op);
1320 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1321 if (Record.size() < 3)
1322 return Error("Invalid ALLOCA record");
1323 const PointerType *Ty =
1324 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1325 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1326 unsigned Align = Record[2];
1327 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1328 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1331 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1332 if (Record.size() < 4)
1333 return Error("Invalid LOAD record");
1334 const Type *OpTy = getTypeByID(Record[0]);
1335 Value *Op = getFnValueByID(Record[1], OpTy);
1337 return Error("Invalid LOAD record");
1338 I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
1341 case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
1342 if (Record.size() < 5)
1343 return Error("Invalid LOAD record");
1344 const Type *OpTy = getTypeByID(Record[0]);
1345 Value *Op = getFnValueByID(Record[1], OpTy);
1346 Value *Ptr = getFnValueByID(Record[2], PointerType::get(OpTy));
1347 if (!OpTy || !Op || !Ptr)
1348 return Error("Invalid STORE record");
1349 I = new StoreInst(Op, Ptr, (1 << Record[3]) >> 1, Record[4]);
1352 case bitc::FUNC_CODE_INST_CALL: { // CALL: [fnty, fnid, arg0, arg1...]
1353 if (Record.size() < 2)
1354 return Error("Invalid CALL record");
1355 const PointerType *OpTy =
1356 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1357 const FunctionType *FTy = 0;
1358 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1359 Value *Callee = getFnValueByID(Record[1], OpTy);
1360 if (!FTy || !Callee || Record.size() < FTy->getNumParams()+2)
1361 return Error("Invalid CALL record");
1363 SmallVector<Value*, 16> Args;
1364 // Read the fixed params.
1365 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1366 Args.push_back(getFnValueByID(Record[i+2], FTy->getParamType(i)));
1367 if (Args.back() == 0) return Error("Invalid CALL record");
1371 // Read type/value pairs for varargs params.
1372 unsigned NextArg = FTy->getNumParams()+2;
1373 if (!FTy->isVarArg()) {
1374 if (NextArg != Record.size())
1375 return Error("Invalid CALL record");
1377 if ((Record.size()-NextArg) & 1)
1378 return Error("Invalid CALL record");
1379 for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
1380 Args.push_back(getFnValueByID(Record[NextArg+1],
1381 getTypeByID(Record[NextArg])));
1382 if (Args.back() == 0) return Error("Invalid CALL record");
1386 I = new CallInst(Callee, &Args[0], Args.size());
1389 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1390 if (Record.size() < 3)
1391 return Error("Invalid VAARG record");
1392 const Type *OpTy = getTypeByID(Record[0]);
1393 Value *Op = getFnValueByID(Record[1], OpTy);
1394 const Type *ResTy = getTypeByID(Record[2]);
1395 if (!OpTy || !Op || !ResTy)
1396 return Error("Invalid VAARG record");
1397 I = new VAArgInst(Op, ResTy);
1402 // Add instruction to end of current BB. If there is no current BB, reject
1406 return Error("Invalid instruction with no BB");
1408 CurBB->getInstList().push_back(I);
1410 // If this was a terminator instruction, move to the next block.
1411 if (isa<TerminatorInst>(I)) {
1413 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1416 // Non-void values get registered in the value table for future use.
1417 if (I && I->getType() != Type::VoidTy)
1418 ValueList.AssignValue(I, NextValueNo++);
1421 // Check the function list for unresolved values.
1422 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1423 if (A->getParent() == 0) {
1424 // We found at least one unresolved value. Nuke them all to avoid leaks.
1425 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1426 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1427 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1432 return Error("Never resolved value found in function!");
1435 // Trim the value list down to the size it was before we parsed this function.
1436 ValueList.shrinkTo(ModuleValueListSize);
1437 std::vector<BasicBlock*>().swap(FunctionBBs);
1443 //===----------------------------------------------------------------------===//
1444 // External interface
1445 //===----------------------------------------------------------------------===//
1447 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1449 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1450 std::string *ErrMsg) {
1451 BitcodeReader *R = new BitcodeReader(Buffer);
1452 if (R->ParseBitcode()) {
1454 *ErrMsg = R->getErrorString();
1456 // Don't let the BitcodeReader dtor delete 'Buffer'.
1457 R->releaseMemoryBuffer();
1464 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1465 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1466 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1468 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1471 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1472 // delete it when its dtor is run.
1473 Module *M = R->releaseModule(ErrMsg);
1475 // Don't let the BitcodeReader dtor delete 'Buffer'.
1476 R->releaseMemoryBuffer();