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 "BitcodeReader.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/MathExtras.h"
23 /// ConvertToString - Convert a string from a record into an std::string, return
25 template<typename StrTy>
26 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
28 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
31 for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
32 Result += (char)Record[Idx+i+1];
36 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
38 default: // Map unknown/new linkages to external
39 case 0: return GlobalValue::ExternalLinkage;
40 case 1: return GlobalValue::WeakLinkage;
41 case 2: return GlobalValue::AppendingLinkage;
42 case 3: return GlobalValue::InternalLinkage;
43 case 4: return GlobalValue::LinkOnceLinkage;
44 case 5: return GlobalValue::DLLImportLinkage;
45 case 6: return GlobalValue::DLLExportLinkage;
46 case 7: return GlobalValue::ExternalWeakLinkage;
50 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
52 default: // Map unknown visibilities to default.
53 case 0: return GlobalValue::DefaultVisibility;
54 case 1: return GlobalValue::HiddenVisibility;
58 static int GetDecodedCastOpcode(unsigned Val) {
61 case bitc::CAST_TRUNC : return Instruction::Trunc;
62 case bitc::CAST_ZEXT : return Instruction::ZExt;
63 case bitc::CAST_SEXT : return Instruction::SExt;
64 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
65 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
66 case bitc::CAST_UITOFP : return Instruction::UIToFP;
67 case bitc::CAST_SITOFP : return Instruction::SIToFP;
68 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
69 case bitc::CAST_FPEXT : return Instruction::FPExt;
70 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
71 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
72 case bitc::CAST_BITCAST : return Instruction::BitCast;
75 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
78 case bitc::BINOP_ADD: return Instruction::Add;
79 case bitc::BINOP_SUB: return Instruction::Sub;
80 case bitc::BINOP_MUL: return Instruction::Mul;
81 case bitc::BINOP_UDIV: return Instruction::UDiv;
82 case bitc::BINOP_SDIV:
83 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
84 case bitc::BINOP_UREM: return Instruction::URem;
85 case bitc::BINOP_SREM:
86 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
87 case bitc::BINOP_SHL: return Instruction::Shl;
88 case bitc::BINOP_LSHR: return Instruction::LShr;
89 case bitc::BINOP_ASHR: return Instruction::AShr;
90 case bitc::BINOP_AND: return Instruction::And;
91 case bitc::BINOP_OR: return Instruction::Or;
92 case bitc::BINOP_XOR: return Instruction::Xor;
98 /// @brief A class for maintaining the slot number definition
99 /// as a placeholder for the actual definition for forward constants defs.
100 class ConstantPlaceHolder : public ConstantExpr {
101 ConstantPlaceHolder(); // DO NOT IMPLEMENT
102 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
105 ConstantPlaceHolder(const Type *Ty)
106 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
107 Op(UndefValue::get(Type::Int32Ty), this) {
112 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
115 // Insert a bunch of null values.
117 OperandList = &Uses[0];
122 assert(Ty == getOperand(Idx)->getType() &&
123 "Type mismatch in constant table!");
124 return cast<Constant>(getOperand(Idx));
127 // Create and return a placeholder, which will later be RAUW'd.
128 Constant *C = new ConstantPlaceHolder(Ty);
129 Uses[Idx].init(C, this);
134 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
135 // If the TypeID is in range, return it.
136 if (ID < TypeList.size())
137 return TypeList[ID].get();
138 if (!isTypeTable) return 0;
140 // The type table allows forward references. Push as many Opaque types as
141 // needed to get up to ID.
142 while (TypeList.size() <= ID)
143 TypeList.push_back(OpaqueType::get());
144 return TypeList.back().get();
148 bool BitcodeReader::ParseTypeTable(BitstreamReader &Stream) {
149 if (Stream.EnterSubBlock())
150 return Error("Malformed block record");
152 if (!TypeList.empty())
153 return Error("Multiple TYPE_BLOCKs found!");
155 SmallVector<uint64_t, 64> Record;
156 unsigned NumRecords = 0;
158 // Read all the records for this type table.
160 unsigned Code = Stream.ReadCode();
161 if (Code == bitc::END_BLOCK) {
162 if (NumRecords != TypeList.size())
163 return Error("Invalid type forward reference in TYPE_BLOCK");
164 return Stream.ReadBlockEnd();
167 if (Code == bitc::ENTER_SUBBLOCK) {
168 // No known subblocks, always skip them.
169 Stream.ReadSubBlockID();
170 if (Stream.SkipBlock())
171 return Error("Malformed block record");
175 if (Code == bitc::DEFINE_ABBREV) {
176 Stream.ReadAbbrevRecord();
182 const Type *ResultTy = 0;
183 switch (Stream.ReadRecord(Code, Record)) {
184 default: // Default behavior: unknown type.
187 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
188 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
189 // type list. This allows us to reserve space.
190 if (Record.size() < 1)
191 return Error("Invalid TYPE_CODE_NUMENTRY record");
192 TypeList.reserve(Record[0]);
194 case bitc::TYPE_CODE_META: // TYPE_CODE_META: [metacode]...
195 // No metadata supported yet.
196 if (Record.size() < 1)
197 return Error("Invalid TYPE_CODE_META record");
200 case bitc::TYPE_CODE_VOID: // VOID
201 ResultTy = Type::VoidTy;
203 case bitc::TYPE_CODE_FLOAT: // FLOAT
204 ResultTy = Type::FloatTy;
206 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
207 ResultTy = Type::DoubleTy;
209 case bitc::TYPE_CODE_LABEL: // LABEL
210 ResultTy = Type::LabelTy;
212 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
215 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
216 if (Record.size() < 1)
217 return Error("Invalid Integer type record");
219 ResultTy = IntegerType::get(Record[0]);
221 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
222 if (Record.size() < 1)
223 return Error("Invalid POINTER type record");
224 ResultTy = PointerType::get(getTypeByID(Record[0], true));
226 case bitc::TYPE_CODE_FUNCTION: {
227 // FUNCTION: [vararg, retty, #pararms, paramty N]
228 if (Record.size() < 3 || Record.size() < Record[2]+3)
229 return Error("Invalid FUNCTION type record");
230 std::vector<const Type*> ArgTys;
231 for (unsigned i = 0, e = Record[2]; i != e; ++i)
232 ArgTys.push_back(getTypeByID(Record[3+i], true));
235 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
239 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
240 if (Record.size() < 2 || Record.size() < Record[1]+2)
241 return Error("Invalid STRUCT type record");
242 std::vector<const Type*> EltTys;
243 for (unsigned i = 0, e = Record[1]; i != e; ++i)
244 EltTys.push_back(getTypeByID(Record[2+i], true));
245 ResultTy = StructType::get(EltTys, Record[0]);
248 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
249 if (Record.size() < 2)
250 return Error("Invalid ARRAY type record");
251 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
253 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
254 if (Record.size() < 2)
255 return Error("Invalid VECTOR type record");
256 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
260 if (NumRecords == TypeList.size()) {
261 // If this is a new type slot, just append it.
262 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
264 } else if (ResultTy == 0) {
265 // Otherwise, this was forward referenced, so an opaque type was created,
266 // but the result type is actually just an opaque. Leave the one we
267 // created previously.
270 // Otherwise, this was forward referenced, so an opaque type was created.
271 // Resolve the opaque type to the real type now.
272 assert(NumRecords < TypeList.size() && "Typelist imbalance");
273 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
275 // Don't directly push the new type on the Tab. Instead we want to replace
276 // the opaque type we previously inserted with the new concrete value. The
277 // refinement from the abstract (opaque) type to the new type causes all
278 // uses of the abstract type to use the concrete type (NewTy). This will
279 // also cause the opaque type to be deleted.
280 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
282 // This should have replaced the old opaque type with the new type in the
283 // value table... or with a preexisting type that was already in the
284 // system. Let's just make sure it did.
285 assert(TypeList[NumRecords-1].get() != OldTy &&
286 "refineAbstractType didn't work!");
292 bool BitcodeReader::ParseTypeSymbolTable(BitstreamReader &Stream) {
293 if (Stream.EnterSubBlock())
294 return Error("Malformed block record");
296 SmallVector<uint64_t, 64> Record;
298 // Read all the records for this type table.
299 std::string TypeName;
301 unsigned Code = Stream.ReadCode();
302 if (Code == bitc::END_BLOCK)
303 return Stream.ReadBlockEnd();
305 if (Code == bitc::ENTER_SUBBLOCK) {
306 // No known subblocks, always skip them.
307 Stream.ReadSubBlockID();
308 if (Stream.SkipBlock())
309 return Error("Malformed block record");
313 if (Code == bitc::DEFINE_ABBREV) {
314 Stream.ReadAbbrevRecord();
320 switch (Stream.ReadRecord(Code, Record)) {
321 default: // Default behavior: unknown type.
323 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
324 if (ConvertToString(Record, 1, TypeName))
325 return Error("Invalid TST_ENTRY record");
326 unsigned TypeID = Record[0];
327 if (TypeID >= TypeList.size())
328 return Error("Invalid Type ID in TST_ENTRY record");
330 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
337 bool BitcodeReader::ParseValueSymbolTable(BitstreamReader &Stream) {
338 if (Stream.EnterSubBlock())
339 return Error("Malformed block record");
341 SmallVector<uint64_t, 64> Record;
343 // Read all the records for this value table.
344 SmallString<128> ValueName;
346 unsigned Code = Stream.ReadCode();
347 if (Code == bitc::END_BLOCK)
348 return Stream.ReadBlockEnd();
350 if (Code == bitc::ENTER_SUBBLOCK) {
351 // No known subblocks, always skip them.
352 Stream.ReadSubBlockID();
353 if (Stream.SkipBlock())
354 return Error("Malformed block record");
358 if (Code == bitc::DEFINE_ABBREV) {
359 Stream.ReadAbbrevRecord();
365 switch (Stream.ReadRecord(Code, Record)) {
366 default: // Default behavior: unknown type.
368 case bitc::TST_CODE_ENTRY: // VST_ENTRY: [valueid, namelen, namechar x N]
369 if (ConvertToString(Record, 1, ValueName))
370 return Error("Invalid TST_ENTRY record");
371 unsigned ValueID = Record[0];
372 if (ValueID >= ValueList.size())
373 return Error("Invalid Value ID in VST_ENTRY record");
374 Value *V = ValueList[ValueID];
376 V->setName(&ValueName[0], ValueName.size());
383 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
384 /// the LSB for dense VBR encoding.
385 static uint64_t DecodeSignRotatedValue(uint64_t V) {
390 // There is no such thing as -0 with integers. "-0" really means MININT.
394 bool BitcodeReader::ParseConstants(BitstreamReader &Stream) {
395 if (Stream.EnterSubBlock())
396 return Error("Malformed block record");
398 SmallVector<uint64_t, 64> Record;
400 // Read all the records for this value table.
401 const Type *CurTy = Type::Int32Ty;
402 unsigned NextCstNo = ValueList.size();
404 unsigned Code = Stream.ReadCode();
405 if (Code == bitc::END_BLOCK) {
406 // If there are global var inits to process, do so now.
407 if (!GlobalInits.empty()) {
408 while (!GlobalInits.empty()) {
409 unsigned ValID = GlobalInits.back().second;
410 if (ValID >= ValueList.size())
411 return Error("Invalid value ID for global var init!");
412 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
413 GlobalInits.back().first->setInitializer(C);
415 return Error("Global variable initializer is not a constant!");
416 GlobalInits.pop_back();
420 if (NextCstNo != ValueList.size())
421 return Error("Invalid constant reference!");
423 return Stream.ReadBlockEnd();
426 if (Code == bitc::ENTER_SUBBLOCK) {
427 // No known subblocks, always skip them.
428 Stream.ReadSubBlockID();
429 if (Stream.SkipBlock())
430 return Error("Malformed block record");
434 if (Code == bitc::DEFINE_ABBREV) {
435 Stream.ReadAbbrevRecord();
442 switch (Stream.ReadRecord(Code, Record)) {
443 default: // Default behavior: unknown constant
444 case bitc::CST_CODE_UNDEF: // UNDEF
445 V = UndefValue::get(CurTy);
447 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
449 return Error("Malformed CST_SETTYPE record");
450 if (Record[0] >= TypeList.size())
451 return Error("Invalid Type ID in CST_SETTYPE record");
452 CurTy = TypeList[Record[0]];
453 continue; // Skip the ValueList manipulation.
454 case bitc::CST_CODE_NULL: // NULL
455 V = Constant::getNullValue(CurTy);
457 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
458 if (!isa<IntegerType>(CurTy) || Record.empty())
459 return Error("Invalid CST_INTEGER record");
460 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
462 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
463 if (!isa<IntegerType>(CurTy) || Record.empty() ||
464 Record.size() < Record[0]+1)
465 return Error("Invalid WIDE_INTEGER record");
467 unsigned NumWords = Record[0];
468 uint64_t *Data = new uint64_t[NumWords];
469 for (unsigned i = 0; i != NumWords; ++i)
470 Data[i] = DecodeSignRotatedValue(Record[i+1]);
471 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
475 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
477 return Error("Invalid FLOAT record");
478 if (CurTy == Type::FloatTy)
479 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
480 else if (CurTy == Type::DoubleTy)
481 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
483 V = UndefValue::get(CurTy);
486 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
487 if (Record.empty() || Record.size() < Record[0]+1)
488 return Error("Invalid CST_AGGREGATE record");
490 unsigned Size = Record[0];
491 std::vector<Constant*> Elts;
493 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
494 for (unsigned i = 0; i != Size; ++i)
495 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
496 STy->getElementType(i)));
497 V = ConstantStruct::get(STy, Elts);
498 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
499 const Type *EltTy = ATy->getElementType();
500 for (unsigned i = 0; i != Size; ++i)
501 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
502 V = ConstantArray::get(ATy, Elts);
503 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
504 const Type *EltTy = VTy->getElementType();
505 for (unsigned i = 0; i != Size; ++i)
506 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
507 V = ConstantVector::get(Elts);
509 V = UndefValue::get(CurTy);
514 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
515 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
516 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
517 if (Opc < 0) return UndefValue::get(CurTy); // Unknown binop.
519 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
520 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
521 V = ConstantExpr::get(Opc, LHS, RHS);
524 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
525 if (Record.size() < 3) return Error("Invalid CE_CAST record");
526 int Opc = GetDecodedCastOpcode(Record[0]);
527 if (Opc < 0) return UndefValue::get(CurTy); // Unknown cast.
529 const Type *OpTy = getTypeByID(Record[1]);
530 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
531 V = ConstantExpr::getCast(Opc, Op, CurTy);
534 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
535 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
536 SmallVector<Constant*, 16> Elts;
537 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
538 const Type *ElTy = getTypeByID(Record[i]);
539 if (!ElTy) return Error("Invalid CE_GEP record");
540 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
542 return ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
544 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
545 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
546 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
548 ValueList.getConstantFwdRef(Record[1],CurTy),
549 ValueList.getConstantFwdRef(Record[2],CurTy));
551 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
552 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
553 const VectorType *OpTy =
554 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
555 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
556 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
557 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
558 OpTy->getElementType());
559 V = ConstantExpr::getExtractElement(Op0, Op1);
562 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
563 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
564 if (Record.size() < 3 || OpTy == 0)
565 return Error("Invalid CE_INSERTELT record");
566 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
567 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
568 OpTy->getElementType());
569 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
570 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
573 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
574 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
575 if (Record.size() < 3 || OpTy == 0)
576 return Error("Invalid CE_INSERTELT record");
577 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
578 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
579 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
580 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
581 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
584 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
585 if (Record.size() < 4) return Error("Invalid CE_CMP record");
586 const Type *OpTy = getTypeByID(Record[0]);
587 if (OpTy == 0) return Error("Invalid CE_CMP record");
588 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
589 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
591 if (OpTy->isFloatingPoint())
592 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
594 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
599 if (NextCstNo == ValueList.size())
600 ValueList.push_back(V);
601 else if (ValueList[NextCstNo] == 0)
602 ValueList.initVal(NextCstNo, V);
604 // If there was a forward reference to this constant,
605 Value *OldV = ValueList[NextCstNo];
606 ValueList.setOperand(NextCstNo, V);
607 OldV->replaceAllUsesWith(V);
615 bool BitcodeReader::ParseModule(BitstreamReader &Stream,
616 const std::string &ModuleID) {
617 // Reject multiple MODULE_BLOCK's in a single bitstream.
619 return Error("Multiple MODULE_BLOCKs in same stream");
621 if (Stream.EnterSubBlock())
622 return Error("Malformed block record");
624 // Otherwise, create the module.
625 TheModule = new Module(ModuleID);
627 SmallVector<uint64_t, 64> Record;
628 std::vector<std::string> SectionTable;
630 // Read all the records for this module.
631 while (!Stream.AtEndOfStream()) {
632 unsigned Code = Stream.ReadCode();
633 if (Code == bitc::END_BLOCK) {
634 if (!GlobalInits.empty())
635 return Error("Malformed global initializer set");
636 return Stream.ReadBlockEnd();
639 if (Code == bitc::ENTER_SUBBLOCK) {
640 switch (Stream.ReadSubBlockID()) {
641 default: // Skip unknown content.
642 if (Stream.SkipBlock())
643 return Error("Malformed block record");
645 case bitc::TYPE_BLOCK_ID:
646 if (ParseTypeTable(Stream))
649 case bitc::TYPE_SYMTAB_BLOCK_ID:
650 if (ParseTypeSymbolTable(Stream))
653 case bitc::VALUE_SYMTAB_BLOCK_ID:
654 if (ParseValueSymbolTable(Stream))
657 case bitc::CONSTANTS_BLOCK_ID:
658 if (ParseConstants(Stream))
665 if (Code == bitc::DEFINE_ABBREV) {
666 Stream.ReadAbbrevRecord();
671 switch (Stream.ReadRecord(Code, Record)) {
672 default: break; // Default behavior, ignore unknown content.
673 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
674 if (Record.size() < 1)
675 return Error("Malformed MODULE_CODE_VERSION");
676 // Only version #0 is supported so far.
678 return Error("Unknown bitstream version!");
680 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
682 if (ConvertToString(Record, 0, S))
683 return Error("Invalid MODULE_CODE_TRIPLE record");
684 TheModule->setTargetTriple(S);
687 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
689 if (ConvertToString(Record, 0, S))
690 return Error("Invalid MODULE_CODE_DATALAYOUT record");
691 TheModule->setDataLayout(S);
694 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
696 if (ConvertToString(Record, 0, S))
697 return Error("Invalid MODULE_CODE_ASM record");
698 TheModule->setModuleInlineAsm(S);
701 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
703 if (ConvertToString(Record, 0, S))
704 return Error("Invalid MODULE_CODE_DEPLIB record");
705 TheModule->addLibrary(S);
708 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
710 if (ConvertToString(Record, 0, S))
711 return Error("Invalid MODULE_CODE_SECTIONNAME record");
712 SectionTable.push_back(S);
715 // GLOBALVAR: [type, isconst, initid,
716 // linkage, alignment, section, visibility, threadlocal]
717 case bitc::MODULE_CODE_GLOBALVAR: {
718 if (Record.size() < 6)
719 return Error("Invalid MODULE_CODE_GLOBALVAR record");
720 const Type *Ty = getTypeByID(Record[0]);
721 if (!isa<PointerType>(Ty))
722 return Error("Global not a pointer type!");
723 Ty = cast<PointerType>(Ty)->getElementType();
725 bool isConstant = Record[1];
726 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
727 unsigned Alignment = (1 << Record[4]) >> 1;
730 if (Record[5]-1 >= SectionTable.size())
731 return Error("Invalid section ID");
732 Section = SectionTable[Record[5]-1];
734 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
735 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
736 bool isThreadLocal = false;
737 if (Record.size() >= 7) isThreadLocal = Record[7];
739 GlobalVariable *NewGV =
740 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
741 NewGV->setAlignment(Alignment);
742 if (!Section.empty())
743 NewGV->setSection(Section);
744 NewGV->setVisibility(Visibility);
745 NewGV->setThreadLocal(isThreadLocal);
747 ValueList.push_back(NewGV);
749 // Remember which value to use for the global initializer.
750 if (unsigned InitID = Record[2])
751 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
754 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
756 case bitc::MODULE_CODE_FUNCTION: {
757 if (Record.size() < 7)
758 return Error("Invalid MODULE_CODE_FUNCTION record");
759 const Type *Ty = getTypeByID(Record[0]);
760 if (!isa<PointerType>(Ty))
761 return Error("Function not a pointer type!");
762 const FunctionType *FTy =
763 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
765 return Error("Function not a pointer to function type!");
767 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
770 Func->setCallingConv(Record[1]);
771 Func->setLinkage(GetDecodedLinkage(Record[3]));
772 Func->setAlignment((1 << Record[4]) >> 1);
774 if (Record[5]-1 >= SectionTable.size())
775 return Error("Invalid section ID");
776 Func->setSection(SectionTable[Record[5]-1]);
778 Func->setVisibility(GetDecodedVisibility(Record[6]));
780 ValueList.push_back(Func);
781 // TODO: remember initializer/global pair for later substitution.
788 return Error("Premature end of bitstream");
792 bool BitcodeReader::ParseBitcode(unsigned char *Buf, unsigned Length,
793 const std::string &ModuleID) {
797 return Error("Bitcode stream should be a multiple of 4 bytes in length");
799 BitstreamReader Stream(Buf, Buf+Length);
801 // Sniff for the signature.
802 if (Stream.Read(8) != 'B' ||
803 Stream.Read(8) != 'C' ||
804 Stream.Read(4) != 0x0 ||
805 Stream.Read(4) != 0xC ||
806 Stream.Read(4) != 0xE ||
807 Stream.Read(4) != 0xD)
808 return Error("Invalid bitcode signature");
810 // We expect a number of well-defined blocks, though we don't necessarily
811 // need to understand them all.
812 while (!Stream.AtEndOfStream()) {
813 unsigned Code = Stream.ReadCode();
815 if (Code != bitc::ENTER_SUBBLOCK)
816 return Error("Invalid record at top-level");
818 unsigned BlockID = Stream.ReadSubBlockID();
820 // We only know the MODULE subblock ID.
821 if (BlockID == bitc::MODULE_BLOCK_ID) {
822 if (ParseModule(Stream, ModuleID))
824 } else if (Stream.SkipBlock()) {
825 return Error("Malformed block record");