blob: 9ae657836375c046d3db985fae8906e1dee77369 [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattnera7c49aa2007-05-01 07:01:57 +000018#include "llvm/Instructions.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000019#include "llvm/Module.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000020#include "llvm/ADT/SmallString.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000021#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000022#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000023using namespace llvm;
24
Chris Lattnerc453f762007-04-29 07:54:31 +000025BitcodeReader::~BitcodeReader() {
26 delete Buffer;
27}
28
29
Chris Lattnercaee0dc2007-04-22 06:23:29 +000030/// ConvertToString - Convert a string from a record into an std::string, return
31/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000032template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000033static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000034 StrTy &Result) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +000035 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
36 return true;
37
38 for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
39 Result += (char)Record[Idx+i+1];
40 return false;
41}
42
43static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
44 switch (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;
54 }
55}
56
57static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
58 switch (Val) {
59 default: // Map unknown visibilities to default.
60 case 0: return GlobalValue::DefaultVisibility;
61 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000062 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063 }
64}
65
Chris Lattnerf581c3b2007-04-24 07:07:11 +000066static int GetDecodedCastOpcode(unsigned Val) {
67 switch (Val) {
68 default: return -1;
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;
81 }
82}
83static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
84 switch (Val) {
85 default: return -1;
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;
101 }
102}
103
104
Chris Lattner522b7b12007-04-24 05:48:56 +0000105namespace {
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
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000111 public:
112 Use Op;
113 ConstantPlaceHolder(const Type *Ty)
114 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
115 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000116 }
117 };
118}
119
120Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
121 const Type *Ty) {
122 if (Idx >= size()) {
123 // Insert a bunch of null values.
124 Uses.resize(Idx+1);
125 OperandList = &Uses[0];
126 NumOperands = Idx+1;
127 }
128
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000129 if (Value *V = Uses[Idx]) {
130 assert(Ty == V->getType() && "Type mismatch in constant table!");
131 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000132 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000133
134 // Create and return a placeholder, which will later be RAUW'd.
135 Constant *C = new ConstantPlaceHolder(Ty);
136 Uses[Idx].init(C, this);
137 return C;
138}
139
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000140Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
141 if (Idx >= size()) {
142 // Insert a bunch of null values.
143 Uses.resize(Idx+1);
144 OperandList = &Uses[0];
145 NumOperands = Idx+1;
146 }
147
148 if (Value *V = Uses[Idx]) {
149 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
150 return V;
151 }
152
153 // Create and return a placeholder, which will later be RAUW'd.
154 Value *V = new Argument(Ty);
155 Uses[Idx].init(V, this);
156 return V;
157}
158
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000159
160const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
161 // If the TypeID is in range, return it.
162 if (ID < TypeList.size())
163 return TypeList[ID].get();
164 if (!isTypeTable) return 0;
165
166 // The type table allows forward references. Push as many Opaque types as
167 // needed to get up to ID.
168 while (TypeList.size() <= ID)
169 TypeList.push_back(OpaqueType::get());
170 return TypeList.back().get();
171}
172
Chris Lattner86697142007-05-01 05:01:34 +0000173bool BitcodeReader::ParseTypeTable() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000174 if (Stream.EnterSubBlock())
175 return Error("Malformed block record");
176
177 if (!TypeList.empty())
178 return Error("Multiple TYPE_BLOCKs found!");
179
180 SmallVector<uint64_t, 64> Record;
181 unsigned NumRecords = 0;
182
183 // Read all the records for this type table.
184 while (1) {
185 unsigned Code = Stream.ReadCode();
186 if (Code == bitc::END_BLOCK) {
187 if (NumRecords != TypeList.size())
188 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000189 if (Stream.ReadBlockEnd())
190 return Error("Error at end of type table block");
191 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000192 }
193
194 if (Code == bitc::ENTER_SUBBLOCK) {
195 // No known subblocks, always skip them.
196 Stream.ReadSubBlockID();
197 if (Stream.SkipBlock())
198 return Error("Malformed block record");
199 continue;
200 }
201
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000202 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000203 Stream.ReadAbbrevRecord();
204 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000205 }
206
207 // Read a record.
208 Record.clear();
209 const Type *ResultTy = 0;
210 switch (Stream.ReadRecord(Code, Record)) {
211 default: // Default behavior: unknown type.
212 ResultTy = 0;
213 break;
214 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
215 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
216 // type list. This allows us to reserve space.
217 if (Record.size() < 1)
218 return Error("Invalid TYPE_CODE_NUMENTRY record");
219 TypeList.reserve(Record[0]);
220 continue;
221 case bitc::TYPE_CODE_META: // TYPE_CODE_META: [metacode]...
222 // No metadata supported yet.
223 if (Record.size() < 1)
224 return Error("Invalid TYPE_CODE_META record");
225 continue;
226
227 case bitc::TYPE_CODE_VOID: // VOID
228 ResultTy = Type::VoidTy;
229 break;
230 case bitc::TYPE_CODE_FLOAT: // FLOAT
231 ResultTy = Type::FloatTy;
232 break;
233 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
234 ResultTy = Type::DoubleTy;
235 break;
236 case bitc::TYPE_CODE_LABEL: // LABEL
237 ResultTy = Type::LabelTy;
238 break;
239 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
240 ResultTy = 0;
241 break;
242 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
243 if (Record.size() < 1)
244 return Error("Invalid Integer type record");
245
246 ResultTy = IntegerType::get(Record[0]);
247 break;
248 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
249 if (Record.size() < 1)
250 return Error("Invalid POINTER type record");
251 ResultTy = PointerType::get(getTypeByID(Record[0], true));
252 break;
253 case bitc::TYPE_CODE_FUNCTION: {
254 // FUNCTION: [vararg, retty, #pararms, paramty N]
255 if (Record.size() < 3 || Record.size() < Record[2]+3)
256 return Error("Invalid FUNCTION type record");
257 std::vector<const Type*> ArgTys;
258 for (unsigned i = 0, e = Record[2]; i != e; ++i)
259 ArgTys.push_back(getTypeByID(Record[3+i], true));
260
261 // FIXME: PARAM TYS.
262 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
263 Record[0]);
264 break;
265 }
266 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
267 if (Record.size() < 2 || Record.size() < Record[1]+2)
268 return Error("Invalid STRUCT type record");
269 std::vector<const Type*> EltTys;
270 for (unsigned i = 0, e = Record[1]; i != e; ++i)
271 EltTys.push_back(getTypeByID(Record[2+i], true));
272 ResultTy = StructType::get(EltTys, Record[0]);
273 break;
274 }
275 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
276 if (Record.size() < 2)
277 return Error("Invalid ARRAY type record");
278 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
279 break;
280 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
281 if (Record.size() < 2)
282 return Error("Invalid VECTOR type record");
283 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
284 break;
285 }
286
287 if (NumRecords == TypeList.size()) {
288 // If this is a new type slot, just append it.
289 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
290 ++NumRecords;
291 } else if (ResultTy == 0) {
292 // Otherwise, this was forward referenced, so an opaque type was created,
293 // but the result type is actually just an opaque. Leave the one we
294 // created previously.
295 ++NumRecords;
296 } else {
297 // Otherwise, this was forward referenced, so an opaque type was created.
298 // Resolve the opaque type to the real type now.
299 assert(NumRecords < TypeList.size() && "Typelist imbalance");
300 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
301
302 // Don't directly push the new type on the Tab. Instead we want to replace
303 // the opaque type we previously inserted with the new concrete value. The
304 // refinement from the abstract (opaque) type to the new type causes all
305 // uses of the abstract type to use the concrete type (NewTy). This will
306 // also cause the opaque type to be deleted.
307 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
308
309 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000310 // value table... or with a preexisting type that was already in the
311 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000312 assert(TypeList[NumRecords-1].get() != OldTy &&
313 "refineAbstractType didn't work!");
314 }
315 }
316}
317
318
Chris Lattner86697142007-05-01 05:01:34 +0000319bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000320 if (Stream.EnterSubBlock())
321 return Error("Malformed block record");
322
323 SmallVector<uint64_t, 64> Record;
324
325 // Read all the records for this type table.
326 std::string TypeName;
327 while (1) {
328 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000329 if (Code == bitc::END_BLOCK) {
330 if (Stream.ReadBlockEnd())
331 return Error("Error at end of type symbol table block");
332 return false;
333 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000334
335 if (Code == bitc::ENTER_SUBBLOCK) {
336 // No known subblocks, always skip them.
337 Stream.ReadSubBlockID();
338 if (Stream.SkipBlock())
339 return Error("Malformed block record");
340 continue;
341 }
342
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000343 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000344 Stream.ReadAbbrevRecord();
345 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000346 }
347
348 // Read a record.
349 Record.clear();
350 switch (Stream.ReadRecord(Code, Record)) {
351 default: // Default behavior: unknown type.
352 break;
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000353 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000354 if (ConvertToString(Record, 1, TypeName))
355 return Error("Invalid TST_ENTRY record");
356 unsigned TypeID = Record[0];
357 if (TypeID >= TypeList.size())
358 return Error("Invalid Type ID in TST_ENTRY record");
359
360 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
361 TypeName.clear();
362 break;
363 }
364 }
365}
366
Chris Lattner86697142007-05-01 05:01:34 +0000367bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000368 if (Stream.EnterSubBlock())
369 return Error("Malformed block record");
370
371 SmallVector<uint64_t, 64> Record;
372
373 // Read all the records for this value table.
374 SmallString<128> ValueName;
375 while (1) {
376 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000377 if (Code == bitc::END_BLOCK) {
378 if (Stream.ReadBlockEnd())
379 return Error("Error at end of value symbol table block");
380 return false;
381 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000382 if (Code == bitc::ENTER_SUBBLOCK) {
383 // No known subblocks, always skip them.
384 Stream.ReadSubBlockID();
385 if (Stream.SkipBlock())
386 return Error("Malformed block record");
387 continue;
388 }
389
390 if (Code == bitc::DEFINE_ABBREV) {
391 Stream.ReadAbbrevRecord();
392 continue;
393 }
394
395 // Read a record.
396 Record.clear();
397 switch (Stream.ReadRecord(Code, Record)) {
398 default: // Default behavior: unknown type.
399 break;
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000400 case bitc::TST_CODE_ENTRY: // VST_ENTRY: [valueid, namelen, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000401 if (ConvertToString(Record, 1, ValueName))
402 return Error("Invalid TST_ENTRY record");
403 unsigned ValueID = Record[0];
404 if (ValueID >= ValueList.size())
405 return Error("Invalid Value ID in VST_ENTRY record");
406 Value *V = ValueList[ValueID];
407
408 V->setName(&ValueName[0], ValueName.size());
409 ValueName.clear();
410 break;
411 }
412 }
413}
414
Chris Lattner0eef0802007-04-24 04:04:35 +0000415/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
416/// the LSB for dense VBR encoding.
417static uint64_t DecodeSignRotatedValue(uint64_t V) {
418 if ((V & 1) == 0)
419 return V >> 1;
420 if (V != 1)
421 return -(V >> 1);
422 // There is no such thing as -0 with integers. "-0" really means MININT.
423 return 1ULL << 63;
424}
425
Chris Lattner07d98b42007-04-26 02:46:40 +0000426/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
427/// values and aliases that we can.
428bool BitcodeReader::ResolveGlobalAndAliasInits() {
429 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
430 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
431
432 GlobalInitWorklist.swap(GlobalInits);
433 AliasInitWorklist.swap(AliasInits);
434
435 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000436 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000437 if (ValID >= ValueList.size()) {
438 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000439 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000440 } else {
441 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
442 GlobalInitWorklist.back().first->setInitializer(C);
443 else
444 return Error("Global variable initializer is not a constant!");
445 }
446 GlobalInitWorklist.pop_back();
447 }
448
449 while (!AliasInitWorklist.empty()) {
450 unsigned ValID = AliasInitWorklist.back().second;
451 if (ValID >= ValueList.size()) {
452 AliasInits.push_back(AliasInitWorklist.back());
453 } else {
454 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000455 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000456 else
457 return Error("Alias initializer is not a constant!");
458 }
459 AliasInitWorklist.pop_back();
460 }
461 return false;
462}
463
464
Chris Lattner86697142007-05-01 05:01:34 +0000465bool BitcodeReader::ParseConstants() {
Chris Lattnere16504e2007-04-24 03:30:34 +0000466 if (Stream.EnterSubBlock())
467 return Error("Malformed block record");
468
469 SmallVector<uint64_t, 64> Record;
470
471 // Read all the records for this value table.
472 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000473 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000474 while (1) {
475 unsigned Code = Stream.ReadCode();
476 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000477 if (NextCstNo != ValueList.size())
478 return Error("Invalid constant reference!");
479
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000480 if (Stream.ReadBlockEnd())
481 return Error("Error at end of constants block");
482 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000483 }
484
485 if (Code == bitc::ENTER_SUBBLOCK) {
486 // No known subblocks, always skip them.
487 Stream.ReadSubBlockID();
488 if (Stream.SkipBlock())
489 return Error("Malformed block record");
490 continue;
491 }
492
493 if (Code == bitc::DEFINE_ABBREV) {
494 Stream.ReadAbbrevRecord();
495 continue;
496 }
497
498 // Read a record.
499 Record.clear();
500 Value *V = 0;
501 switch (Stream.ReadRecord(Code, Record)) {
502 default: // Default behavior: unknown constant
503 case bitc::CST_CODE_UNDEF: // UNDEF
504 V = UndefValue::get(CurTy);
505 break;
506 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
507 if (Record.empty())
508 return Error("Malformed CST_SETTYPE record");
509 if (Record[0] >= TypeList.size())
510 return Error("Invalid Type ID in CST_SETTYPE record");
511 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000512 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000513 case bitc::CST_CODE_NULL: // NULL
514 V = Constant::getNullValue(CurTy);
515 break;
516 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000517 if (!isa<IntegerType>(CurTy) || Record.empty())
518 return Error("Invalid CST_INTEGER record");
519 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
520 break;
521 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
522 if (!isa<IntegerType>(CurTy) || Record.empty() ||
523 Record.size() < Record[0]+1)
524 return Error("Invalid WIDE_INTEGER record");
525
526 unsigned NumWords = Record[0];
Chris Lattner084a8442007-04-24 17:22:05 +0000527 SmallVector<uint64_t, 8> Words;
528 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000529 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner084a8442007-04-24 17:22:05 +0000530 Words[i] = DecodeSignRotatedValue(Record[i+1]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000531 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000532 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000533 break;
534 }
535 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
536 if (Record.empty())
537 return Error("Invalid FLOAT record");
538 if (CurTy == Type::FloatTy)
539 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
540 else if (CurTy == Type::DoubleTy)
541 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
Chris Lattnere16504e2007-04-24 03:30:34 +0000542 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000543 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000544 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000545
546 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
547 if (Record.empty() || Record.size() < Record[0]+1)
548 return Error("Invalid CST_AGGREGATE record");
549
550 unsigned Size = Record[0];
551 std::vector<Constant*> Elts;
552
553 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
554 for (unsigned i = 0; i != Size; ++i)
555 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
556 STy->getElementType(i)));
557 V = ConstantStruct::get(STy, Elts);
558 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
559 const Type *EltTy = ATy->getElementType();
560 for (unsigned i = 0; i != Size; ++i)
561 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
562 V = ConstantArray::get(ATy, Elts);
563 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
564 const Type *EltTy = VTy->getElementType();
565 for (unsigned i = 0; i != Size; ++i)
566 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
567 V = ConstantVector::get(Elts);
568 } else {
569 V = UndefValue::get(CurTy);
570 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000571 break;
572 }
573
574 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
575 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
576 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000577 if (Opc < 0) {
578 V = UndefValue::get(CurTy); // Unknown binop.
579 } else {
580 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
581 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
582 V = ConstantExpr::get(Opc, LHS, RHS);
583 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000584 break;
585 }
586 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
587 if (Record.size() < 3) return Error("Invalid CE_CAST record");
588 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000589 if (Opc < 0) {
590 V = UndefValue::get(CurTy); // Unknown cast.
591 } else {
592 const Type *OpTy = getTypeByID(Record[1]);
593 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
594 V = ConstantExpr::getCast(Opc, Op, CurTy);
595 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000596 break;
597 }
598 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
599 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
600 SmallVector<Constant*, 16> Elts;
601 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
602 const Type *ElTy = getTypeByID(Record[i]);
603 if (!ElTy) return Error("Invalid CE_GEP record");
604 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
605 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000606 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
607 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000608 }
609 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
610 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
611 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
612 Type::Int1Ty),
613 ValueList.getConstantFwdRef(Record[1],CurTy),
614 ValueList.getConstantFwdRef(Record[2],CurTy));
615 break;
616 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
617 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
618 const VectorType *OpTy =
619 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
620 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
621 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
622 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
623 OpTy->getElementType());
624 V = ConstantExpr::getExtractElement(Op0, Op1);
625 break;
626 }
627 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
628 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
629 if (Record.size() < 3 || OpTy == 0)
630 return Error("Invalid CE_INSERTELT record");
631 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
632 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
633 OpTy->getElementType());
634 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
635 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
636 break;
637 }
638 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
639 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
640 if (Record.size() < 3 || OpTy == 0)
641 return Error("Invalid CE_INSERTELT record");
642 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
643 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
644 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
645 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
646 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
647 break;
648 }
649 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
650 if (Record.size() < 4) return Error("Invalid CE_CMP record");
651 const Type *OpTy = getTypeByID(Record[0]);
652 if (OpTy == 0) return Error("Invalid CE_CMP record");
653 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
654 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
655
656 if (OpTy->isFloatingPoint())
657 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
658 else
659 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
660 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000661 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000662 }
663
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000664 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000665 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000666 }
667}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000668
Chris Lattner980e5aa2007-05-01 05:52:21 +0000669/// RememberAndSkipFunctionBody - When we see the block for a function body,
670/// remember where it is and then skip it. This lets us lazily deserialize the
671/// functions.
672bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000673 // Get the function we are talking about.
674 if (FunctionsWithBodies.empty())
675 return Error("Insufficient function protos");
676
677 Function *Fn = FunctionsWithBodies.back();
678 FunctionsWithBodies.pop_back();
679
680 // Save the current stream state.
681 uint64_t CurBit = Stream.GetCurrentBitNo();
682 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
683
684 // Set the functions linkage to GhostLinkage so we know it is lazily
685 // deserialized.
686 Fn->setLinkage(GlobalValue::GhostLinkage);
687
688 // Skip over the function block for now.
689 if (Stream.SkipBlock())
690 return Error("Malformed block record");
691 return false;
692}
693
Chris Lattner86697142007-05-01 05:01:34 +0000694bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000695 // Reject multiple MODULE_BLOCK's in a single bitstream.
696 if (TheModule)
697 return Error("Multiple MODULE_BLOCKs in same stream");
698
699 if (Stream.EnterSubBlock())
700 return Error("Malformed block record");
701
702 // Otherwise, create the module.
703 TheModule = new Module(ModuleID);
704
705 SmallVector<uint64_t, 64> Record;
706 std::vector<std::string> SectionTable;
707
708 // Read all the records for this module.
709 while (!Stream.AtEndOfStream()) {
710 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000711 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000712 if (Stream.ReadBlockEnd())
713 return Error("Error at end of module block");
714
715 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000716 ResolveGlobalAndAliasInits();
717 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000718 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000719 if (!FunctionsWithBodies.empty())
720 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000721
722 // Force deallocation of memory for these vectors to favor the client that
723 // want lazy deserialization.
724 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
725 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
726 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000727 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000728 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000729
730 if (Code == bitc::ENTER_SUBBLOCK) {
731 switch (Stream.ReadSubBlockID()) {
732 default: // Skip unknown content.
733 if (Stream.SkipBlock())
734 return Error("Malformed block record");
735 break;
736 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000737 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000738 return true;
739 break;
740 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000741 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000742 return true;
743 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000744 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000745 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000746 return true;
747 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000748 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000749 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000750 return true;
751 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000752 case bitc::FUNCTION_BLOCK_ID:
753 // If this is the first function body we've seen, reverse the
754 // FunctionsWithBodies list.
755 if (!HasReversedFunctionsWithBodies) {
756 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
757 HasReversedFunctionsWithBodies = true;
758 }
759
Chris Lattner980e5aa2007-05-01 05:52:21 +0000760 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000761 return true;
762 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000763 }
764 continue;
765 }
766
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000767 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000768 Stream.ReadAbbrevRecord();
769 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000770 }
771
772 // Read a record.
773 switch (Stream.ReadRecord(Code, Record)) {
774 default: break; // Default behavior, ignore unknown content.
775 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
776 if (Record.size() < 1)
777 return Error("Malformed MODULE_CODE_VERSION");
778 // Only version #0 is supported so far.
779 if (Record[0] != 0)
780 return Error("Unknown bitstream version!");
781 break;
782 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
783 std::string S;
784 if (ConvertToString(Record, 0, S))
785 return Error("Invalid MODULE_CODE_TRIPLE record");
786 TheModule->setTargetTriple(S);
787 break;
788 }
789 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
790 std::string S;
791 if (ConvertToString(Record, 0, S))
792 return Error("Invalid MODULE_CODE_DATALAYOUT record");
793 TheModule->setDataLayout(S);
794 break;
795 }
796 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
797 std::string S;
798 if (ConvertToString(Record, 0, S))
799 return Error("Invalid MODULE_CODE_ASM record");
800 TheModule->setModuleInlineAsm(S);
801 break;
802 }
803 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
804 std::string S;
805 if (ConvertToString(Record, 0, S))
806 return Error("Invalid MODULE_CODE_DEPLIB record");
807 TheModule->addLibrary(S);
808 break;
809 }
810 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
811 std::string S;
812 if (ConvertToString(Record, 0, S))
813 return Error("Invalid MODULE_CODE_SECTIONNAME record");
814 SectionTable.push_back(S);
815 break;
816 }
817 // GLOBALVAR: [type, isconst, initid,
818 // linkage, alignment, section, visibility, threadlocal]
819 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000820 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000821 return Error("Invalid MODULE_CODE_GLOBALVAR record");
822 const Type *Ty = getTypeByID(Record[0]);
823 if (!isa<PointerType>(Ty))
824 return Error("Global not a pointer type!");
825 Ty = cast<PointerType>(Ty)->getElementType();
826
827 bool isConstant = Record[1];
828 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
829 unsigned Alignment = (1 << Record[4]) >> 1;
830 std::string Section;
831 if (Record[5]) {
832 if (Record[5]-1 >= SectionTable.size())
833 return Error("Invalid section ID");
834 Section = SectionTable[Record[5]-1];
835 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000836 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
837 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
838 bool isThreadLocal = false;
839 if (Record.size() >= 7) isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000840
841 GlobalVariable *NewGV =
842 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
843 NewGV->setAlignment(Alignment);
844 if (!Section.empty())
845 NewGV->setSection(Section);
846 NewGV->setVisibility(Visibility);
847 NewGV->setThreadLocal(isThreadLocal);
848
Chris Lattner0b2482a2007-04-23 21:26:05 +0000849 ValueList.push_back(NewGV);
850
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000851 // Remember which value to use for the global initializer.
852 if (unsigned InitID = Record[2])
853 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000854 break;
855 }
856 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
857 // visibility]
858 case bitc::MODULE_CODE_FUNCTION: {
859 if (Record.size() < 7)
860 return Error("Invalid MODULE_CODE_FUNCTION record");
861 const Type *Ty = getTypeByID(Record[0]);
862 if (!isa<PointerType>(Ty))
863 return Error("Function not a pointer type!");
864 const FunctionType *FTy =
865 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
866 if (!FTy)
867 return Error("Function not a pointer to function type!");
868
869 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
870 "", TheModule);
871
872 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +0000873 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000874 Func->setLinkage(GetDecodedLinkage(Record[3]));
875 Func->setAlignment((1 << Record[4]) >> 1);
876 if (Record[5]) {
877 if (Record[5]-1 >= SectionTable.size())
878 return Error("Invalid section ID");
879 Func->setSection(SectionTable[Record[5]-1]);
880 }
881 Func->setVisibility(GetDecodedVisibility(Record[6]));
882
Chris Lattner0b2482a2007-04-23 21:26:05 +0000883 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +0000884
885 // If this is a function with a body, remember the prototype we are
886 // creating now, so that we can match up the body with them later.
887 if (!isProto)
888 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000889 break;
890 }
Chris Lattner07d98b42007-04-26 02:46:40 +0000891 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +0000892 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +0000893 if (Record.size() < 3)
894 return Error("Invalid MODULE_ALIAS record");
895 const Type *Ty = getTypeByID(Record[0]);
896 if (!isa<PointerType>(Ty))
897 return Error("Function not a pointer type!");
898
899 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
900 "", 0, TheModule);
901 ValueList.push_back(NewGA);
902 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
903 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000904 }
Chris Lattner198f34a2007-04-26 03:27:58 +0000905 /// MODULE_CODE_PURGEVALS: [numvals]
906 case bitc::MODULE_CODE_PURGEVALS:
907 // Trim down the value list to the specified size.
908 if (Record.size() < 1 || Record[0] > ValueList.size())
909 return Error("Invalid MODULE_PURGEVALS record");
910 ValueList.shrinkTo(Record[0]);
911 break;
912 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000913 Record.clear();
914 }
915
916 return Error("Premature end of bitstream");
917}
918
919
Chris Lattnerc453f762007-04-29 07:54:31 +0000920bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000921 TheModule = 0;
922
Chris Lattnerc453f762007-04-29 07:54:31 +0000923 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000924 return Error("Bitcode stream should be a multiple of 4 bytes in length");
925
Chris Lattnerc453f762007-04-29 07:54:31 +0000926 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +0000927 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000928
929 // Sniff for the signature.
930 if (Stream.Read(8) != 'B' ||
931 Stream.Read(8) != 'C' ||
932 Stream.Read(4) != 0x0 ||
933 Stream.Read(4) != 0xC ||
934 Stream.Read(4) != 0xE ||
935 Stream.Read(4) != 0xD)
936 return Error("Invalid bitcode signature");
937
938 // We expect a number of well-defined blocks, though we don't necessarily
939 // need to understand them all.
940 while (!Stream.AtEndOfStream()) {
941 unsigned Code = Stream.ReadCode();
942
943 if (Code != bitc::ENTER_SUBBLOCK)
944 return Error("Invalid record at top-level");
945
946 unsigned BlockID = Stream.ReadSubBlockID();
947
948 // We only know the MODULE subblock ID.
949 if (BlockID == bitc::MODULE_BLOCK_ID) {
Chris Lattner86697142007-05-01 05:01:34 +0000950 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000951 return true;
952 } else if (Stream.SkipBlock()) {
953 return Error("Malformed block record");
954 }
955 }
956
957 return false;
958}
Chris Lattnerc453f762007-04-29 07:54:31 +0000959
Chris Lattner48f84872007-05-01 04:59:48 +0000960
961bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
962 // If it already is material, ignore the request.
963 if (!F->hasNotBeenReadFromBytecode()) return false;
964
965 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
966 DeferredFunctionInfo.find(F);
967 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
968
969 // Move the bit stream to the saved position of the deferred function body and
970 // restore the real linkage type for the function.
971 Stream.JumpToBit(DFII->second.first);
972 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
973 DeferredFunctionInfo.erase(DFII);
974
Chris Lattner980e5aa2007-05-01 05:52:21 +0000975 if (ParseFunctionBody(F)) {
976 if (ErrInfo) *ErrInfo = ErrorString;
977 return true;
978 }
979
980 return false;
981}
982
983Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
984 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
985 DeferredFunctionInfo.begin();
986 while (!DeferredFunctionInfo.empty()) {
987 Function *F = (*I++).first;
988 assert(F->hasNotBeenReadFromBytecode() &&
989 "Deserialized function found in map!");
990 if (materializeFunction(F, ErrInfo))
991 return 0;
992 }
993 return TheModule;
994}
995
996
997/// ParseFunctionBody - Lazily parse the specified function body block.
998bool BitcodeReader::ParseFunctionBody(Function *F) {
999 if (Stream.EnterSubBlock())
1000 return Error("Malformed block record");
1001
1002 unsigned ModuleValueListSize = ValueList.size();
1003
1004 // Add all the function arguments to the value table.
1005 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1006 ValueList.push_back(I);
1007
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001008 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001009 BasicBlock *CurBB = 0;
1010 unsigned CurBBNo = 0;
1011
Chris Lattner980e5aa2007-05-01 05:52:21 +00001012 // Read all the records.
1013 SmallVector<uint64_t, 64> Record;
1014 while (1) {
1015 unsigned Code = Stream.ReadCode();
1016 if (Code == bitc::END_BLOCK) {
1017 if (Stream.ReadBlockEnd())
1018 return Error("Error at end of function block");
1019 break;
1020 }
1021
1022 if (Code == bitc::ENTER_SUBBLOCK) {
1023 switch (Stream.ReadSubBlockID()) {
1024 default: // Skip unknown content.
1025 if (Stream.SkipBlock())
1026 return Error("Malformed block record");
1027 break;
1028 case bitc::CONSTANTS_BLOCK_ID:
1029 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001030 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001031 break;
1032 case bitc::VALUE_SYMTAB_BLOCK_ID:
1033 if (ParseValueSymbolTable()) return true;
1034 break;
1035 }
1036 continue;
1037 }
1038
1039 if (Code == bitc::DEFINE_ABBREV) {
1040 Stream.ReadAbbrevRecord();
1041 continue;
1042 }
1043
1044 // Read a record.
1045 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001046 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001047 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001048 default: // Default behavior: reject
1049 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001050 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001051 if (Record.size() < 1 || Record[0] == 0)
1052 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001053 // Create all the basic blocks for the function.
1054 FunctionBBs.resize(Record.size());
1055 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1056 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001057 CurBB = FunctionBBs[0];
1058 continue;
1059
Chris Lattner231cbcb2007-05-02 04:27:25 +00001060 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001061 if (Record.size() < 4) return Error("Invalid BINOP record");
1062 const Type *Ty = getTypeByID(Record[1]);
1063 int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1064 Value *LHS = getFnValueByID(Record[2], Ty);
1065 Value *RHS = getFnValueByID(Record[3], Ty);
1066 if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1067 return Error("Invalid BINOP record");
1068 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001069 break;
1070 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001071 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
1072 if (Record.size() < 4) return Error("Invalid CAST record");
1073 int Opc = GetDecodedCastOpcode(Record[0]);
1074 const Type *ResTy = getTypeByID(Record[1]);
1075 const Type *OpTy = getTypeByID(Record[2]);
1076 Value *Op = getFnValueByID(Record[3], OpTy);
1077 if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1078 return Error("Invalid CAST record");
1079 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1080 break;
1081 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001082#if 0
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001083 case bitc::FUNC_CODE_INST_GEP:
1084 // GEP: [n, n x operands]
1085 case bitc::FUNC_CODE_INST_SELECT:
1086 // SELECT: [ty, opval, opval, opval]
1087 case bitc::FUNC_CODE_INST_EXTRACTELT:
1088 // EXTRACTELT: [opty, opval, opval]
1089 case bitc::FUNC_CODE_INST_INSERTELT:
1090 // INSERTELT: [ty, opval, opval, opval]
1091 case bitc::FUNC_CODE_INST_SHUFFLEVEC:
1092 // SHUFFLEVEC: [ty, opval, opval, opval]
1093 case bitc::FUNC_CODE_INST_CMP:
1094 // CMP: [opty, opval, opval, pred]
Chris Lattner231cbcb2007-05-02 04:27:25 +00001095#endif
1096
1097 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1098 if (Record.size() == 0) {
1099 I = new ReturnInst();
1100 break;
1101 }
1102 if (Record.size() == 2) {
1103 const Type *OpTy = getTypeByID(Record[0]);
1104 Value *Op = getFnValueByID(Record[1], OpTy);
1105 if (OpTy && Op);
1106 I = new ReturnInst(Op);
1107 break;
1108 }
1109 return Error("Invalid RET record");
1110#if 0
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001111 case bitc::FUNC_CODE_INST_BR:
1112 // BR: [opval, bb#, bb#] or [bb#]
1113 case bitc::FUNC_CODE_INST_SWITCH:
1114 // SWITCH: [opty, opval, n, n x ops]
1115 case bitc::FUNC_CODE_INST_INVOKE:
1116 // INVOKE: [fnty, op0,op1,op2, ...]
Chris Lattner231cbcb2007-05-02 04:27:25 +00001117 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1118 I = new UnwindInst();
1119 break;
1120 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1121 I = new UnreachableInst();
1122 break;
1123
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001124 case bitc::FUNC_CODE_INST_PHI:
1125 // PHI: [ty, #ops, val0,bb0, ...]
1126 case bitc::FUNC_CODE_INST_MALLOC:
1127 // MALLOC: [instty, op, align]
1128 case bitc::FUNC_CODE_INST_FREE:
1129 // FREE: [opty, op]
1130 case bitc::FUNC_CODE_INST_ALLOCA:
1131 // ALLOCA: [instty, op, align]
1132 case bitc::FUNC_CODE_INST_LOAD:
1133 // LOAD: [opty, op, align, vol]
1134 case bitc::FUNC_CODE_INST_STORE:
1135 // STORE: [ptrty,val,ptr, align, vol]
1136 case bitc::FUNC_CODE_INST_CALL:
1137 // CALL: [fnty, fnid, arg0, arg1...]
1138 case bitc::FUNC_CODE_INST_VAARG:
1139 // VAARG: [valistty, valist, instty]
1140 break;
1141#endif
1142 }
1143
1144 // Add instruction to end of current BB. If there is no current BB, reject
1145 // this file.
1146 if (CurBB == 0) {
1147 delete I;
1148 return Error("Invalid instruction with no BB");
1149 }
1150 CurBB->getInstList().push_back(I);
1151
1152 // If this was a terminator instruction, move to the next block.
1153 if (isa<TerminatorInst>(I)) {
1154 ++CurBBNo;
1155 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1156 }
1157
1158 // Non-void values get registered in the value table for future use.
1159 if (I && I->getType() != Type::VoidTy)
1160 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001161 }
1162
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001163 // Check the function list for unresolved values.
1164 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1165 if (A->getParent() == 0) {
1166 // We found at least one unresolved value. Nuke them all to avoid leaks.
1167 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1168 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1169 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1170 delete A;
1171 }
1172 }
1173 }
1174 return Error("Never resolved value found in function!");
1175 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001176
1177 // Trim the value list down to the size it was before we parsed this function.
1178 ValueList.shrinkTo(ModuleValueListSize);
1179 std::vector<BasicBlock*>().swap(FunctionBBs);
1180
Chris Lattner48f84872007-05-01 04:59:48 +00001181 return false;
1182}
1183
1184
Chris Lattnerc453f762007-04-29 07:54:31 +00001185//===----------------------------------------------------------------------===//
1186// External interface
1187//===----------------------------------------------------------------------===//
1188
1189/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1190///
1191ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1192 std::string *ErrMsg) {
1193 BitcodeReader *R = new BitcodeReader(Buffer);
1194 if (R->ParseBitcode()) {
1195 if (ErrMsg)
1196 *ErrMsg = R->getErrorString();
1197
1198 // Don't let the BitcodeReader dtor delete 'Buffer'.
1199 R->releaseMemoryBuffer();
1200 delete R;
1201 return 0;
1202 }
1203 return R;
1204}
1205
1206/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1207/// If an error occurs, return null and fill in *ErrMsg if non-null.
1208Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1209 BitcodeReader *R;
1210 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1211 if (!R) return 0;
1212
1213 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1214 // delete it when its dtor is run.
1215 Module *M = R->releaseModule(ErrMsg);
1216
1217 // Don't let the BitcodeReader dtor delete 'Buffer'.
1218 R->releaseMemoryBuffer();
1219 delete R;
1220 return M;
1221}