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::VST_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());
414 case bitc::VST_CODE_BBENTRY:
415 if (ConvertToString(Record, 1, ValueName))
416 return Error("Invalid VST_BBENTRY record");
417 BasicBlock *BB = getBasicBlock(Record[0]);
419 return Error("Invalid BB ID in VST_BBENTRY record");
421 BB->setName(&ValueName[0], ValueName.size());
428 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
429 /// the LSB for dense VBR encoding.
430 static uint64_t DecodeSignRotatedValue(uint64_t V) {
435 // There is no such thing as -0 with integers. "-0" really means MININT.
439 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
440 /// values and aliases that we can.
441 bool BitcodeReader::ResolveGlobalAndAliasInits() {
442 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
443 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
445 GlobalInitWorklist.swap(GlobalInits);
446 AliasInitWorklist.swap(AliasInits);
448 while (!GlobalInitWorklist.empty()) {
449 unsigned ValID = GlobalInitWorklist.back().second;
450 if (ValID >= ValueList.size()) {
451 // Not ready to resolve this yet, it requires something later in the file.
452 GlobalInits.push_back(GlobalInitWorklist.back());
454 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
455 GlobalInitWorklist.back().first->setInitializer(C);
457 return Error("Global variable initializer is not a constant!");
459 GlobalInitWorklist.pop_back();
462 while (!AliasInitWorklist.empty()) {
463 unsigned ValID = AliasInitWorklist.back().second;
464 if (ValID >= ValueList.size()) {
465 AliasInits.push_back(AliasInitWorklist.back());
467 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
468 AliasInitWorklist.back().first->setAliasee(C);
470 return Error("Alias initializer is not a constant!");
472 AliasInitWorklist.pop_back();
478 bool BitcodeReader::ParseConstants() {
479 if (Stream.EnterSubBlock())
480 return Error("Malformed block record");
482 SmallVector<uint64_t, 64> Record;
484 // Read all the records for this value table.
485 const Type *CurTy = Type::Int32Ty;
486 unsigned NextCstNo = ValueList.size();
488 unsigned Code = Stream.ReadCode();
489 if (Code == bitc::END_BLOCK) {
490 if (NextCstNo != ValueList.size())
491 return Error("Invalid constant reference!");
493 if (Stream.ReadBlockEnd())
494 return Error("Error at end of constants block");
498 if (Code == bitc::ENTER_SUBBLOCK) {
499 // No known subblocks, always skip them.
500 Stream.ReadSubBlockID();
501 if (Stream.SkipBlock())
502 return Error("Malformed block record");
506 if (Code == bitc::DEFINE_ABBREV) {
507 Stream.ReadAbbrevRecord();
514 switch (Stream.ReadRecord(Code, Record)) {
515 default: // Default behavior: unknown constant
516 case bitc::CST_CODE_UNDEF: // UNDEF
517 V = UndefValue::get(CurTy);
519 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
521 return Error("Malformed CST_SETTYPE record");
522 if (Record[0] >= TypeList.size())
523 return Error("Invalid Type ID in CST_SETTYPE record");
524 CurTy = TypeList[Record[0]];
525 continue; // Skip the ValueList manipulation.
526 case bitc::CST_CODE_NULL: // NULL
527 V = Constant::getNullValue(CurTy);
529 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
530 if (!isa<IntegerType>(CurTy) || Record.empty())
531 return Error("Invalid CST_INTEGER record");
532 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
534 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
535 if (!isa<IntegerType>(CurTy) || Record.empty() ||
536 Record.size() < Record[0]+1)
537 return Error("Invalid WIDE_INTEGER record");
539 unsigned NumWords = Record[0];
540 SmallVector<uint64_t, 8> Words;
541 Words.resize(NumWords);
542 for (unsigned i = 0; i != NumWords; ++i)
543 Words[i] = DecodeSignRotatedValue(Record[i+1]);
544 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
545 NumWords, &Words[0]));
548 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
550 return Error("Invalid FLOAT record");
551 if (CurTy == Type::FloatTy)
552 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
553 else if (CurTy == Type::DoubleTy)
554 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
556 V = UndefValue::get(CurTy);
559 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
560 if (Record.empty() || Record.size() < Record[0]+1)
561 return Error("Invalid CST_AGGREGATE record");
563 unsigned Size = Record[0];
564 std::vector<Constant*> Elts;
566 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
567 for (unsigned i = 0; i != Size; ++i)
568 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
569 STy->getElementType(i)));
570 V = ConstantStruct::get(STy, Elts);
571 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
572 const Type *EltTy = ATy->getElementType();
573 for (unsigned i = 0; i != Size; ++i)
574 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
575 V = ConstantArray::get(ATy, Elts);
576 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
577 const Type *EltTy = VTy->getElementType();
578 for (unsigned i = 0; i != Size; ++i)
579 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
580 V = ConstantVector::get(Elts);
582 V = UndefValue::get(CurTy);
587 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
588 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
589 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
591 V = UndefValue::get(CurTy); // Unknown binop.
593 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
594 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
595 V = ConstantExpr::get(Opc, LHS, RHS);
599 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
600 if (Record.size() < 3) return Error("Invalid CE_CAST record");
601 int Opc = GetDecodedCastOpcode(Record[0]);
603 V = UndefValue::get(CurTy); // Unknown cast.
605 const Type *OpTy = getTypeByID(Record[1]);
606 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
607 V = ConstantExpr::getCast(Opc, Op, CurTy);
611 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
612 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
613 SmallVector<Constant*, 16> Elts;
614 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
615 const Type *ElTy = getTypeByID(Record[i]);
616 if (!ElTy) return Error("Invalid CE_GEP record");
617 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
619 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
622 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
623 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
624 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
626 ValueList.getConstantFwdRef(Record[1],CurTy),
627 ValueList.getConstantFwdRef(Record[2],CurTy));
629 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
630 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
631 const VectorType *OpTy =
632 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
633 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
634 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
635 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
636 OpTy->getElementType());
637 V = ConstantExpr::getExtractElement(Op0, Op1);
640 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
641 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
642 if (Record.size() < 3 || OpTy == 0)
643 return Error("Invalid CE_INSERTELT record");
644 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
645 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
646 OpTy->getElementType());
647 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
648 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
651 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
652 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
653 if (Record.size() < 3 || OpTy == 0)
654 return Error("Invalid CE_INSERTELT record");
655 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
656 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
657 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
658 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
659 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
662 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
663 if (Record.size() < 4) return Error("Invalid CE_CMP record");
664 const Type *OpTy = getTypeByID(Record[0]);
665 if (OpTy == 0) return Error("Invalid CE_CMP record");
666 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
667 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
669 if (OpTy->isFloatingPoint())
670 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
672 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
677 ValueList.AssignValue(V, NextCstNo);
682 /// RememberAndSkipFunctionBody - When we see the block for a function body,
683 /// remember where it is and then skip it. This lets us lazily deserialize the
685 bool BitcodeReader::RememberAndSkipFunctionBody() {
686 // Get the function we are talking about.
687 if (FunctionsWithBodies.empty())
688 return Error("Insufficient function protos");
690 Function *Fn = FunctionsWithBodies.back();
691 FunctionsWithBodies.pop_back();
693 // Save the current stream state.
694 uint64_t CurBit = Stream.GetCurrentBitNo();
695 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
697 // Set the functions linkage to GhostLinkage so we know it is lazily
699 Fn->setLinkage(GlobalValue::GhostLinkage);
701 // Skip over the function block for now.
702 if (Stream.SkipBlock())
703 return Error("Malformed block record");
707 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
708 // Reject multiple MODULE_BLOCK's in a single bitstream.
710 return Error("Multiple MODULE_BLOCKs in same stream");
712 if (Stream.EnterSubBlock())
713 return Error("Malformed block record");
715 // Otherwise, create the module.
716 TheModule = new Module(ModuleID);
718 SmallVector<uint64_t, 64> Record;
719 std::vector<std::string> SectionTable;
721 // Read all the records for this module.
722 while (!Stream.AtEndOfStream()) {
723 unsigned Code = Stream.ReadCode();
724 if (Code == bitc::END_BLOCK) {
725 if (Stream.ReadBlockEnd())
726 return Error("Error at end of module block");
728 // Patch the initializers for globals and aliases up.
729 ResolveGlobalAndAliasInits();
730 if (!GlobalInits.empty() || !AliasInits.empty())
731 return Error("Malformed global initializer set");
732 if (!FunctionsWithBodies.empty())
733 return Error("Too few function bodies found");
735 // Force deallocation of memory for these vectors to favor the client that
736 // want lazy deserialization.
737 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
738 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
739 std::vector<Function*>().swap(FunctionsWithBodies);
743 if (Code == bitc::ENTER_SUBBLOCK) {
744 switch (Stream.ReadSubBlockID()) {
745 default: // Skip unknown content.
746 if (Stream.SkipBlock())
747 return Error("Malformed block record");
749 case bitc::TYPE_BLOCK_ID:
750 if (ParseTypeTable())
753 case bitc::TYPE_SYMTAB_BLOCK_ID:
754 if (ParseTypeSymbolTable())
757 case bitc::VALUE_SYMTAB_BLOCK_ID:
758 if (ParseValueSymbolTable())
761 case bitc::CONSTANTS_BLOCK_ID:
762 if (ParseConstants() || ResolveGlobalAndAliasInits())
765 case bitc::FUNCTION_BLOCK_ID:
766 // If this is the first function body we've seen, reverse the
767 // FunctionsWithBodies list.
768 if (!HasReversedFunctionsWithBodies) {
769 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
770 HasReversedFunctionsWithBodies = true;
773 if (RememberAndSkipFunctionBody())
780 if (Code == bitc::DEFINE_ABBREV) {
781 Stream.ReadAbbrevRecord();
786 switch (Stream.ReadRecord(Code, Record)) {
787 default: break; // Default behavior, ignore unknown content.
788 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
789 if (Record.size() < 1)
790 return Error("Malformed MODULE_CODE_VERSION");
791 // Only version #0 is supported so far.
793 return Error("Unknown bitstream version!");
795 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
797 if (ConvertToString(Record, 0, S))
798 return Error("Invalid MODULE_CODE_TRIPLE record");
799 TheModule->setTargetTriple(S);
802 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
804 if (ConvertToString(Record, 0, S))
805 return Error("Invalid MODULE_CODE_DATALAYOUT record");
806 TheModule->setDataLayout(S);
809 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
811 if (ConvertToString(Record, 0, S))
812 return Error("Invalid MODULE_CODE_ASM record");
813 TheModule->setModuleInlineAsm(S);
816 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
818 if (ConvertToString(Record, 0, S))
819 return Error("Invalid MODULE_CODE_DEPLIB record");
820 TheModule->addLibrary(S);
823 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
825 if (ConvertToString(Record, 0, S))
826 return Error("Invalid MODULE_CODE_SECTIONNAME record");
827 SectionTable.push_back(S);
830 // GLOBALVAR: [type, isconst, initid,
831 // linkage, alignment, section, visibility, threadlocal]
832 case bitc::MODULE_CODE_GLOBALVAR: {
833 if (Record.size() < 6)
834 return Error("Invalid MODULE_CODE_GLOBALVAR record");
835 const Type *Ty = getTypeByID(Record[0]);
836 if (!isa<PointerType>(Ty))
837 return Error("Global not a pointer type!");
838 Ty = cast<PointerType>(Ty)->getElementType();
840 bool isConstant = Record[1];
841 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
842 unsigned Alignment = (1 << Record[4]) >> 1;
845 if (Record[5]-1 >= SectionTable.size())
846 return Error("Invalid section ID");
847 Section = SectionTable[Record[5]-1];
849 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
850 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
851 bool isThreadLocal = false;
852 if (Record.size() >= 7) isThreadLocal = Record[7];
854 GlobalVariable *NewGV =
855 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
856 NewGV->setAlignment(Alignment);
857 if (!Section.empty())
858 NewGV->setSection(Section);
859 NewGV->setVisibility(Visibility);
860 NewGV->setThreadLocal(isThreadLocal);
862 ValueList.push_back(NewGV);
864 // Remember which value to use for the global initializer.
865 if (unsigned InitID = Record[2])
866 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
869 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
871 case bitc::MODULE_CODE_FUNCTION: {
872 if (Record.size() < 7)
873 return Error("Invalid MODULE_CODE_FUNCTION record");
874 const Type *Ty = getTypeByID(Record[0]);
875 if (!isa<PointerType>(Ty))
876 return Error("Function not a pointer type!");
877 const FunctionType *FTy =
878 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
880 return Error("Function not a pointer to function type!");
882 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
885 Func->setCallingConv(Record[1]);
886 bool isProto = Record[2];
887 Func->setLinkage(GetDecodedLinkage(Record[3]));
888 Func->setAlignment((1 << Record[4]) >> 1);
890 if (Record[5]-1 >= SectionTable.size())
891 return Error("Invalid section ID");
892 Func->setSection(SectionTable[Record[5]-1]);
894 Func->setVisibility(GetDecodedVisibility(Record[6]));
896 ValueList.push_back(Func);
898 // If this is a function with a body, remember the prototype we are
899 // creating now, so that we can match up the body with them later.
901 FunctionsWithBodies.push_back(Func);
904 // ALIAS: [alias type, aliasee val#, linkage]
905 case bitc::MODULE_CODE_ALIAS: {
906 if (Record.size() < 3)
907 return Error("Invalid MODULE_ALIAS record");
908 const Type *Ty = getTypeByID(Record[0]);
909 if (!isa<PointerType>(Ty))
910 return Error("Function not a pointer type!");
912 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
914 ValueList.push_back(NewGA);
915 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
918 /// MODULE_CODE_PURGEVALS: [numvals]
919 case bitc::MODULE_CODE_PURGEVALS:
920 // Trim down the value list to the specified size.
921 if (Record.size() < 1 || Record[0] > ValueList.size())
922 return Error("Invalid MODULE_PURGEVALS record");
923 ValueList.shrinkTo(Record[0]);
929 return Error("Premature end of bitstream");
933 bool BitcodeReader::ParseBitcode() {
936 if (Buffer->getBufferSize() & 3)
937 return Error("Bitcode stream should be a multiple of 4 bytes in length");
939 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
940 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
942 // Sniff for the signature.
943 if (Stream.Read(8) != 'B' ||
944 Stream.Read(8) != 'C' ||
945 Stream.Read(4) != 0x0 ||
946 Stream.Read(4) != 0xC ||
947 Stream.Read(4) != 0xE ||
948 Stream.Read(4) != 0xD)
949 return Error("Invalid bitcode signature");
951 // We expect a number of well-defined blocks, though we don't necessarily
952 // need to understand them all.
953 while (!Stream.AtEndOfStream()) {
954 unsigned Code = Stream.ReadCode();
956 if (Code != bitc::ENTER_SUBBLOCK)
957 return Error("Invalid record at top-level");
959 unsigned BlockID = Stream.ReadSubBlockID();
961 // We only know the MODULE subblock ID.
962 if (BlockID == bitc::MODULE_BLOCK_ID) {
963 if (ParseModule(Buffer->getBufferIdentifier()))
965 } else if (Stream.SkipBlock()) {
966 return Error("Malformed block record");
974 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
975 // If it already is material, ignore the request.
976 if (!F->hasNotBeenReadFromBytecode()) return false;
978 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
979 DeferredFunctionInfo.find(F);
980 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
982 // Move the bit stream to the saved position of the deferred function body and
983 // restore the real linkage type for the function.
984 Stream.JumpToBit(DFII->second.first);
985 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
986 DeferredFunctionInfo.erase(DFII);
988 if (ParseFunctionBody(F)) {
989 if (ErrInfo) *ErrInfo = ErrorString;
996 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
997 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
998 DeferredFunctionInfo.begin();
999 while (!DeferredFunctionInfo.empty()) {
1000 Function *F = (*I++).first;
1001 assert(F->hasNotBeenReadFromBytecode() &&
1002 "Deserialized function found in map!");
1003 if (materializeFunction(F, ErrInfo))
1010 /// ParseFunctionBody - Lazily parse the specified function body block.
1011 bool BitcodeReader::ParseFunctionBody(Function *F) {
1012 if (Stream.EnterSubBlock())
1013 return Error("Malformed block record");
1015 unsigned ModuleValueListSize = ValueList.size();
1017 // Add all the function arguments to the value table.
1018 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1019 ValueList.push_back(I);
1021 unsigned NextValueNo = ValueList.size();
1022 BasicBlock *CurBB = 0;
1023 unsigned CurBBNo = 0;
1025 // Read all the records.
1026 SmallVector<uint64_t, 64> Record;
1028 unsigned Code = Stream.ReadCode();
1029 if (Code == bitc::END_BLOCK) {
1030 if (Stream.ReadBlockEnd())
1031 return Error("Error at end of function block");
1035 if (Code == bitc::ENTER_SUBBLOCK) {
1036 switch (Stream.ReadSubBlockID()) {
1037 default: // Skip unknown content.
1038 if (Stream.SkipBlock())
1039 return Error("Malformed block record");
1041 case bitc::CONSTANTS_BLOCK_ID:
1042 if (ParseConstants()) return true;
1043 NextValueNo = ValueList.size();
1045 case bitc::VALUE_SYMTAB_BLOCK_ID:
1046 if (ParseValueSymbolTable()) return true;
1052 if (Code == bitc::DEFINE_ABBREV) {
1053 Stream.ReadAbbrevRecord();
1060 switch (Stream.ReadRecord(Code, Record)) {
1061 default: // Default behavior: reject
1062 return Error("Unknown instruction");
1063 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1064 if (Record.size() < 1 || Record[0] == 0)
1065 return Error("Invalid DECLAREBLOCKS record");
1066 // Create all the basic blocks for the function.
1067 FunctionBBs.resize(Record[0]);
1068 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1069 FunctionBBs[i] = new BasicBlock("", F);
1070 CurBB = FunctionBBs[0];
1073 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
1074 if (Record.size() < 4) return Error("Invalid BINOP record");
1075 const Type *Ty = getTypeByID(Record[1]);
1076 int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1077 Value *LHS = getFnValueByID(Record[2], Ty);
1078 Value *RHS = getFnValueByID(Record[3], Ty);
1079 if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1080 return Error("Invalid BINOP record");
1081 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1084 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
1085 if (Record.size() < 4) return Error("Invalid CAST record");
1086 int Opc = GetDecodedCastOpcode(Record[0]);
1087 const Type *ResTy = getTypeByID(Record[1]);
1088 const Type *OpTy = getTypeByID(Record[2]);
1089 Value *Op = getFnValueByID(Record[3], OpTy);
1090 if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1091 return Error("Invalid CAST record");
1092 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1095 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n, n x operands]
1096 if (Record.size() < 2 || (Record.size() & 1))
1097 return Error("Invalid GEP record");
1098 const Type *OpTy = getTypeByID(Record[0]);
1099 Value *Op = getFnValueByID(Record[1], OpTy);
1100 if (OpTy == 0 || Op == 0)
1101 return Error("Invalid GEP record");
1103 SmallVector<Value*, 16> GEPIdx;
1104 for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
1105 const Type *IdxTy = getTypeByID(Record[i*2]);
1106 Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
1107 if (IdxTy == 0 || Idx == 0)
1108 return Error("Invalid GEP record");
1109 GEPIdx.push_back(Idx);
1112 I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
1116 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
1117 if (Record.size() < 4) return Error("Invalid SELECT record");
1118 const Type *Ty = getTypeByID(Record[0]);
1119 Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
1120 Value *LHS = getFnValueByID(Record[2], Ty);
1121 Value *RHS = getFnValueByID(Record[3], Ty);
1122 if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
1123 return Error("Invalid SELECT record");
1124 I = new SelectInst(Cond, LHS, RHS);
1128 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1129 if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
1130 const Type *OpTy = getTypeByID(Record[0]);
1131 Value *Vec = getFnValueByID(Record[1], OpTy);
1132 Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
1133 if (OpTy == 0 || Vec == 0 || Idx == 0)
1134 return Error("Invalid EXTRACTELT record");
1135 I = new ExtractElementInst(Vec, Idx);
1139 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1140 if (Record.size() < 4) return Error("Invalid INSERTELT record");
1141 const VectorType *OpTy =
1142 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1143 if (OpTy == 0) return Error("Invalid INSERTELT record");
1144 Value *Vec = getFnValueByID(Record[1], OpTy);
1145 Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
1146 Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
1147 if (Vec == 0 || Elt == 0 || Idx == 0)
1148 return Error("Invalid INSERTELT record");
1149 I = new InsertElementInst(Vec, Elt, Idx);
1153 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
1154 if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
1155 const VectorType *OpTy =
1156 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1157 if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
1158 Value *Vec1 = getFnValueByID(Record[1], OpTy);
1159 Value *Vec2 = getFnValueByID(Record[2], OpTy);
1160 Value *Mask = getFnValueByID(Record[3],
1161 VectorType::get(Type::Int32Ty,
1162 OpTy->getNumElements()));
1163 if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
1164 return Error("Invalid SHUFFLEVEC record");
1165 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1169 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1170 if (Record.size() < 4) return Error("Invalid CMP record");
1171 const Type *OpTy = getTypeByID(Record[0]);
1172 Value *LHS = getFnValueByID(Record[1], OpTy);
1173 Value *RHS = getFnValueByID(Record[2], OpTy);
1174 if (OpTy == 0 || LHS == 0 || RHS == 0)
1175 return Error("Invalid CMP record");
1176 if (OpTy->isFPOrFPVector())
1177 I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
1179 I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
1183 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1184 if (Record.size() == 0) {
1185 I = new ReturnInst();
1188 if (Record.size() == 2) {
1189 const Type *OpTy = getTypeByID(Record[0]);
1190 Value *Op = getFnValueByID(Record[1], OpTy);
1192 return Error("Invalid RET record");
1193 I = new ReturnInst(Op);
1196 return Error("Invalid RET record");
1197 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1198 if (Record.size() != 1 && Record.size() != 3)
1199 return Error("Invalid BR record");
1200 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1202 return Error("Invalid BR record");
1204 if (Record.size() == 1)
1205 I = new BranchInst(TrueDest);
1207 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1208 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1209 if (FalseDest == 0 || Cond == 0)
1210 return Error("Invalid BR record");
1211 I = new BranchInst(TrueDest, FalseDest, Cond);
1215 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1216 if (Record.size() < 3 || (Record.size() & 1) == 0)
1217 return Error("Invalid SWITCH record");
1218 const Type *OpTy = getTypeByID(Record[0]);
1219 Value *Cond = getFnValueByID(Record[1], OpTy);
1220 BasicBlock *Default = getBasicBlock(Record[2]);
1221 if (OpTy == 0 || Cond == 0 || Default == 0)
1222 return Error("Invalid SWITCH record");
1223 unsigned NumCases = (Record.size()-3)/2;
1224 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1225 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1226 ConstantInt *CaseVal =
1227 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1228 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1229 if (CaseVal == 0 || DestBB == 0) {
1231 return Error("Invalid SWITCH record!");
1233 SI->addCase(CaseVal, DestBB);
1239 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1240 if (Record.size() < 5)
1241 return Error("Invalid INVOKE record");
1242 unsigned CCInfo = Record[0];
1243 const PointerType *CalleeTy =
1244 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
1245 Value *Callee = getFnValueByID(Record[2], CalleeTy);
1246 BasicBlock *NormalBB = getBasicBlock(Record[3]);
1247 BasicBlock *UnwindBB = getBasicBlock(Record[4]);
1248 if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
1249 return Error("Invalid INVOKE record");
1251 const FunctionType *FTy =
1252 dyn_cast<FunctionType>(CalleeTy->getElementType());
1254 // Check that the right number of fixed parameters are here.
1255 if (FTy == 0 || Record.size() < 5+FTy->getNumParams())
1256 return Error("Invalid INVOKE record");
1258 SmallVector<Value*, 16> Ops;
1259 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1260 Ops.push_back(getFnValueByID(Record[5+i], FTy->getParamType(i)));
1261 if (Ops.back() == 0)
1262 return Error("Invalid INVOKE record");
1265 unsigned FirstVarargParam = 5+FTy->getNumParams();
1266 if (FTy->isVarArg()) {
1267 // Read type/value pairs for varargs params.
1268 if ((Record.size()-FirstVarargParam) & 1)
1269 return Error("Invalid INVOKE record");
1271 for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
1272 const Type *ArgTy = getTypeByID(Record[i]);
1273 Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
1274 if (Ops.back() == 0 || ArgTy == 0)
1275 return Error("Invalid INVOKE record");
1278 if (Record.size() != FirstVarargParam)
1279 return Error("Invalid INVOKE record");
1282 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1283 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1286 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1287 I = new UnwindInst();
1289 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1290 I = new UnreachableInst();
1292 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
1293 if (Record.size() < 2 || Record.size() < 2+Record[1] || (Record[1]&1))
1294 return Error("Invalid PHI record");
1295 const Type *Ty = getTypeByID(Record[0]);
1296 if (!Ty) return Error("Invalid PHI record");
1298 PHINode *PN = new PHINode(Ty);
1299 PN->reserveOperandSpace(Record[1]);
1301 for (unsigned i = 0, e = Record[1]; i != e; i += 2) {
1302 Value *V = getFnValueByID(Record[2+i], Ty);
1303 BasicBlock *BB = getBasicBlock(Record[3+i]);
1304 if (!V || !BB) return Error("Invalid PHI record");
1305 PN->addIncoming(V, BB);
1311 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1312 if (Record.size() < 3)
1313 return Error("Invalid MALLOC record");
1314 const PointerType *Ty =
1315 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1316 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1317 unsigned Align = Record[2];
1318 if (!Ty || !Size) return Error("Invalid MALLOC record");
1319 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1322 case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
1323 if (Record.size() < 2)
1324 return Error("Invalid FREE record");
1325 const Type *OpTy = getTypeByID(Record[0]);
1326 Value *Op = getFnValueByID(Record[1], OpTy);
1328 return Error("Invalid FREE record");
1329 I = new FreeInst(Op);
1332 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1333 if (Record.size() < 3)
1334 return Error("Invalid ALLOCA record");
1335 const PointerType *Ty =
1336 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1337 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1338 unsigned Align = Record[2];
1339 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1340 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1343 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1344 if (Record.size() < 4)
1345 return Error("Invalid LOAD record");
1346 const Type *OpTy = getTypeByID(Record[0]);
1347 Value *Op = getFnValueByID(Record[1], OpTy);
1349 return Error("Invalid LOAD record");
1350 I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
1353 case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
1354 if (Record.size() < 5)
1355 return Error("Invalid LOAD record");
1356 const PointerType *OpTy =
1357 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1358 Value *Op = getFnValueByID(Record[1], OpTy ? OpTy->getElementType() : 0);
1359 Value *Ptr = getFnValueByID(Record[2], OpTy);
1360 if (!OpTy || !Op || !Ptr)
1361 return Error("Invalid STORE record");
1362 I = new StoreInst(Op, Ptr, (1 << Record[3]) >> 1, Record[4]);
1365 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1366 if (Record.size() < 3)
1367 return Error("Invalid CALL record");
1368 unsigned CCInfo = Record[0];
1369 const PointerType *OpTy =
1370 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
1371 const FunctionType *FTy = 0;
1372 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1373 Value *Callee = getFnValueByID(Record[2], OpTy);
1374 if (!FTy || !Callee || Record.size() < FTy->getNumParams()+3)
1375 return Error("Invalid CALL record");
1377 SmallVector<Value*, 16> Args;
1378 // Read the fixed params.
1379 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1380 Args.push_back(getFnValueByID(Record[i+3], FTy->getParamType(i)));
1381 if (Args.back() == 0) return Error("Invalid CALL record");
1385 // Read type/value pairs for varargs params.
1386 unsigned NextArg = FTy->getNumParams()+3;
1387 if (!FTy->isVarArg()) {
1388 if (NextArg != Record.size())
1389 return Error("Invalid CALL record");
1391 if ((Record.size()-NextArg) & 1)
1392 return Error("Invalid CALL record");
1393 for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
1394 Args.push_back(getFnValueByID(Record[NextArg+1],
1395 getTypeByID(Record[NextArg])));
1396 if (Args.back() == 0) return Error("Invalid CALL record");
1400 I = new CallInst(Callee, &Args[0], Args.size());
1401 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1402 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1405 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1406 if (Record.size() < 3)
1407 return Error("Invalid VAARG record");
1408 const Type *OpTy = getTypeByID(Record[0]);
1409 Value *Op = getFnValueByID(Record[1], OpTy);
1410 const Type *ResTy = getTypeByID(Record[2]);
1411 if (!OpTy || !Op || !ResTy)
1412 return Error("Invalid VAARG record");
1413 I = new VAArgInst(Op, ResTy);
1418 // Add instruction to end of current BB. If there is no current BB, reject
1422 return Error("Invalid instruction with no BB");
1424 CurBB->getInstList().push_back(I);
1426 // If this was a terminator instruction, move to the next block.
1427 if (isa<TerminatorInst>(I)) {
1429 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1432 // Non-void values get registered in the value table for future use.
1433 if (I && I->getType() != Type::VoidTy)
1434 ValueList.AssignValue(I, NextValueNo++);
1437 // Check the function list for unresolved values.
1438 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1439 if (A->getParent() == 0) {
1440 // We found at least one unresolved value. Nuke them all to avoid leaks.
1441 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1442 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1443 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1448 return Error("Never resolved value found in function!");
1451 // Trim the value list down to the size it was before we parsed this function.
1452 ValueList.shrinkTo(ModuleValueListSize);
1453 std::vector<BasicBlock*>().swap(FunctionBBs);
1459 //===----------------------------------------------------------------------===//
1460 // External interface
1461 //===----------------------------------------------------------------------===//
1463 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1465 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1466 std::string *ErrMsg) {
1467 BitcodeReader *R = new BitcodeReader(Buffer);
1468 if (R->ParseBitcode()) {
1470 *ErrMsg = R->getErrorString();
1472 // Don't let the BitcodeReader dtor delete 'Buffer'.
1473 R->releaseMemoryBuffer();
1480 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1481 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1482 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1484 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1487 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1488 // delete it when its dtor is run.
1489 Module *M = R->releaseModule(ErrMsg);
1491 // Don't let the BitcodeReader dtor delete 'Buffer'.
1492 R->releaseMemoryBuffer();