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_VOID: // VOID
225 ResultTy = Type::VoidTy;
227 case bitc::TYPE_CODE_FLOAT: // FLOAT
228 ResultTy = Type::FloatTy;
230 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
231 ResultTy = Type::DoubleTy;
233 case bitc::TYPE_CODE_LABEL: // LABEL
234 ResultTy = Type::LabelTy;
236 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
239 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
240 if (Record.size() < 1)
241 return Error("Invalid Integer type record");
243 ResultTy = IntegerType::get(Record[0]);
245 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
246 if (Record.size() < 1)
247 return Error("Invalid POINTER type record");
248 ResultTy = PointerType::get(getTypeByID(Record[0], true));
250 case bitc::TYPE_CODE_FUNCTION: {
251 // FUNCTION: [vararg, retty, #pararms, paramty N]
252 if (Record.size() < 3 || Record.size() < Record[2]+3)
253 return Error("Invalid FUNCTION type record");
254 std::vector<const Type*> ArgTys;
255 for (unsigned i = 0, e = Record[2]; i != e; ++i)
256 ArgTys.push_back(getTypeByID(Record[3+i], true));
259 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
263 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
264 if (Record.size() < 2 || Record.size() < Record[1]+2)
265 return Error("Invalid STRUCT type record");
266 std::vector<const Type*> EltTys;
267 for (unsigned i = 0, e = Record[1]; i != e; ++i)
268 EltTys.push_back(getTypeByID(Record[2+i], true));
269 ResultTy = StructType::get(EltTys, Record[0]);
272 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
273 if (Record.size() < 2)
274 return Error("Invalid ARRAY type record");
275 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
277 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
278 if (Record.size() < 2)
279 return Error("Invalid VECTOR type record");
280 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
284 if (NumRecords == TypeList.size()) {
285 // If this is a new type slot, just append it.
286 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
288 } else if (ResultTy == 0) {
289 // Otherwise, this was forward referenced, so an opaque type was created,
290 // but the result type is actually just an opaque. Leave the one we
291 // created previously.
294 // Otherwise, this was forward referenced, so an opaque type was created.
295 // Resolve the opaque type to the real type now.
296 assert(NumRecords < TypeList.size() && "Typelist imbalance");
297 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
299 // Don't directly push the new type on the Tab. Instead we want to replace
300 // the opaque type we previously inserted with the new concrete value. The
301 // refinement from the abstract (opaque) type to the new type causes all
302 // uses of the abstract type to use the concrete type (NewTy). This will
303 // also cause the opaque type to be deleted.
304 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
306 // This should have replaced the old opaque type with the new type in the
307 // value table... or with a preexisting type that was already in the
308 // system. Let's just make sure it did.
309 assert(TypeList[NumRecords-1].get() != OldTy &&
310 "refineAbstractType didn't work!");
316 bool BitcodeReader::ParseTypeSymbolTable() {
317 if (Stream.EnterSubBlock())
318 return Error("Malformed block record");
320 SmallVector<uint64_t, 64> Record;
322 // Read all the records for this type table.
323 std::string TypeName;
325 unsigned Code = Stream.ReadCode();
326 if (Code == bitc::END_BLOCK) {
327 if (Stream.ReadBlockEnd())
328 return Error("Error at end of type symbol table block");
332 if (Code == bitc::ENTER_SUBBLOCK) {
333 // No known subblocks, always skip them.
334 Stream.ReadSubBlockID();
335 if (Stream.SkipBlock())
336 return Error("Malformed block record");
340 if (Code == bitc::DEFINE_ABBREV) {
341 Stream.ReadAbbrevRecord();
347 switch (Stream.ReadRecord(Code, Record)) {
348 default: // Default behavior: unknown type.
350 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
351 if (ConvertToString(Record, 1, TypeName))
352 return Error("Invalid TST_ENTRY record");
353 unsigned TypeID = Record[0];
354 if (TypeID >= TypeList.size())
355 return Error("Invalid Type ID in TST_ENTRY record");
357 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
364 bool BitcodeReader::ParseValueSymbolTable() {
365 if (Stream.EnterSubBlock())
366 return Error("Malformed block record");
368 SmallVector<uint64_t, 64> Record;
370 // Read all the records for this value table.
371 SmallString<128> ValueName;
373 unsigned Code = Stream.ReadCode();
374 if (Code == bitc::END_BLOCK) {
375 if (Stream.ReadBlockEnd())
376 return Error("Error at end of value symbol table block");
379 if (Code == bitc::ENTER_SUBBLOCK) {
380 // No known subblocks, always skip them.
381 Stream.ReadSubBlockID();
382 if (Stream.SkipBlock())
383 return Error("Malformed block record");
387 if (Code == bitc::DEFINE_ABBREV) {
388 Stream.ReadAbbrevRecord();
394 switch (Stream.ReadRecord(Code, Record)) {
395 default: // Default behavior: unknown type.
397 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namelen, namechar x N]
398 if (ConvertToString(Record, 1, ValueName))
399 return Error("Invalid TST_ENTRY record");
400 unsigned ValueID = Record[0];
401 if (ValueID >= ValueList.size())
402 return Error("Invalid Value ID in VST_ENTRY record");
403 Value *V = ValueList[ValueID];
405 V->setName(&ValueName[0], ValueName.size());
409 case bitc::VST_CODE_BBENTRY: {
410 if (ConvertToString(Record, 1, ValueName))
411 return Error("Invalid VST_BBENTRY record");
412 BasicBlock *BB = getBasicBlock(Record[0]);
414 return Error("Invalid BB ID in VST_BBENTRY record");
416 BB->setName(&ValueName[0], ValueName.size());
424 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
425 /// the LSB for dense VBR encoding.
426 static uint64_t DecodeSignRotatedValue(uint64_t V) {
431 // There is no such thing as -0 with integers. "-0" really means MININT.
435 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
436 /// values and aliases that we can.
437 bool BitcodeReader::ResolveGlobalAndAliasInits() {
438 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
439 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
441 GlobalInitWorklist.swap(GlobalInits);
442 AliasInitWorklist.swap(AliasInits);
444 while (!GlobalInitWorklist.empty()) {
445 unsigned ValID = GlobalInitWorklist.back().second;
446 if (ValID >= ValueList.size()) {
447 // Not ready to resolve this yet, it requires something later in the file.
448 GlobalInits.push_back(GlobalInitWorklist.back());
450 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
451 GlobalInitWorklist.back().first->setInitializer(C);
453 return Error("Global variable initializer is not a constant!");
455 GlobalInitWorklist.pop_back();
458 while (!AliasInitWorklist.empty()) {
459 unsigned ValID = AliasInitWorklist.back().second;
460 if (ValID >= ValueList.size()) {
461 AliasInits.push_back(AliasInitWorklist.back());
463 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
464 AliasInitWorklist.back().first->setAliasee(C);
466 return Error("Alias initializer is not a constant!");
468 AliasInitWorklist.pop_back();
474 bool BitcodeReader::ParseConstants() {
475 if (Stream.EnterSubBlock())
476 return Error("Malformed block record");
478 SmallVector<uint64_t, 64> Record;
480 // Read all the records for this value table.
481 const Type *CurTy = Type::Int32Ty;
482 unsigned NextCstNo = ValueList.size();
484 unsigned Code = Stream.ReadCode();
485 if (Code == bitc::END_BLOCK) {
486 if (NextCstNo != ValueList.size())
487 return Error("Invalid constant reference!");
489 if (Stream.ReadBlockEnd())
490 return Error("Error at end of constants block");
494 if (Code == bitc::ENTER_SUBBLOCK) {
495 // No known subblocks, always skip them.
496 Stream.ReadSubBlockID();
497 if (Stream.SkipBlock())
498 return Error("Malformed block record");
502 if (Code == bitc::DEFINE_ABBREV) {
503 Stream.ReadAbbrevRecord();
510 switch (Stream.ReadRecord(Code, Record)) {
511 default: // Default behavior: unknown constant
512 case bitc::CST_CODE_UNDEF: // UNDEF
513 V = UndefValue::get(CurTy);
515 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
517 return Error("Malformed CST_SETTYPE record");
518 if (Record[0] >= TypeList.size())
519 return Error("Invalid Type ID in CST_SETTYPE record");
520 CurTy = TypeList[Record[0]];
521 continue; // Skip the ValueList manipulation.
522 case bitc::CST_CODE_NULL: // NULL
523 V = Constant::getNullValue(CurTy);
525 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
526 if (!isa<IntegerType>(CurTy) || Record.empty())
527 return Error("Invalid CST_INTEGER record");
528 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
530 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
531 if (!isa<IntegerType>(CurTy) || Record.empty() ||
532 Record.size() < Record[0]+1)
533 return Error("Invalid WIDE_INTEGER record");
535 unsigned NumWords = Record[0];
536 SmallVector<uint64_t, 8> Words;
537 Words.resize(NumWords);
538 for (unsigned i = 0; i != NumWords; ++i)
539 Words[i] = DecodeSignRotatedValue(Record[i+1]);
540 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
541 NumWords, &Words[0]));
544 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
546 return Error("Invalid FLOAT record");
547 if (CurTy == Type::FloatTy)
548 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
549 else if (CurTy == Type::DoubleTy)
550 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
552 V = UndefValue::get(CurTy);
555 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
556 if (Record.empty() || Record.size() < Record[0]+1)
557 return Error("Invalid CST_AGGREGATE record");
559 unsigned Size = Record[0];
560 std::vector<Constant*> Elts;
562 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
563 for (unsigned i = 0; i != Size; ++i)
564 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
565 STy->getElementType(i)));
566 V = ConstantStruct::get(STy, Elts);
567 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
568 const Type *EltTy = ATy->getElementType();
569 for (unsigned i = 0; i != Size; ++i)
570 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
571 V = ConstantArray::get(ATy, Elts);
572 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
573 const Type *EltTy = VTy->getElementType();
574 for (unsigned i = 0; i != Size; ++i)
575 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
576 V = ConstantVector::get(Elts);
578 V = UndefValue::get(CurTy);
583 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
584 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
585 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
587 V = UndefValue::get(CurTy); // Unknown binop.
589 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
590 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
591 V = ConstantExpr::get(Opc, LHS, RHS);
595 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
596 if (Record.size() < 3) return Error("Invalid CE_CAST record");
597 int Opc = GetDecodedCastOpcode(Record[0]);
599 V = UndefValue::get(CurTy); // Unknown cast.
601 const Type *OpTy = getTypeByID(Record[1]);
602 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
603 V = ConstantExpr::getCast(Opc, Op, CurTy);
607 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
608 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
609 SmallVector<Constant*, 16> Elts;
610 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
611 const Type *ElTy = getTypeByID(Record[i]);
612 if (!ElTy) return Error("Invalid CE_GEP record");
613 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
615 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
618 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
619 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
620 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
622 ValueList.getConstantFwdRef(Record[1],CurTy),
623 ValueList.getConstantFwdRef(Record[2],CurTy));
625 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
626 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
627 const VectorType *OpTy =
628 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
629 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
630 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
631 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
632 OpTy->getElementType());
633 V = ConstantExpr::getExtractElement(Op0, Op1);
636 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
637 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
638 if (Record.size() < 3 || OpTy == 0)
639 return Error("Invalid CE_INSERTELT record");
640 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
641 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
642 OpTy->getElementType());
643 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
644 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
647 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
648 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
649 if (Record.size() < 3 || OpTy == 0)
650 return Error("Invalid CE_INSERTELT record");
651 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
652 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
653 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
654 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
655 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
658 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
659 if (Record.size() < 4) return Error("Invalid CE_CMP record");
660 const Type *OpTy = getTypeByID(Record[0]);
661 if (OpTy == 0) return Error("Invalid CE_CMP record");
662 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
663 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
665 if (OpTy->isFloatingPoint())
666 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
668 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
673 ValueList.AssignValue(V, NextCstNo);
678 /// RememberAndSkipFunctionBody - When we see the block for a function body,
679 /// remember where it is and then skip it. This lets us lazily deserialize the
681 bool BitcodeReader::RememberAndSkipFunctionBody() {
682 // Get the function we are talking about.
683 if (FunctionsWithBodies.empty())
684 return Error("Insufficient function protos");
686 Function *Fn = FunctionsWithBodies.back();
687 FunctionsWithBodies.pop_back();
689 // Save the current stream state.
690 uint64_t CurBit = Stream.GetCurrentBitNo();
691 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
693 // Set the functions linkage to GhostLinkage so we know it is lazily
695 Fn->setLinkage(GlobalValue::GhostLinkage);
697 // Skip over the function block for now.
698 if (Stream.SkipBlock())
699 return Error("Malformed block record");
703 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
704 // Reject multiple MODULE_BLOCK's in a single bitstream.
706 return Error("Multiple MODULE_BLOCKs in same stream");
708 if (Stream.EnterSubBlock())
709 return Error("Malformed block record");
711 // Otherwise, create the module.
712 TheModule = new Module(ModuleID);
714 SmallVector<uint64_t, 64> Record;
715 std::vector<std::string> SectionTable;
717 // Read all the records for this module.
718 while (!Stream.AtEndOfStream()) {
719 unsigned Code = Stream.ReadCode();
720 if (Code == bitc::END_BLOCK) {
721 if (Stream.ReadBlockEnd())
722 return Error("Error at end of module block");
724 // Patch the initializers for globals and aliases up.
725 ResolveGlobalAndAliasInits();
726 if (!GlobalInits.empty() || !AliasInits.empty())
727 return Error("Malformed global initializer set");
728 if (!FunctionsWithBodies.empty())
729 return Error("Too few function bodies found");
731 // Force deallocation of memory for these vectors to favor the client that
732 // want lazy deserialization.
733 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
734 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
735 std::vector<Function*>().swap(FunctionsWithBodies);
739 if (Code == bitc::ENTER_SUBBLOCK) {
740 switch (Stream.ReadSubBlockID()) {
741 default: // Skip unknown content.
742 if (Stream.SkipBlock())
743 return Error("Malformed block record");
745 case bitc::TYPE_BLOCK_ID:
746 if (ParseTypeTable())
749 case bitc::TYPE_SYMTAB_BLOCK_ID:
750 if (ParseTypeSymbolTable())
753 case bitc::VALUE_SYMTAB_BLOCK_ID:
754 if (ParseValueSymbolTable())
757 case bitc::CONSTANTS_BLOCK_ID:
758 if (ParseConstants() || ResolveGlobalAndAliasInits())
761 case bitc::FUNCTION_BLOCK_ID:
762 // If this is the first function body we've seen, reverse the
763 // FunctionsWithBodies list.
764 if (!HasReversedFunctionsWithBodies) {
765 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
766 HasReversedFunctionsWithBodies = true;
769 if (RememberAndSkipFunctionBody())
776 if (Code == bitc::DEFINE_ABBREV) {
777 Stream.ReadAbbrevRecord();
782 switch (Stream.ReadRecord(Code, Record)) {
783 default: break; // Default behavior, ignore unknown content.
784 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
785 if (Record.size() < 1)
786 return Error("Malformed MODULE_CODE_VERSION");
787 // Only version #0 is supported so far.
789 return Error("Unknown bitstream version!");
791 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
793 if (ConvertToString(Record, 0, S))
794 return Error("Invalid MODULE_CODE_TRIPLE record");
795 TheModule->setTargetTriple(S);
798 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
800 if (ConvertToString(Record, 0, S))
801 return Error("Invalid MODULE_CODE_DATALAYOUT record");
802 TheModule->setDataLayout(S);
805 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
807 if (ConvertToString(Record, 0, S))
808 return Error("Invalid MODULE_CODE_ASM record");
809 TheModule->setModuleInlineAsm(S);
812 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
814 if (ConvertToString(Record, 0, S))
815 return Error("Invalid MODULE_CODE_DEPLIB record");
816 TheModule->addLibrary(S);
819 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
821 if (ConvertToString(Record, 0, S))
822 return Error("Invalid MODULE_CODE_SECTIONNAME record");
823 SectionTable.push_back(S);
826 // GLOBALVAR: [type, isconst, initid,
827 // linkage, alignment, section, visibility, threadlocal]
828 case bitc::MODULE_CODE_GLOBALVAR: {
829 if (Record.size() < 6)
830 return Error("Invalid MODULE_CODE_GLOBALVAR record");
831 const Type *Ty = getTypeByID(Record[0]);
832 if (!isa<PointerType>(Ty))
833 return Error("Global not a pointer type!");
834 Ty = cast<PointerType>(Ty)->getElementType();
836 bool isConstant = Record[1];
837 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
838 unsigned Alignment = (1 << Record[4]) >> 1;
841 if (Record[5]-1 >= SectionTable.size())
842 return Error("Invalid section ID");
843 Section = SectionTable[Record[5]-1];
845 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
846 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
847 bool isThreadLocal = false;
848 if (Record.size() >= 7) isThreadLocal = Record[7];
850 GlobalVariable *NewGV =
851 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
852 NewGV->setAlignment(Alignment);
853 if (!Section.empty())
854 NewGV->setSection(Section);
855 NewGV->setVisibility(Visibility);
856 NewGV->setThreadLocal(isThreadLocal);
858 ValueList.push_back(NewGV);
860 // Remember which value to use for the global initializer.
861 if (unsigned InitID = Record[2])
862 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
865 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
867 case bitc::MODULE_CODE_FUNCTION: {
868 if (Record.size() < 7)
869 return Error("Invalid MODULE_CODE_FUNCTION record");
870 const Type *Ty = getTypeByID(Record[0]);
871 if (!isa<PointerType>(Ty))
872 return Error("Function not a pointer type!");
873 const FunctionType *FTy =
874 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
876 return Error("Function not a pointer to function type!");
878 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
881 Func->setCallingConv(Record[1]);
882 bool isProto = Record[2];
883 Func->setLinkage(GetDecodedLinkage(Record[3]));
884 Func->setAlignment((1 << Record[4]) >> 1);
886 if (Record[5]-1 >= SectionTable.size())
887 return Error("Invalid section ID");
888 Func->setSection(SectionTable[Record[5]-1]);
890 Func->setVisibility(GetDecodedVisibility(Record[6]));
892 ValueList.push_back(Func);
894 // If this is a function with a body, remember the prototype we are
895 // creating now, so that we can match up the body with them later.
897 FunctionsWithBodies.push_back(Func);
900 // ALIAS: [alias type, aliasee val#, linkage]
901 case bitc::MODULE_CODE_ALIAS: {
902 if (Record.size() < 3)
903 return Error("Invalid MODULE_ALIAS record");
904 const Type *Ty = getTypeByID(Record[0]);
905 if (!isa<PointerType>(Ty))
906 return Error("Function not a pointer type!");
908 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
910 ValueList.push_back(NewGA);
911 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
914 /// MODULE_CODE_PURGEVALS: [numvals]
915 case bitc::MODULE_CODE_PURGEVALS:
916 // Trim down the value list to the specified size.
917 if (Record.size() < 1 || Record[0] > ValueList.size())
918 return Error("Invalid MODULE_PURGEVALS record");
919 ValueList.shrinkTo(Record[0]);
925 return Error("Premature end of bitstream");
929 bool BitcodeReader::ParseBitcode() {
932 if (Buffer->getBufferSize() & 3)
933 return Error("Bitcode stream should be a multiple of 4 bytes in length");
935 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
936 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
938 // Sniff for the signature.
939 if (Stream.Read(8) != 'B' ||
940 Stream.Read(8) != 'C' ||
941 Stream.Read(4) != 0x0 ||
942 Stream.Read(4) != 0xC ||
943 Stream.Read(4) != 0xE ||
944 Stream.Read(4) != 0xD)
945 return Error("Invalid bitcode signature");
947 // We expect a number of well-defined blocks, though we don't necessarily
948 // need to understand them all.
949 while (!Stream.AtEndOfStream()) {
950 unsigned Code = Stream.ReadCode();
952 if (Code != bitc::ENTER_SUBBLOCK)
953 return Error("Invalid record at top-level");
955 unsigned BlockID = Stream.ReadSubBlockID();
957 // We only know the MODULE subblock ID.
958 if (BlockID == bitc::MODULE_BLOCK_ID) {
959 if (ParseModule(Buffer->getBufferIdentifier()))
961 } else if (Stream.SkipBlock()) {
962 return Error("Malformed block record");
970 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
971 // If it already is material, ignore the request.
972 if (!F->hasNotBeenReadFromBytecode()) return false;
974 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
975 DeferredFunctionInfo.find(F);
976 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
978 // Move the bit stream to the saved position of the deferred function body and
979 // restore the real linkage type for the function.
980 Stream.JumpToBit(DFII->second.first);
981 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
982 DeferredFunctionInfo.erase(DFII);
984 if (ParseFunctionBody(F)) {
985 if (ErrInfo) *ErrInfo = ErrorString;
992 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
993 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
994 DeferredFunctionInfo.begin();
995 while (!DeferredFunctionInfo.empty()) {
996 Function *F = (*I++).first;
997 assert(F->hasNotBeenReadFromBytecode() &&
998 "Deserialized function found in map!");
999 if (materializeFunction(F, ErrInfo))
1006 /// ParseFunctionBody - Lazily parse the specified function body block.
1007 bool BitcodeReader::ParseFunctionBody(Function *F) {
1008 if (Stream.EnterSubBlock())
1009 return Error("Malformed block record");
1011 unsigned ModuleValueListSize = ValueList.size();
1013 // Add all the function arguments to the value table.
1014 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1015 ValueList.push_back(I);
1017 unsigned NextValueNo = ValueList.size();
1018 BasicBlock *CurBB = 0;
1019 unsigned CurBBNo = 0;
1021 // Read all the records.
1022 SmallVector<uint64_t, 64> Record;
1024 unsigned Code = Stream.ReadCode();
1025 if (Code == bitc::END_BLOCK) {
1026 if (Stream.ReadBlockEnd())
1027 return Error("Error at end of function block");
1031 if (Code == bitc::ENTER_SUBBLOCK) {
1032 switch (Stream.ReadSubBlockID()) {
1033 default: // Skip unknown content.
1034 if (Stream.SkipBlock())
1035 return Error("Malformed block record");
1037 case bitc::CONSTANTS_BLOCK_ID:
1038 if (ParseConstants()) return true;
1039 NextValueNo = ValueList.size();
1041 case bitc::VALUE_SYMTAB_BLOCK_ID:
1042 if (ParseValueSymbolTable()) return true;
1048 if (Code == bitc::DEFINE_ABBREV) {
1049 Stream.ReadAbbrevRecord();
1056 switch (Stream.ReadRecord(Code, Record)) {
1057 default: // Default behavior: reject
1058 return Error("Unknown instruction");
1059 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1060 if (Record.size() < 1 || Record[0] == 0)
1061 return Error("Invalid DECLAREBLOCKS record");
1062 // Create all the basic blocks for the function.
1063 FunctionBBs.resize(Record[0]);
1064 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1065 FunctionBBs[i] = new BasicBlock("", F);
1066 CurBB = FunctionBBs[0];
1069 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
1070 if (Record.size() < 4) return Error("Invalid BINOP record");
1071 const Type *Ty = getTypeByID(Record[1]);
1072 int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1073 Value *LHS = getFnValueByID(Record[2], Ty);
1074 Value *RHS = getFnValueByID(Record[3], Ty);
1075 if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1076 return Error("Invalid BINOP record");
1077 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1080 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
1081 if (Record.size() < 4) return Error("Invalid CAST record");
1082 int Opc = GetDecodedCastOpcode(Record[0]);
1083 const Type *ResTy = getTypeByID(Record[1]);
1084 const Type *OpTy = getTypeByID(Record[2]);
1085 Value *Op = getFnValueByID(Record[3], OpTy);
1086 if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1087 return Error("Invalid CAST record");
1088 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1091 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n, n x operands]
1092 if (Record.size() < 2 || (Record.size() & 1))
1093 return Error("Invalid GEP record");
1094 const Type *OpTy = getTypeByID(Record[0]);
1095 Value *Op = getFnValueByID(Record[1], OpTy);
1096 if (OpTy == 0 || Op == 0)
1097 return Error("Invalid GEP record");
1099 SmallVector<Value*, 16> GEPIdx;
1100 for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
1101 const Type *IdxTy = getTypeByID(Record[i*2]);
1102 Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
1103 if (IdxTy == 0 || Idx == 0)
1104 return Error("Invalid GEP record");
1105 GEPIdx.push_back(Idx);
1108 I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
1112 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
1113 if (Record.size() < 4) return Error("Invalid SELECT record");
1114 const Type *Ty = getTypeByID(Record[0]);
1115 Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
1116 Value *LHS = getFnValueByID(Record[2], Ty);
1117 Value *RHS = getFnValueByID(Record[3], Ty);
1118 if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
1119 return Error("Invalid SELECT record");
1120 I = new SelectInst(Cond, LHS, RHS);
1124 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1125 if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
1126 const Type *OpTy = getTypeByID(Record[0]);
1127 Value *Vec = getFnValueByID(Record[1], OpTy);
1128 Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
1129 if (OpTy == 0 || Vec == 0 || Idx == 0)
1130 return Error("Invalid EXTRACTELT record");
1131 I = new ExtractElementInst(Vec, Idx);
1135 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1136 if (Record.size() < 4) return Error("Invalid INSERTELT record");
1137 const VectorType *OpTy =
1138 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1139 if (OpTy == 0) return Error("Invalid INSERTELT record");
1140 Value *Vec = getFnValueByID(Record[1], OpTy);
1141 Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
1142 Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
1143 if (Vec == 0 || Elt == 0 || Idx == 0)
1144 return Error("Invalid INSERTELT record");
1145 I = new InsertElementInst(Vec, Elt, Idx);
1149 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
1150 if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
1151 const VectorType *OpTy =
1152 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1153 if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
1154 Value *Vec1 = getFnValueByID(Record[1], OpTy);
1155 Value *Vec2 = getFnValueByID(Record[2], OpTy);
1156 Value *Mask = getFnValueByID(Record[3],
1157 VectorType::get(Type::Int32Ty,
1158 OpTy->getNumElements()));
1159 if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
1160 return Error("Invalid SHUFFLEVEC record");
1161 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1165 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1166 if (Record.size() < 4) return Error("Invalid CMP record");
1167 const Type *OpTy = getTypeByID(Record[0]);
1168 Value *LHS = getFnValueByID(Record[1], OpTy);
1169 Value *RHS = getFnValueByID(Record[2], OpTy);
1170 if (OpTy == 0 || LHS == 0 || RHS == 0)
1171 return Error("Invalid CMP record");
1172 if (OpTy->isFPOrFPVector())
1173 I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
1175 I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
1179 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1180 if (Record.size() == 0) {
1181 I = new ReturnInst();
1184 if (Record.size() == 2) {
1185 const Type *OpTy = getTypeByID(Record[0]);
1186 Value *Op = getFnValueByID(Record[1], OpTy);
1188 return Error("Invalid RET record");
1189 I = new ReturnInst(Op);
1192 return Error("Invalid RET record");
1193 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1194 if (Record.size() != 1 && Record.size() != 3)
1195 return Error("Invalid BR record");
1196 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1198 return Error("Invalid BR record");
1200 if (Record.size() == 1)
1201 I = new BranchInst(TrueDest);
1203 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1204 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1205 if (FalseDest == 0 || Cond == 0)
1206 return Error("Invalid BR record");
1207 I = new BranchInst(TrueDest, FalseDest, Cond);
1211 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1212 if (Record.size() < 3 || (Record.size() & 1) == 0)
1213 return Error("Invalid SWITCH record");
1214 const Type *OpTy = getTypeByID(Record[0]);
1215 Value *Cond = getFnValueByID(Record[1], OpTy);
1216 BasicBlock *Default = getBasicBlock(Record[2]);
1217 if (OpTy == 0 || Cond == 0 || Default == 0)
1218 return Error("Invalid SWITCH record");
1219 unsigned NumCases = (Record.size()-3)/2;
1220 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1221 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1222 ConstantInt *CaseVal =
1223 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1224 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1225 if (CaseVal == 0 || DestBB == 0) {
1227 return Error("Invalid SWITCH record!");
1229 SI->addCase(CaseVal, DestBB);
1235 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1236 if (Record.size() < 5)
1237 return Error("Invalid INVOKE record");
1238 unsigned CCInfo = Record[0];
1239 const PointerType *CalleeTy =
1240 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
1241 Value *Callee = getFnValueByID(Record[2], CalleeTy);
1242 BasicBlock *NormalBB = getBasicBlock(Record[3]);
1243 BasicBlock *UnwindBB = getBasicBlock(Record[4]);
1244 if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
1245 return Error("Invalid INVOKE record");
1247 const FunctionType *FTy =
1248 dyn_cast<FunctionType>(CalleeTy->getElementType());
1250 // Check that the right number of fixed parameters are here.
1251 if (FTy == 0 || Record.size() < 5+FTy->getNumParams())
1252 return Error("Invalid INVOKE record");
1254 SmallVector<Value*, 16> Ops;
1255 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1256 Ops.push_back(getFnValueByID(Record[5+i], FTy->getParamType(i)));
1257 if (Ops.back() == 0)
1258 return Error("Invalid INVOKE record");
1261 unsigned FirstVarargParam = 5+FTy->getNumParams();
1262 if (FTy->isVarArg()) {
1263 // Read type/value pairs for varargs params.
1264 if ((Record.size()-FirstVarargParam) & 1)
1265 return Error("Invalid INVOKE record");
1267 for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
1268 const Type *ArgTy = getTypeByID(Record[i]);
1269 Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
1270 if (Ops.back() == 0 || ArgTy == 0)
1271 return Error("Invalid INVOKE record");
1274 if (Record.size() != FirstVarargParam)
1275 return Error("Invalid INVOKE record");
1278 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1279 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1282 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1283 I = new UnwindInst();
1285 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1286 I = new UnreachableInst();
1288 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
1289 if (Record.size() < 2 || Record.size() < 2+Record[1] || (Record[1]&1))
1290 return Error("Invalid PHI record");
1291 const Type *Ty = getTypeByID(Record[0]);
1292 if (!Ty) return Error("Invalid PHI record");
1294 PHINode *PN = new PHINode(Ty);
1295 PN->reserveOperandSpace(Record[1]);
1297 for (unsigned i = 0, e = Record[1]; i != e; i += 2) {
1298 Value *V = getFnValueByID(Record[2+i], Ty);
1299 BasicBlock *BB = getBasicBlock(Record[3+i]);
1300 if (!V || !BB) return Error("Invalid PHI record");
1301 PN->addIncoming(V, BB);
1307 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1308 if (Record.size() < 3)
1309 return Error("Invalid MALLOC record");
1310 const PointerType *Ty =
1311 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1312 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1313 unsigned Align = Record[2];
1314 if (!Ty || !Size) return Error("Invalid MALLOC record");
1315 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1318 case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
1319 if (Record.size() < 2)
1320 return Error("Invalid FREE record");
1321 const Type *OpTy = getTypeByID(Record[0]);
1322 Value *Op = getFnValueByID(Record[1], OpTy);
1324 return Error("Invalid FREE record");
1325 I = new FreeInst(Op);
1328 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1329 if (Record.size() < 3)
1330 return Error("Invalid ALLOCA record");
1331 const PointerType *Ty =
1332 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1333 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1334 unsigned Align = Record[2];
1335 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1336 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1339 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1340 if (Record.size() < 4)
1341 return Error("Invalid LOAD record");
1342 const Type *OpTy = getTypeByID(Record[0]);
1343 Value *Op = getFnValueByID(Record[1], OpTy);
1345 return Error("Invalid LOAD record");
1346 I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
1349 case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
1350 if (Record.size() < 5)
1351 return Error("Invalid LOAD record");
1352 const PointerType *OpTy =
1353 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1354 Value *Op = getFnValueByID(Record[1], OpTy ? OpTy->getElementType() : 0);
1355 Value *Ptr = getFnValueByID(Record[2], OpTy);
1356 if (!OpTy || !Op || !Ptr)
1357 return Error("Invalid STORE record");
1358 I = new StoreInst(Op, Ptr, (1 << Record[3]) >> 1, Record[4]);
1361 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1362 if (Record.size() < 3)
1363 return Error("Invalid CALL record");
1364 unsigned CCInfo = Record[0];
1365 const PointerType *OpTy =
1366 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
1367 const FunctionType *FTy = 0;
1368 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1369 Value *Callee = getFnValueByID(Record[2], OpTy);
1370 if (!FTy || !Callee || Record.size() < FTy->getNumParams()+3)
1371 return Error("Invalid CALL record");
1373 SmallVector<Value*, 16> Args;
1374 // Read the fixed params.
1375 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1376 Args.push_back(getFnValueByID(Record[i+3], FTy->getParamType(i)));
1377 if (Args.back() == 0) return Error("Invalid CALL record");
1381 // Read type/value pairs for varargs params.
1382 unsigned NextArg = FTy->getNumParams()+3;
1383 if (!FTy->isVarArg()) {
1384 if (NextArg != Record.size())
1385 return Error("Invalid CALL record");
1387 if ((Record.size()-NextArg) & 1)
1388 return Error("Invalid CALL record");
1389 for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
1390 Args.push_back(getFnValueByID(Record[NextArg+1],
1391 getTypeByID(Record[NextArg])));
1392 if (Args.back() == 0) return Error("Invalid CALL record");
1396 I = new CallInst(Callee, &Args[0], Args.size());
1397 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1398 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1401 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1402 if (Record.size() < 3)
1403 return Error("Invalid VAARG record");
1404 const Type *OpTy = getTypeByID(Record[0]);
1405 Value *Op = getFnValueByID(Record[1], OpTy);
1406 const Type *ResTy = getTypeByID(Record[2]);
1407 if (!OpTy || !Op || !ResTy)
1408 return Error("Invalid VAARG record");
1409 I = new VAArgInst(Op, ResTy);
1414 // Add instruction to end of current BB. If there is no current BB, reject
1418 return Error("Invalid instruction with no BB");
1420 CurBB->getInstList().push_back(I);
1422 // If this was a terminator instruction, move to the next block.
1423 if (isa<TerminatorInst>(I)) {
1425 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1428 // Non-void values get registered in the value table for future use.
1429 if (I && I->getType() != Type::VoidTy)
1430 ValueList.AssignValue(I, NextValueNo++);
1433 // Check the function list for unresolved values.
1434 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1435 if (A->getParent() == 0) {
1436 // We found at least one unresolved value. Nuke them all to avoid leaks.
1437 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1438 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1439 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1444 return Error("Never resolved value found in function!");
1447 // Trim the value list down to the size it was before we parsed this function.
1448 ValueList.shrinkTo(ModuleValueListSize);
1449 std::vector<BasicBlock*>().swap(FunctionBBs);
1455 //===----------------------------------------------------------------------===//
1456 // External interface
1457 //===----------------------------------------------------------------------===//
1459 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1461 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1462 std::string *ErrMsg) {
1463 BitcodeReader *R = new BitcodeReader(Buffer);
1464 if (R->ParseBitcode()) {
1466 *ErrMsg = R->getErrorString();
1468 // Don't let the BitcodeReader dtor delete 'Buffer'.
1469 R->releaseMemoryBuffer();
1476 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1477 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1478 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1480 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1483 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1484 // delete it when its dtor is run.
1485 Module *M = R->releaseModule(ErrMsg);
1487 // Don't let the BitcodeReader dtor delete 'Buffer'.
1488 R->releaseMemoryBuffer();