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/DerivedTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/ADT/SmallString.h"
21 /// ConvertToString - Convert a string from a record into an std::string, return
23 template<typename StrTy>
24 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
26 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
29 for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
30 Result += (char)Record[Idx+i+1];
34 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
36 default: // Map unknown/new linkages to external
37 case 0: return GlobalValue::ExternalLinkage;
38 case 1: return GlobalValue::WeakLinkage;
39 case 2: return GlobalValue::AppendingLinkage;
40 case 3: return GlobalValue::InternalLinkage;
41 case 4: return GlobalValue::LinkOnceLinkage;
42 case 5: return GlobalValue::DLLImportLinkage;
43 case 6: return GlobalValue::DLLExportLinkage;
44 case 7: return GlobalValue::ExternalWeakLinkage;
48 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
50 default: // Map unknown visibilities to default.
51 case 0: return GlobalValue::DefaultVisibility;
52 case 1: return GlobalValue::HiddenVisibility;
57 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
58 // If the TypeID is in range, return it.
59 if (ID < TypeList.size())
60 return TypeList[ID].get();
61 if (!isTypeTable) return 0;
63 // The type table allows forward references. Push as many Opaque types as
64 // needed to get up to ID.
65 while (TypeList.size() <= ID)
66 TypeList.push_back(OpaqueType::get());
67 return TypeList.back().get();
71 bool BitcodeReader::ParseTypeTable(BitstreamReader &Stream) {
72 if (Stream.EnterSubBlock())
73 return Error("Malformed block record");
75 if (!TypeList.empty())
76 return Error("Multiple TYPE_BLOCKs found!");
78 SmallVector<uint64_t, 64> Record;
79 unsigned NumRecords = 0;
81 // Read all the records for this type table.
83 unsigned Code = Stream.ReadCode();
84 if (Code == bitc::END_BLOCK) {
85 if (NumRecords != TypeList.size())
86 return Error("Invalid type forward reference in TYPE_BLOCK");
87 return Stream.ReadBlockEnd();
90 if (Code == bitc::ENTER_SUBBLOCK) {
91 // No known subblocks, always skip them.
92 Stream.ReadSubBlockID();
93 if (Stream.SkipBlock())
94 return Error("Malformed block record");
98 if (Code == bitc::DEFINE_ABBREV) {
99 Stream.ReadAbbrevRecord();
105 const Type *ResultTy = 0;
106 switch (Stream.ReadRecord(Code, Record)) {
107 default: // Default behavior: unknown type.
110 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
111 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
112 // type list. This allows us to reserve space.
113 if (Record.size() < 1)
114 return Error("Invalid TYPE_CODE_NUMENTRY record");
115 TypeList.reserve(Record[0]);
117 case bitc::TYPE_CODE_META: // TYPE_CODE_META: [metacode]...
118 // No metadata supported yet.
119 if (Record.size() < 1)
120 return Error("Invalid TYPE_CODE_META record");
123 case bitc::TYPE_CODE_VOID: // VOID
124 ResultTy = Type::VoidTy;
126 case bitc::TYPE_CODE_FLOAT: // FLOAT
127 ResultTy = Type::FloatTy;
129 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
130 ResultTy = Type::DoubleTy;
132 case bitc::TYPE_CODE_LABEL: // LABEL
133 ResultTy = Type::LabelTy;
135 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
138 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
139 if (Record.size() < 1)
140 return Error("Invalid Integer type record");
142 ResultTy = IntegerType::get(Record[0]);
144 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
145 if (Record.size() < 1)
146 return Error("Invalid POINTER type record");
147 ResultTy = PointerType::get(getTypeByID(Record[0], true));
149 case bitc::TYPE_CODE_FUNCTION: {
150 // FUNCTION: [vararg, retty, #pararms, paramty N]
151 if (Record.size() < 3 || Record.size() < Record[2]+3)
152 return Error("Invalid FUNCTION type record");
153 std::vector<const Type*> ArgTys;
154 for (unsigned i = 0, e = Record[2]; i != e; ++i)
155 ArgTys.push_back(getTypeByID(Record[3+i], true));
158 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
162 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
163 if (Record.size() < 2 || Record.size() < Record[1]+2)
164 return Error("Invalid STRUCT type record");
165 std::vector<const Type*> EltTys;
166 for (unsigned i = 0, e = Record[1]; i != e; ++i)
167 EltTys.push_back(getTypeByID(Record[2+i], true));
168 ResultTy = StructType::get(EltTys, Record[0]);
171 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
172 if (Record.size() < 2)
173 return Error("Invalid ARRAY type record");
174 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
176 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
177 if (Record.size() < 2)
178 return Error("Invalid VECTOR type record");
179 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
183 if (NumRecords == TypeList.size()) {
184 // If this is a new type slot, just append it.
185 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
187 } else if (ResultTy == 0) {
188 // Otherwise, this was forward referenced, so an opaque type was created,
189 // but the result type is actually just an opaque. Leave the one we
190 // created previously.
193 // Otherwise, this was forward referenced, so an opaque type was created.
194 // Resolve the opaque type to the real type now.
195 assert(NumRecords < TypeList.size() && "Typelist imbalance");
196 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
198 // Don't directly push the new type on the Tab. Instead we want to replace
199 // the opaque type we previously inserted with the new concrete value. The
200 // refinement from the abstract (opaque) type to the new type causes all
201 // uses of the abstract type to use the concrete type (NewTy). This will
202 // also cause the opaque type to be deleted.
203 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
205 // This should have replaced the old opaque type with the new type in the
206 // value table... or with a preexisting type that was already in the system.
207 // Let's just make sure it did.
208 assert(TypeList[NumRecords-1].get() != OldTy &&
209 "refineAbstractType didn't work!");
215 bool BitcodeReader::ParseTypeSymbolTable(BitstreamReader &Stream) {
216 if (Stream.EnterSubBlock())
217 return Error("Malformed block record");
219 SmallVector<uint64_t, 64> Record;
221 // Read all the records for this type table.
222 std::string TypeName;
224 unsigned Code = Stream.ReadCode();
225 if (Code == bitc::END_BLOCK)
226 return Stream.ReadBlockEnd();
228 if (Code == bitc::ENTER_SUBBLOCK) {
229 // No known subblocks, always skip them.
230 Stream.ReadSubBlockID();
231 if (Stream.SkipBlock())
232 return Error("Malformed block record");
236 if (Code == bitc::DEFINE_ABBREV) {
237 Stream.ReadAbbrevRecord();
243 switch (Stream.ReadRecord(Code, Record)) {
244 default: // Default behavior: unknown type.
246 case bitc::TST_ENTRY_CODE: // TST_ENTRY: [typeid, namelen, namechar x N]
247 if (ConvertToString(Record, 1, TypeName))
248 return Error("Invalid TST_ENTRY record");
249 unsigned TypeID = Record[0];
250 if (TypeID >= TypeList.size())
251 return Error("Invalid Type ID in TST_ENTRY record");
253 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
260 bool BitcodeReader::ParseValueSymbolTable(BitstreamReader &Stream) {
261 if (Stream.EnterSubBlock())
262 return Error("Malformed block record");
264 SmallVector<uint64_t, 64> Record;
266 // Read all the records for this value table.
267 SmallString<128> ValueName;
269 unsigned Code = Stream.ReadCode();
270 if (Code == bitc::END_BLOCK)
271 return Stream.ReadBlockEnd();
273 if (Code == bitc::ENTER_SUBBLOCK) {
274 // No known subblocks, always skip them.
275 Stream.ReadSubBlockID();
276 if (Stream.SkipBlock())
277 return Error("Malformed block record");
281 if (Code == bitc::DEFINE_ABBREV) {
282 Stream.ReadAbbrevRecord();
288 switch (Stream.ReadRecord(Code, Record)) {
289 default: // Default behavior: unknown type.
291 case bitc::VST_ENTRY_CODE: // VST_ENTRY: [valueid, namelen, namechar x N]
292 if (ConvertToString(Record, 1, ValueName))
293 return Error("Invalid TST_ENTRY record");
294 unsigned ValueID = Record[0];
295 if (ValueID >= ValueList.size())
296 return Error("Invalid Value ID in VST_ENTRY record");
297 Value *V = ValueList[ValueID];
299 V->setName(&ValueName[0], ValueName.size());
307 bool BitcodeReader::ParseModule(BitstreamReader &Stream,
308 const std::string &ModuleID) {
309 // Reject multiple MODULE_BLOCK's in a single bitstream.
311 return Error("Multiple MODULE_BLOCKs in same stream");
313 if (Stream.EnterSubBlock())
314 return Error("Malformed block record");
316 // Otherwise, create the module.
317 TheModule = new Module(ModuleID);
319 SmallVector<uint64_t, 64> Record;
320 std::vector<std::string> SectionTable;
322 // Read all the records for this module.
323 while (!Stream.AtEndOfStream()) {
324 unsigned Code = Stream.ReadCode();
325 if (Code == bitc::END_BLOCK)
326 return Stream.ReadBlockEnd();
328 if (Code == bitc::ENTER_SUBBLOCK) {
329 switch (Stream.ReadSubBlockID()) {
330 default: // Skip unknown content.
331 if (Stream.SkipBlock())
332 return Error("Malformed block record");
334 case bitc::TYPE_BLOCK_ID:
335 if (ParseTypeTable(Stream))
338 case bitc::TYPE_SYMTAB_BLOCK_ID:
339 if (ParseTypeSymbolTable(Stream))
342 case bitc::VALUE_SYMTAB_BLOCK_ID:
343 if (ParseValueSymbolTable(Stream))
350 if (Code == bitc::DEFINE_ABBREV) {
351 Stream.ReadAbbrevRecord();
356 switch (Stream.ReadRecord(Code, Record)) {
357 default: break; // Default behavior, ignore unknown content.
358 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
359 if (Record.size() < 1)
360 return Error("Malformed MODULE_CODE_VERSION");
361 // Only version #0 is supported so far.
363 return Error("Unknown bitstream version!");
365 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
367 if (ConvertToString(Record, 0, S))
368 return Error("Invalid MODULE_CODE_TRIPLE record");
369 TheModule->setTargetTriple(S);
372 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
374 if (ConvertToString(Record, 0, S))
375 return Error("Invalid MODULE_CODE_DATALAYOUT record");
376 TheModule->setDataLayout(S);
379 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
381 if (ConvertToString(Record, 0, S))
382 return Error("Invalid MODULE_CODE_ASM record");
383 TheModule->setModuleInlineAsm(S);
386 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
388 if (ConvertToString(Record, 0, S))
389 return Error("Invalid MODULE_CODE_DEPLIB record");
390 TheModule->addLibrary(S);
393 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
395 if (ConvertToString(Record, 0, S))
396 return Error("Invalid MODULE_CODE_SECTIONNAME record");
397 SectionTable.push_back(S);
400 // GLOBALVAR: [type, isconst, initid,
401 // linkage, alignment, section, visibility, threadlocal]
402 case bitc::MODULE_CODE_GLOBALVAR: {
403 if (Record.size() < 6)
404 return Error("Invalid MODULE_CODE_GLOBALVAR record");
405 const Type *Ty = getTypeByID(Record[0]);
406 if (!isa<PointerType>(Ty))
407 return Error("Global not a pointer type!");
408 Ty = cast<PointerType>(Ty)->getElementType();
410 bool isConstant = Record[1];
411 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
412 unsigned Alignment = (1 << Record[4]) >> 1;
415 if (Record[5]-1 >= SectionTable.size())
416 return Error("Invalid section ID");
417 Section = SectionTable[Record[5]-1];
419 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
420 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
421 bool isThreadLocal = false;
422 if (Record.size() >= 7) isThreadLocal = Record[7];
424 GlobalVariable *NewGV =
425 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
426 NewGV->setAlignment(Alignment);
427 if (!Section.empty())
428 NewGV->setSection(Section);
429 NewGV->setVisibility(Visibility);
430 NewGV->setThreadLocal(isThreadLocal);
432 ValueList.push_back(NewGV);
434 // TODO: remember initializer/global pair for later substitution.
437 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
439 case bitc::MODULE_CODE_FUNCTION: {
440 if (Record.size() < 7)
441 return Error("Invalid MODULE_CODE_FUNCTION record");
442 const Type *Ty = getTypeByID(Record[0]);
443 if (!isa<PointerType>(Ty))
444 return Error("Function not a pointer type!");
445 const FunctionType *FTy =
446 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
448 return Error("Function not a pointer to function type!");
450 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
453 Func->setCallingConv(Record[1]);
454 Func->setLinkage(GetDecodedLinkage(Record[3]));
455 Func->setAlignment((1 << Record[4]) >> 1);
457 if (Record[5]-1 >= SectionTable.size())
458 return Error("Invalid section ID");
459 Func->setSection(SectionTable[Record[5]-1]);
461 Func->setVisibility(GetDecodedVisibility(Record[6]));
463 ValueList.push_back(Func);
464 // TODO: remember initializer/global pair for later substitution.
471 return Error("Premature end of bitstream");
475 bool BitcodeReader::ParseBitcode(unsigned char *Buf, unsigned Length,
476 const std::string &ModuleID) {
480 return Error("Bitcode stream should be a multiple of 4 bytes in length");
482 BitstreamReader Stream(Buf, Buf+Length);
484 // Sniff for the signature.
485 if (Stream.Read(8) != 'B' ||
486 Stream.Read(8) != 'C' ||
487 Stream.Read(4) != 0x0 ||
488 Stream.Read(4) != 0xC ||
489 Stream.Read(4) != 0xE ||
490 Stream.Read(4) != 0xD)
491 return Error("Invalid bitcode signature");
493 // We expect a number of well-defined blocks, though we don't necessarily
494 // need to understand them all.
495 while (!Stream.AtEndOfStream()) {
496 unsigned Code = Stream.ReadCode();
498 if (Code != bitc::ENTER_SUBBLOCK)
499 return Error("Invalid record at top-level");
501 unsigned BlockID = Stream.ReadSubBlockID();
503 // We only know the MODULE subblock ID.
504 if (BlockID == bitc::MODULE_BLOCK_ID) {
505 if (ParseModule(Stream, ModuleID))
507 } else if (Stream.SkipBlock()) {
508 return Error("Malformed block record");