blob: 48604ca91daacfb8f993293737f5438b754527b5 [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
Chris Lattner01ff65f2007-05-02 05:16:49 +0000153 // No type specified, must be invalid reference.
154 if (Ty == 0) return 0;
155
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000156 // Create and return a placeholder, which will later be RAUW'd.
157 Value *V = new Argument(Ty);
158 Uses[Idx].init(V, this);
159 return V;
160}
161
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000162
163const 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;
168
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();
174}
175
Chris Lattner86697142007-05-01 05:01:34 +0000176bool BitcodeReader::ParseTypeTable() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000177 if (Stream.EnterSubBlock())
178 return Error("Malformed block record");
179
180 if (!TypeList.empty())
181 return Error("Multiple TYPE_BLOCKs found!");
182
183 SmallVector<uint64_t, 64> Record;
184 unsigned NumRecords = 0;
185
186 // Read all the records for this type table.
187 while (1) {
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");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000192 if (Stream.ReadBlockEnd())
193 return Error("Error at end of type table block");
194 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000195 }
196
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");
202 continue;
203 }
204
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000205 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000206 Stream.ReadAbbrevRecord();
207 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000208 }
209
210 // Read a record.
211 Record.clear();
212 const Type *ResultTy = 0;
213 switch (Stream.ReadRecord(Code, Record)) {
214 default: // Default behavior: unknown type.
215 ResultTy = 0;
216 break;
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]);
223 continue;
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");
228 continue;
229
230 case bitc::TYPE_CODE_VOID: // VOID
231 ResultTy = Type::VoidTy;
232 break;
233 case bitc::TYPE_CODE_FLOAT: // FLOAT
234 ResultTy = Type::FloatTy;
235 break;
236 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
237 ResultTy = Type::DoubleTy;
238 break;
239 case bitc::TYPE_CODE_LABEL: // LABEL
240 ResultTy = Type::LabelTy;
241 break;
242 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
243 ResultTy = 0;
244 break;
245 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
246 if (Record.size() < 1)
247 return Error("Invalid Integer type record");
248
249 ResultTy = IntegerType::get(Record[0]);
250 break;
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));
255 break;
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));
263
264 // FIXME: PARAM TYS.
265 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
266 Record[0]);
267 break;
268 }
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]);
276 break;
277 }
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]);
282 break;
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]);
287 break;
288 }
289
290 if (NumRecords == TypeList.size()) {
291 // If this is a new type slot, just append it.
292 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
293 ++NumRecords;
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.
298 ++NumRecords;
299 } else {
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());
304
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);
311
312 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000313 // value table... or with a preexisting type that was already in the
314 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000315 assert(TypeList[NumRecords-1].get() != OldTy &&
316 "refineAbstractType didn't work!");
317 }
318 }
319}
320
321
Chris Lattner86697142007-05-01 05:01:34 +0000322bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000323 if (Stream.EnterSubBlock())
324 return Error("Malformed block record");
325
326 SmallVector<uint64_t, 64> Record;
327
328 // Read all the records for this type table.
329 std::string TypeName;
330 while (1) {
331 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000332 if (Code == bitc::END_BLOCK) {
333 if (Stream.ReadBlockEnd())
334 return Error("Error at end of type symbol table block");
335 return false;
336 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000337
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");
343 continue;
344 }
345
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000346 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000347 Stream.ReadAbbrevRecord();
348 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000349 }
350
351 // Read a record.
352 Record.clear();
353 switch (Stream.ReadRecord(Code, Record)) {
354 default: // Default behavior: unknown type.
355 break;
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000356 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000357 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");
362
363 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
364 TypeName.clear();
365 break;
366 }
367 }
368}
369
Chris Lattner86697142007-05-01 05:01:34 +0000370bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000371 if (Stream.EnterSubBlock())
372 return Error("Malformed block record");
373
374 SmallVector<uint64_t, 64> Record;
375
376 // Read all the records for this value table.
377 SmallString<128> ValueName;
378 while (1) {
379 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000380 if (Code == bitc::END_BLOCK) {
381 if (Stream.ReadBlockEnd())
382 return Error("Error at end of value symbol table block");
383 return false;
384 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000385 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");
390 continue;
391 }
392
393 if (Code == bitc::DEFINE_ABBREV) {
394 Stream.ReadAbbrevRecord();
395 continue;
396 }
397
398 // Read a record.
399 Record.clear();
400 switch (Stream.ReadRecord(Code, Record)) {
401 default: // Default behavior: unknown type.
402 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000403 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namelen, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000404 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];
410
411 V->setName(&ValueName[0], ValueName.size());
412 ValueName.clear();
413 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000414 }
415 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000416 if (ConvertToString(Record, 1, ValueName))
417 return Error("Invalid VST_BBENTRY record");
418 BasicBlock *BB = getBasicBlock(Record[0]);
419 if (BB == 0)
420 return Error("Invalid BB ID in VST_BBENTRY record");
421
422 BB->setName(&ValueName[0], ValueName.size());
423 ValueName.clear();
424 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000425 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000426 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000427 }
428}
429
Chris Lattner0eef0802007-04-24 04:04:35 +0000430/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
431/// the LSB for dense VBR encoding.
432static uint64_t DecodeSignRotatedValue(uint64_t V) {
433 if ((V & 1) == 0)
434 return V >> 1;
435 if (V != 1)
436 return -(V >> 1);
437 // There is no such thing as -0 with integers. "-0" really means MININT.
438 return 1ULL << 63;
439}
440
Chris Lattner07d98b42007-04-26 02:46:40 +0000441/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
442/// values and aliases that we can.
443bool BitcodeReader::ResolveGlobalAndAliasInits() {
444 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
445 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
446
447 GlobalInitWorklist.swap(GlobalInits);
448 AliasInitWorklist.swap(AliasInits);
449
450 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000451 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000452 if (ValID >= ValueList.size()) {
453 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000454 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000455 } else {
456 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
457 GlobalInitWorklist.back().first->setInitializer(C);
458 else
459 return Error("Global variable initializer is not a constant!");
460 }
461 GlobalInitWorklist.pop_back();
462 }
463
464 while (!AliasInitWorklist.empty()) {
465 unsigned ValID = AliasInitWorklist.back().second;
466 if (ValID >= ValueList.size()) {
467 AliasInits.push_back(AliasInitWorklist.back());
468 } else {
469 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000470 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000471 else
472 return Error("Alias initializer is not a constant!");
473 }
474 AliasInitWorklist.pop_back();
475 }
476 return false;
477}
478
479
Chris Lattner86697142007-05-01 05:01:34 +0000480bool BitcodeReader::ParseConstants() {
Chris Lattnere16504e2007-04-24 03:30:34 +0000481 if (Stream.EnterSubBlock())
482 return Error("Malformed block record");
483
484 SmallVector<uint64_t, 64> Record;
485
486 // Read all the records for this value table.
487 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000488 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000489 while (1) {
490 unsigned Code = Stream.ReadCode();
491 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000492 if (NextCstNo != ValueList.size())
493 return Error("Invalid constant reference!");
494
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000495 if (Stream.ReadBlockEnd())
496 return Error("Error at end of constants block");
497 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000498 }
499
500 if (Code == bitc::ENTER_SUBBLOCK) {
501 // No known subblocks, always skip them.
502 Stream.ReadSubBlockID();
503 if (Stream.SkipBlock())
504 return Error("Malformed block record");
505 continue;
506 }
507
508 if (Code == bitc::DEFINE_ABBREV) {
509 Stream.ReadAbbrevRecord();
510 continue;
511 }
512
513 // Read a record.
514 Record.clear();
515 Value *V = 0;
516 switch (Stream.ReadRecord(Code, Record)) {
517 default: // Default behavior: unknown constant
518 case bitc::CST_CODE_UNDEF: // UNDEF
519 V = UndefValue::get(CurTy);
520 break;
521 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
522 if (Record.empty())
523 return Error("Malformed CST_SETTYPE record");
524 if (Record[0] >= TypeList.size())
525 return Error("Invalid Type ID in CST_SETTYPE record");
526 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000527 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000528 case bitc::CST_CODE_NULL: // NULL
529 V = Constant::getNullValue(CurTy);
530 break;
531 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000532 if (!isa<IntegerType>(CurTy) || Record.empty())
533 return Error("Invalid CST_INTEGER record");
534 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
535 break;
536 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
537 if (!isa<IntegerType>(CurTy) || Record.empty() ||
538 Record.size() < Record[0]+1)
539 return Error("Invalid WIDE_INTEGER record");
540
541 unsigned NumWords = Record[0];
Chris Lattner084a8442007-04-24 17:22:05 +0000542 SmallVector<uint64_t, 8> Words;
543 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000544 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner084a8442007-04-24 17:22:05 +0000545 Words[i] = DecodeSignRotatedValue(Record[i+1]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000546 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000547 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000548 break;
549 }
550 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
551 if (Record.empty())
552 return Error("Invalid FLOAT record");
553 if (CurTy == Type::FloatTy)
554 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
555 else if (CurTy == Type::DoubleTy)
556 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
Chris Lattnere16504e2007-04-24 03:30:34 +0000557 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000558 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000559 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000560
561 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
562 if (Record.empty() || Record.size() < Record[0]+1)
563 return Error("Invalid CST_AGGREGATE record");
564
565 unsigned Size = Record[0];
566 std::vector<Constant*> Elts;
567
568 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
569 for (unsigned i = 0; i != Size; ++i)
570 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
571 STy->getElementType(i)));
572 V = ConstantStruct::get(STy, Elts);
573 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
574 const Type *EltTy = ATy->getElementType();
575 for (unsigned i = 0; i != Size; ++i)
576 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
577 V = ConstantArray::get(ATy, Elts);
578 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
579 const Type *EltTy = VTy->getElementType();
580 for (unsigned i = 0; i != Size; ++i)
581 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
582 V = ConstantVector::get(Elts);
583 } else {
584 V = UndefValue::get(CurTy);
585 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000586 break;
587 }
588
589 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
590 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
591 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000592 if (Opc < 0) {
593 V = UndefValue::get(CurTy); // Unknown binop.
594 } else {
595 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
596 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
597 V = ConstantExpr::get(Opc, LHS, RHS);
598 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000599 break;
600 }
601 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
602 if (Record.size() < 3) return Error("Invalid CE_CAST record");
603 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000604 if (Opc < 0) {
605 V = UndefValue::get(CurTy); // Unknown cast.
606 } else {
607 const Type *OpTy = getTypeByID(Record[1]);
608 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
609 V = ConstantExpr::getCast(Opc, Op, CurTy);
610 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000611 break;
612 }
613 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
614 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
615 SmallVector<Constant*, 16> Elts;
616 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
617 const Type *ElTy = getTypeByID(Record[i]);
618 if (!ElTy) return Error("Invalid CE_GEP record");
619 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
620 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000621 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
622 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000623 }
624 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
625 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
626 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
627 Type::Int1Ty),
628 ValueList.getConstantFwdRef(Record[1],CurTy),
629 ValueList.getConstantFwdRef(Record[2],CurTy));
630 break;
631 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
632 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
633 const VectorType *OpTy =
634 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
635 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
636 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
637 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
638 OpTy->getElementType());
639 V = ConstantExpr::getExtractElement(Op0, Op1);
640 break;
641 }
642 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
643 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
644 if (Record.size() < 3 || OpTy == 0)
645 return Error("Invalid CE_INSERTELT record");
646 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
647 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
648 OpTy->getElementType());
649 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
650 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
651 break;
652 }
653 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
654 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
655 if (Record.size() < 3 || OpTy == 0)
656 return Error("Invalid CE_INSERTELT record");
657 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
658 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
659 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
660 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
661 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
662 break;
663 }
664 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
665 if (Record.size() < 4) return Error("Invalid CE_CMP record");
666 const Type *OpTy = getTypeByID(Record[0]);
667 if (OpTy == 0) return Error("Invalid CE_CMP record");
668 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
669 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
670
671 if (OpTy->isFloatingPoint())
672 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
673 else
674 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
675 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000676 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000677 }
678
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000679 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000680 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000681 }
682}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000683
Chris Lattner980e5aa2007-05-01 05:52:21 +0000684/// RememberAndSkipFunctionBody - When we see the block for a function body,
685/// remember where it is and then skip it. This lets us lazily deserialize the
686/// functions.
687bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000688 // Get the function we are talking about.
689 if (FunctionsWithBodies.empty())
690 return Error("Insufficient function protos");
691
692 Function *Fn = FunctionsWithBodies.back();
693 FunctionsWithBodies.pop_back();
694
695 // Save the current stream state.
696 uint64_t CurBit = Stream.GetCurrentBitNo();
697 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
698
699 // Set the functions linkage to GhostLinkage so we know it is lazily
700 // deserialized.
701 Fn->setLinkage(GlobalValue::GhostLinkage);
702
703 // Skip over the function block for now.
704 if (Stream.SkipBlock())
705 return Error("Malformed block record");
706 return false;
707}
708
Chris Lattner86697142007-05-01 05:01:34 +0000709bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000710 // Reject multiple MODULE_BLOCK's in a single bitstream.
711 if (TheModule)
712 return Error("Multiple MODULE_BLOCKs in same stream");
713
714 if (Stream.EnterSubBlock())
715 return Error("Malformed block record");
716
717 // Otherwise, create the module.
718 TheModule = new Module(ModuleID);
719
720 SmallVector<uint64_t, 64> Record;
721 std::vector<std::string> SectionTable;
722
723 // Read all the records for this module.
724 while (!Stream.AtEndOfStream()) {
725 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000726 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000727 if (Stream.ReadBlockEnd())
728 return Error("Error at end of module block");
729
730 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000731 ResolveGlobalAndAliasInits();
732 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000733 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000734 if (!FunctionsWithBodies.empty())
735 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000736
737 // Force deallocation of memory for these vectors to favor the client that
738 // want lazy deserialization.
739 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
740 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
741 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000742 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000743 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000744
745 if (Code == bitc::ENTER_SUBBLOCK) {
746 switch (Stream.ReadSubBlockID()) {
747 default: // Skip unknown content.
748 if (Stream.SkipBlock())
749 return Error("Malformed block record");
750 break;
751 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000752 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000753 return true;
754 break;
755 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000756 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000757 return true;
758 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000759 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000760 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000761 return true;
762 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000763 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000764 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000765 return true;
766 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000767 case bitc::FUNCTION_BLOCK_ID:
768 // If this is the first function body we've seen, reverse the
769 // FunctionsWithBodies list.
770 if (!HasReversedFunctionsWithBodies) {
771 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
772 HasReversedFunctionsWithBodies = true;
773 }
774
Chris Lattner980e5aa2007-05-01 05:52:21 +0000775 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000776 return true;
777 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000778 }
779 continue;
780 }
781
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000782 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000783 Stream.ReadAbbrevRecord();
784 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000785 }
786
787 // Read a record.
788 switch (Stream.ReadRecord(Code, Record)) {
789 default: break; // Default behavior, ignore unknown content.
790 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
791 if (Record.size() < 1)
792 return Error("Malformed MODULE_CODE_VERSION");
793 // Only version #0 is supported so far.
794 if (Record[0] != 0)
795 return Error("Unknown bitstream version!");
796 break;
797 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
798 std::string S;
799 if (ConvertToString(Record, 0, S))
800 return Error("Invalid MODULE_CODE_TRIPLE record");
801 TheModule->setTargetTriple(S);
802 break;
803 }
804 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
805 std::string S;
806 if (ConvertToString(Record, 0, S))
807 return Error("Invalid MODULE_CODE_DATALAYOUT record");
808 TheModule->setDataLayout(S);
809 break;
810 }
811 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
812 std::string S;
813 if (ConvertToString(Record, 0, S))
814 return Error("Invalid MODULE_CODE_ASM record");
815 TheModule->setModuleInlineAsm(S);
816 break;
817 }
818 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
819 std::string S;
820 if (ConvertToString(Record, 0, S))
821 return Error("Invalid MODULE_CODE_DEPLIB record");
822 TheModule->addLibrary(S);
823 break;
824 }
825 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
826 std::string S;
827 if (ConvertToString(Record, 0, S))
828 return Error("Invalid MODULE_CODE_SECTIONNAME record");
829 SectionTable.push_back(S);
830 break;
831 }
832 // GLOBALVAR: [type, isconst, initid,
833 // linkage, alignment, section, visibility, threadlocal]
834 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000835 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000836 return Error("Invalid MODULE_CODE_GLOBALVAR record");
837 const Type *Ty = getTypeByID(Record[0]);
838 if (!isa<PointerType>(Ty))
839 return Error("Global not a pointer type!");
840 Ty = cast<PointerType>(Ty)->getElementType();
841
842 bool isConstant = Record[1];
843 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
844 unsigned Alignment = (1 << Record[4]) >> 1;
845 std::string Section;
846 if (Record[5]) {
847 if (Record[5]-1 >= SectionTable.size())
848 return Error("Invalid section ID");
849 Section = SectionTable[Record[5]-1];
850 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000851 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
852 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
853 bool isThreadLocal = false;
854 if (Record.size() >= 7) isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000855
856 GlobalVariable *NewGV =
857 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
858 NewGV->setAlignment(Alignment);
859 if (!Section.empty())
860 NewGV->setSection(Section);
861 NewGV->setVisibility(Visibility);
862 NewGV->setThreadLocal(isThreadLocal);
863
Chris Lattner0b2482a2007-04-23 21:26:05 +0000864 ValueList.push_back(NewGV);
865
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000866 // Remember which value to use for the global initializer.
867 if (unsigned InitID = Record[2])
868 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000869 break;
870 }
871 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
872 // visibility]
873 case bitc::MODULE_CODE_FUNCTION: {
874 if (Record.size() < 7)
875 return Error("Invalid MODULE_CODE_FUNCTION record");
876 const Type *Ty = getTypeByID(Record[0]);
877 if (!isa<PointerType>(Ty))
878 return Error("Function not a pointer type!");
879 const FunctionType *FTy =
880 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
881 if (!FTy)
882 return Error("Function not a pointer to function type!");
883
884 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
885 "", TheModule);
886
887 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +0000888 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000889 Func->setLinkage(GetDecodedLinkage(Record[3]));
890 Func->setAlignment((1 << Record[4]) >> 1);
891 if (Record[5]) {
892 if (Record[5]-1 >= SectionTable.size())
893 return Error("Invalid section ID");
894 Func->setSection(SectionTable[Record[5]-1]);
895 }
896 Func->setVisibility(GetDecodedVisibility(Record[6]));
897
Chris Lattner0b2482a2007-04-23 21:26:05 +0000898 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +0000899
900 // If this is a function with a body, remember the prototype we are
901 // creating now, so that we can match up the body with them later.
902 if (!isProto)
903 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000904 break;
905 }
Chris Lattner07d98b42007-04-26 02:46:40 +0000906 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +0000907 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +0000908 if (Record.size() < 3)
909 return Error("Invalid MODULE_ALIAS record");
910 const Type *Ty = getTypeByID(Record[0]);
911 if (!isa<PointerType>(Ty))
912 return Error("Function not a pointer type!");
913
914 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
915 "", 0, TheModule);
916 ValueList.push_back(NewGA);
917 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
918 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000919 }
Chris Lattner198f34a2007-04-26 03:27:58 +0000920 /// MODULE_CODE_PURGEVALS: [numvals]
921 case bitc::MODULE_CODE_PURGEVALS:
922 // Trim down the value list to the specified size.
923 if (Record.size() < 1 || Record[0] > ValueList.size())
924 return Error("Invalid MODULE_PURGEVALS record");
925 ValueList.shrinkTo(Record[0]);
926 break;
927 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000928 Record.clear();
929 }
930
931 return Error("Premature end of bitstream");
932}
933
934
Chris Lattnerc453f762007-04-29 07:54:31 +0000935bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000936 TheModule = 0;
937
Chris Lattnerc453f762007-04-29 07:54:31 +0000938 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000939 return Error("Bitcode stream should be a multiple of 4 bytes in length");
940
Chris Lattnerc453f762007-04-29 07:54:31 +0000941 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +0000942 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000943
944 // Sniff for the signature.
945 if (Stream.Read(8) != 'B' ||
946 Stream.Read(8) != 'C' ||
947 Stream.Read(4) != 0x0 ||
948 Stream.Read(4) != 0xC ||
949 Stream.Read(4) != 0xE ||
950 Stream.Read(4) != 0xD)
951 return Error("Invalid bitcode signature");
952
953 // We expect a number of well-defined blocks, though we don't necessarily
954 // need to understand them all.
955 while (!Stream.AtEndOfStream()) {
956 unsigned Code = Stream.ReadCode();
957
958 if (Code != bitc::ENTER_SUBBLOCK)
959 return Error("Invalid record at top-level");
960
961 unsigned BlockID = Stream.ReadSubBlockID();
962
963 // We only know the MODULE subblock ID.
964 if (BlockID == bitc::MODULE_BLOCK_ID) {
Chris Lattner86697142007-05-01 05:01:34 +0000965 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000966 return true;
967 } else if (Stream.SkipBlock()) {
968 return Error("Malformed block record");
969 }
970 }
971
972 return false;
973}
Chris Lattnerc453f762007-04-29 07:54:31 +0000974
Chris Lattner48f84872007-05-01 04:59:48 +0000975
976bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
977 // If it already is material, ignore the request.
978 if (!F->hasNotBeenReadFromBytecode()) return false;
979
980 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
981 DeferredFunctionInfo.find(F);
982 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
983
984 // Move the bit stream to the saved position of the deferred function body and
985 // restore the real linkage type for the function.
986 Stream.JumpToBit(DFII->second.first);
987 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
988 DeferredFunctionInfo.erase(DFII);
989
Chris Lattner980e5aa2007-05-01 05:52:21 +0000990 if (ParseFunctionBody(F)) {
991 if (ErrInfo) *ErrInfo = ErrorString;
992 return true;
993 }
994
995 return false;
996}
997
998Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
999 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1000 DeferredFunctionInfo.begin();
1001 while (!DeferredFunctionInfo.empty()) {
1002 Function *F = (*I++).first;
1003 assert(F->hasNotBeenReadFromBytecode() &&
1004 "Deserialized function found in map!");
1005 if (materializeFunction(F, ErrInfo))
1006 return 0;
1007 }
1008 return TheModule;
1009}
1010
1011
1012/// ParseFunctionBody - Lazily parse the specified function body block.
1013bool BitcodeReader::ParseFunctionBody(Function *F) {
1014 if (Stream.EnterSubBlock())
1015 return Error("Malformed block record");
1016
1017 unsigned ModuleValueListSize = ValueList.size();
1018
1019 // Add all the function arguments to the value table.
1020 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1021 ValueList.push_back(I);
1022
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001023 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001024 BasicBlock *CurBB = 0;
1025 unsigned CurBBNo = 0;
1026
Chris Lattner980e5aa2007-05-01 05:52:21 +00001027 // Read all the records.
1028 SmallVector<uint64_t, 64> Record;
1029 while (1) {
1030 unsigned Code = Stream.ReadCode();
1031 if (Code == bitc::END_BLOCK) {
1032 if (Stream.ReadBlockEnd())
1033 return Error("Error at end of function block");
1034 break;
1035 }
1036
1037 if (Code == bitc::ENTER_SUBBLOCK) {
1038 switch (Stream.ReadSubBlockID()) {
1039 default: // Skip unknown content.
1040 if (Stream.SkipBlock())
1041 return Error("Malformed block record");
1042 break;
1043 case bitc::CONSTANTS_BLOCK_ID:
1044 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001045 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001046 break;
1047 case bitc::VALUE_SYMTAB_BLOCK_ID:
1048 if (ParseValueSymbolTable()) return true;
1049 break;
1050 }
1051 continue;
1052 }
1053
1054 if (Code == bitc::DEFINE_ABBREV) {
1055 Stream.ReadAbbrevRecord();
1056 continue;
1057 }
1058
1059 // Read a record.
1060 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001061 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001062 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001063 default: // Default behavior: reject
1064 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001065 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001066 if (Record.size() < 1 || Record[0] == 0)
1067 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001068 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001069 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001070 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1071 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001072 CurBB = FunctionBBs[0];
1073 continue;
1074
Chris Lattner231cbcb2007-05-02 04:27:25 +00001075 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001076 if (Record.size() < 4) return Error("Invalid BINOP record");
1077 const Type *Ty = getTypeByID(Record[1]);
1078 int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1079 Value *LHS = getFnValueByID(Record[2], Ty);
1080 Value *RHS = getFnValueByID(Record[3], Ty);
1081 if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1082 return Error("Invalid BINOP record");
1083 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001084 break;
1085 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001086 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
1087 if (Record.size() < 4) return Error("Invalid CAST record");
1088 int Opc = GetDecodedCastOpcode(Record[0]);
1089 const Type *ResTy = getTypeByID(Record[1]);
1090 const Type *OpTy = getTypeByID(Record[2]);
1091 Value *Op = getFnValueByID(Record[3], OpTy);
1092 if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1093 return Error("Invalid CAST record");
1094 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1095 break;
1096 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001097 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n, n x operands]
1098 if (Record.size() < 2 || (Record.size() & 1))
1099 return Error("Invalid GEP record");
1100 const Type *OpTy = getTypeByID(Record[0]);
1101 Value *Op = getFnValueByID(Record[1], OpTy);
1102 if (OpTy == 0 || Op == 0)
1103 return Error("Invalid GEP record");
1104
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001105 SmallVector<Value*, 16> GEPIdx;
Chris Lattner01ff65f2007-05-02 05:16:49 +00001106 for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
1107 const Type *IdxTy = getTypeByID(Record[i*2]);
1108 Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
1109 if (IdxTy == 0 || Idx == 0)
1110 return Error("Invalid GEP record");
1111 GEPIdx.push_back(Idx);
1112 }
1113
1114 I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
1115 break;
1116 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001117
Chris Lattner01ff65f2007-05-02 05:16:49 +00001118 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
1119 if (Record.size() < 4) return Error("Invalid SELECT record");
1120 const Type *Ty = getTypeByID(Record[0]);
1121 Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
1122 Value *LHS = getFnValueByID(Record[2], Ty);
1123 Value *RHS = getFnValueByID(Record[3], Ty);
1124 if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
1125 return Error("Invalid SELECT record");
1126 I = new SelectInst(Cond, LHS, RHS);
1127 break;
1128 }
1129
1130 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1131 if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
1132 const Type *OpTy = getTypeByID(Record[0]);
1133 Value *Vec = getFnValueByID(Record[1], OpTy);
1134 Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
1135 if (OpTy == 0 || Vec == 0 || Idx == 0)
1136 return Error("Invalid EXTRACTELT record");
1137 I = new ExtractElementInst(Vec, Idx);
1138 break;
1139 }
1140
1141 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1142 if (Record.size() < 4) return Error("Invalid INSERTELT record");
1143 const VectorType *OpTy =
1144 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1145 if (OpTy == 0) return Error("Invalid INSERTELT record");
1146 Value *Vec = getFnValueByID(Record[1], OpTy);
1147 Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
1148 Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
1149 if (Vec == 0 || Elt == 0 || Idx == 0)
1150 return Error("Invalid INSERTELT record");
1151 I = new InsertElementInst(Vec, Elt, Idx);
1152 break;
1153 }
1154
1155 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
1156 if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
1157 const VectorType *OpTy =
1158 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1159 if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
1160 Value *Vec1 = getFnValueByID(Record[1], OpTy);
1161 Value *Vec2 = getFnValueByID(Record[2], OpTy);
1162 Value *Mask = getFnValueByID(Record[3],
1163 VectorType::get(Type::Int32Ty,
1164 OpTy->getNumElements()));
1165 if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
1166 return Error("Invalid SHUFFLEVEC record");
1167 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1168 break;
1169 }
1170
1171 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1172 if (Record.size() < 4) return Error("Invalid CMP record");
1173 const Type *OpTy = getTypeByID(Record[0]);
1174 Value *LHS = getFnValueByID(Record[1], OpTy);
1175 Value *RHS = getFnValueByID(Record[2], OpTy);
1176 if (OpTy == 0 || LHS == 0 || RHS == 0)
1177 return Error("Invalid CMP record");
1178 if (OpTy->isFPOrFPVector())
1179 I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
1180 else
1181 I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
1182 break;
1183 }
1184
Chris Lattner231cbcb2007-05-02 04:27:25 +00001185 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1186 if (Record.size() == 0) {
1187 I = new ReturnInst();
1188 break;
1189 }
1190 if (Record.size() == 2) {
1191 const Type *OpTy = getTypeByID(Record[0]);
1192 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001193 if (!OpTy || !Op)
1194 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001195 I = new ReturnInst(Op);
1196 break;
1197 }
1198 return Error("Invalid RET record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001199 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001200 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001201 return Error("Invalid BR record");
1202 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1203 if (TrueDest == 0)
1204 return Error("Invalid BR record");
1205
1206 if (Record.size() == 1)
1207 I = new BranchInst(TrueDest);
1208 else {
1209 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1210 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1211 if (FalseDest == 0 || Cond == 0)
1212 return Error("Invalid BR record");
1213 I = new BranchInst(TrueDest, FalseDest, Cond);
1214 }
1215 break;
1216 }
1217 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1218 if (Record.size() < 3 || (Record.size() & 1) == 0)
1219 return Error("Invalid SWITCH record");
1220 const Type *OpTy = getTypeByID(Record[0]);
1221 Value *Cond = getFnValueByID(Record[1], OpTy);
1222 BasicBlock *Default = getBasicBlock(Record[2]);
1223 if (OpTy == 0 || Cond == 0 || Default == 0)
1224 return Error("Invalid SWITCH record");
1225 unsigned NumCases = (Record.size()-3)/2;
1226 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1227 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1228 ConstantInt *CaseVal =
1229 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1230 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1231 if (CaseVal == 0 || DestBB == 0) {
1232 delete SI;
1233 return Error("Invalid SWITCH record!");
1234 }
1235 SI->addCase(CaseVal, DestBB);
1236 }
1237 I = SI;
1238 break;
1239 }
1240
Chris Lattner76520192007-05-03 22:34:03 +00001241 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1242 if (Record.size() < 5)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001243 return Error("Invalid INVOKE record");
Chris Lattner76520192007-05-03 22:34:03 +00001244 unsigned CCInfo = Record[0];
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001245 const PointerType *CalleeTy =
Chris Lattner76520192007-05-03 22:34:03 +00001246 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
1247 Value *Callee = getFnValueByID(Record[2], CalleeTy);
1248 BasicBlock *NormalBB = getBasicBlock(Record[3]);
1249 BasicBlock *UnwindBB = getBasicBlock(Record[4]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001250 if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
1251 return Error("Invalid INVOKE record");
1252
1253 const FunctionType *FTy =
1254 dyn_cast<FunctionType>(CalleeTy->getElementType());
1255
1256 // Check that the right number of fixed parameters are here.
Chris Lattner76520192007-05-03 22:34:03 +00001257 if (FTy == 0 || Record.size() < 5+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001258 return Error("Invalid INVOKE record");
1259
1260 SmallVector<Value*, 16> Ops;
1261 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
Chris Lattner76520192007-05-03 22:34:03 +00001262 Ops.push_back(getFnValueByID(Record[5+i], FTy->getParamType(i)));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001263 if (Ops.back() == 0)
1264 return Error("Invalid INVOKE record");
1265 }
1266
Chris Lattner76520192007-05-03 22:34:03 +00001267 unsigned FirstVarargParam = 5+FTy->getNumParams();
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001268 if (FTy->isVarArg()) {
1269 // Read type/value pairs for varargs params.
1270 if ((Record.size()-FirstVarargParam) & 1)
1271 return Error("Invalid INVOKE record");
1272
1273 for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
1274 const Type *ArgTy = getTypeByID(Record[i]);
1275 Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
1276 if (Ops.back() == 0 || ArgTy == 0)
1277 return Error("Invalid INVOKE record");
1278 }
1279 } else {
1280 if (Record.size() != FirstVarargParam)
1281 return Error("Invalid INVOKE record");
1282 }
1283
1284 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
Chris Lattner76520192007-05-03 22:34:03 +00001285 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001286 break;
1287 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001288 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1289 I = new UnwindInst();
1290 break;
1291 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1292 I = new UnreachableInst();
1293 break;
Chris Lattner2a98cca2007-05-03 18:58:09 +00001294 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
1295 if (Record.size() < 2 || Record.size() < 2+Record[1] || (Record[1]&1))
1296 return Error("Invalid PHI record");
1297 const Type *Ty = getTypeByID(Record[0]);
1298 if (!Ty) return Error("Invalid PHI record");
1299
1300 PHINode *PN = new PHINode(Ty);
1301 PN->reserveOperandSpace(Record[1]);
1302
1303 for (unsigned i = 0, e = Record[1]; i != e; i += 2) {
1304 Value *V = getFnValueByID(Record[2+i], Ty);
1305 BasicBlock *BB = getBasicBlock(Record[3+i]);
1306 if (!V || !BB) return Error("Invalid PHI record");
1307 PN->addIncoming(V, BB);
1308 }
1309 I = PN;
1310 break;
1311 }
1312
1313 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1314 if (Record.size() < 3)
1315 return Error("Invalid MALLOC record");
1316 const PointerType *Ty =
1317 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1318 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1319 unsigned Align = Record[2];
1320 if (!Ty || !Size) return Error("Invalid MALLOC record");
1321 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1322 break;
1323 }
1324 case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
1325 if (Record.size() < 2)
1326 return Error("Invalid FREE record");
1327 const Type *OpTy = getTypeByID(Record[0]);
1328 Value *Op = getFnValueByID(Record[1], OpTy);
1329 if (!OpTy || !Op)
1330 return Error("Invalid FREE record");
1331 I = new FreeInst(Op);
1332 break;
1333 }
1334 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1335 if (Record.size() < 3)
1336 return Error("Invalid ALLOCA record");
1337 const PointerType *Ty =
1338 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1339 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1340 unsigned Align = Record[2];
1341 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1342 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1343 break;
1344 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001345 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1346 if (Record.size() < 4)
1347 return Error("Invalid LOAD record");
1348 const Type *OpTy = getTypeByID(Record[0]);
1349 Value *Op = getFnValueByID(Record[1], OpTy);
1350 if (!OpTy || !Op)
1351 return Error("Invalid LOAD record");
1352 I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001353 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001354 }
1355 case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
1356 if (Record.size() < 5)
1357 return Error("Invalid LOAD record");
Chris Lattnerc9c55a92007-05-03 22:21:59 +00001358 const PointerType *OpTy =
1359 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1360 Value *Op = getFnValueByID(Record[1], OpTy ? OpTy->getElementType() : 0);
1361 Value *Ptr = getFnValueByID(Record[2], OpTy);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001362 if (!OpTy || !Op || !Ptr)
1363 return Error("Invalid STORE record");
1364 I = new StoreInst(Op, Ptr, (1 << Record[3]) >> 1, Record[4]);
1365 break;
1366 }
Chris Lattner76520192007-05-03 22:34:03 +00001367 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1368 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001369 return Error("Invalid CALL record");
Chris Lattner76520192007-05-03 22:34:03 +00001370 unsigned CCInfo = Record[0];
Chris Lattner0579f7f2007-05-03 22:04:19 +00001371 const PointerType *OpTy =
Chris Lattner76520192007-05-03 22:34:03 +00001372 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001373 const FunctionType *FTy = 0;
1374 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner76520192007-05-03 22:34:03 +00001375 Value *Callee = getFnValueByID(Record[2], OpTy);
1376 if (!FTy || !Callee || Record.size() < FTy->getNumParams()+3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001377 return Error("Invalid CALL record");
1378
1379 SmallVector<Value*, 16> Args;
1380 // Read the fixed params.
1381 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
Chris Lattner76520192007-05-03 22:34:03 +00001382 Args.push_back(getFnValueByID(Record[i+3], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001383 if (Args.back() == 0) return Error("Invalid CALL record");
1384 }
1385
1386
1387 // Read type/value pairs for varargs params.
Chris Lattner76520192007-05-03 22:34:03 +00001388 unsigned NextArg = FTy->getNumParams()+3;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001389 if (!FTy->isVarArg()) {
1390 if (NextArg != Record.size())
1391 return Error("Invalid CALL record");
1392 } else {
1393 if ((Record.size()-NextArg) & 1)
1394 return Error("Invalid CALL record");
1395 for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
1396 Args.push_back(getFnValueByID(Record[NextArg+1],
1397 getTypeByID(Record[NextArg])));
1398 if (Args.back() == 0) return Error("Invalid CALL record");
1399 }
1400 }
1401
1402 I = new CallInst(Callee, &Args[0], Args.size());
Chris Lattner76520192007-05-03 22:34:03 +00001403 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1404 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001405 break;
1406 }
1407 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1408 if (Record.size() < 3)
1409 return Error("Invalid VAARG record");
1410 const Type *OpTy = getTypeByID(Record[0]);
1411 Value *Op = getFnValueByID(Record[1], OpTy);
1412 const Type *ResTy = getTypeByID(Record[2]);
1413 if (!OpTy || !Op || !ResTy)
1414 return Error("Invalid VAARG record");
1415 I = new VAArgInst(Op, ResTy);
1416 break;
1417 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001418 }
1419
1420 // Add instruction to end of current BB. If there is no current BB, reject
1421 // this file.
1422 if (CurBB == 0) {
1423 delete I;
1424 return Error("Invalid instruction with no BB");
1425 }
1426 CurBB->getInstList().push_back(I);
1427
1428 // If this was a terminator instruction, move to the next block.
1429 if (isa<TerminatorInst>(I)) {
1430 ++CurBBNo;
1431 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1432 }
1433
1434 // Non-void values get registered in the value table for future use.
1435 if (I && I->getType() != Type::VoidTy)
1436 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001437 }
1438
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001439 // Check the function list for unresolved values.
1440 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1441 if (A->getParent() == 0) {
1442 // We found at least one unresolved value. Nuke them all to avoid leaks.
1443 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1444 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1445 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1446 delete A;
1447 }
1448 }
1449 }
1450 return Error("Never resolved value found in function!");
1451 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001452
1453 // Trim the value list down to the size it was before we parsed this function.
1454 ValueList.shrinkTo(ModuleValueListSize);
1455 std::vector<BasicBlock*>().swap(FunctionBBs);
1456
Chris Lattner48f84872007-05-01 04:59:48 +00001457 return false;
1458}
1459
1460
Chris Lattnerc453f762007-04-29 07:54:31 +00001461//===----------------------------------------------------------------------===//
1462// External interface
1463//===----------------------------------------------------------------------===//
1464
1465/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1466///
1467ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1468 std::string *ErrMsg) {
1469 BitcodeReader *R = new BitcodeReader(Buffer);
1470 if (R->ParseBitcode()) {
1471 if (ErrMsg)
1472 *ErrMsg = R->getErrorString();
1473
1474 // Don't let the BitcodeReader dtor delete 'Buffer'.
1475 R->releaseMemoryBuffer();
1476 delete R;
1477 return 0;
1478 }
1479 return R;
1480}
1481
1482/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1483/// If an error occurs, return null and fill in *ErrMsg if non-null.
1484Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1485 BitcodeReader *R;
1486 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1487 if (!R) return 0;
1488
1489 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1490 // delete it when its dtor is run.
1491 Module *M = R->releaseModule(ErrMsg);
1492
1493 // Don't let the BitcodeReader dtor delete 'Buffer'.
1494 R->releaseMemoryBuffer();
1495 delete R;
1496 return M;
1497}