blob: ca372d663e21026f4ba5b70a3ce5f9198f06e017 [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 Lattner48c85b82007-05-04 03:30:17 +000020#include "llvm/ParameterAttributes.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000021#include "llvm/ADT/SmallString.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000022#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000023#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000024using namespace llvm;
25
Chris Lattnerc453f762007-04-29 07:54:31 +000026BitcodeReader::~BitcodeReader() {
27 delete Buffer;
28}
29
Chris Lattner48c85b82007-05-04 03:30:17 +000030//===----------------------------------------------------------------------===//
31// Helper functions to implement forward reference resolution, etc.
32//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000033
Chris Lattnercaee0dc2007-04-22 06:23:29 +000034/// ConvertToString - Convert a string from a record into an std::string, return
35/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000036template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000037static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000038 StrTy &Result) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +000039 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
40 return true;
41
42 for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
43 Result += (char)Record[Idx+i+1];
44 return false;
45}
46
47static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
48 switch (Val) {
49 default: // Map unknown/new linkages to external
50 case 0: return GlobalValue::ExternalLinkage;
51 case 1: return GlobalValue::WeakLinkage;
52 case 2: return GlobalValue::AppendingLinkage;
53 case 3: return GlobalValue::InternalLinkage;
54 case 4: return GlobalValue::LinkOnceLinkage;
55 case 5: return GlobalValue::DLLImportLinkage;
56 case 6: return GlobalValue::DLLExportLinkage;
57 case 7: return GlobalValue::ExternalWeakLinkage;
58 }
59}
60
61static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
62 switch (Val) {
63 default: // Map unknown visibilities to default.
64 case 0: return GlobalValue::DefaultVisibility;
65 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000066 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000067 }
68}
69
Chris Lattnerf581c3b2007-04-24 07:07:11 +000070static int GetDecodedCastOpcode(unsigned Val) {
71 switch (Val) {
72 default: return -1;
73 case bitc::CAST_TRUNC : return Instruction::Trunc;
74 case bitc::CAST_ZEXT : return Instruction::ZExt;
75 case bitc::CAST_SEXT : return Instruction::SExt;
76 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
77 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
78 case bitc::CAST_UITOFP : return Instruction::UIToFP;
79 case bitc::CAST_SITOFP : return Instruction::SIToFP;
80 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
81 case bitc::CAST_FPEXT : return Instruction::FPExt;
82 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
83 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
84 case bitc::CAST_BITCAST : return Instruction::BitCast;
85 }
86}
87static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
88 switch (Val) {
89 default: return -1;
90 case bitc::BINOP_ADD: return Instruction::Add;
91 case bitc::BINOP_SUB: return Instruction::Sub;
92 case bitc::BINOP_MUL: return Instruction::Mul;
93 case bitc::BINOP_UDIV: return Instruction::UDiv;
94 case bitc::BINOP_SDIV:
95 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
96 case bitc::BINOP_UREM: return Instruction::URem;
97 case bitc::BINOP_SREM:
98 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
99 case bitc::BINOP_SHL: return Instruction::Shl;
100 case bitc::BINOP_LSHR: return Instruction::LShr;
101 case bitc::BINOP_ASHR: return Instruction::AShr;
102 case bitc::BINOP_AND: return Instruction::And;
103 case bitc::BINOP_OR: return Instruction::Or;
104 case bitc::BINOP_XOR: return Instruction::Xor;
105 }
106}
107
108
Chris Lattner522b7b12007-04-24 05:48:56 +0000109namespace {
110 /// @brief A class for maintaining the slot number definition
111 /// as a placeholder for the actual definition for forward constants defs.
112 class ConstantPlaceHolder : public ConstantExpr {
113 ConstantPlaceHolder(); // DO NOT IMPLEMENT
114 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000115 public:
116 Use Op;
117 ConstantPlaceHolder(const Type *Ty)
118 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
119 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000120 }
121 };
122}
123
124Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
125 const Type *Ty) {
126 if (Idx >= size()) {
127 // Insert a bunch of null values.
128 Uses.resize(Idx+1);
129 OperandList = &Uses[0];
130 NumOperands = Idx+1;
131 }
132
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000133 if (Value *V = Uses[Idx]) {
134 assert(Ty == V->getType() && "Type mismatch in constant table!");
135 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000136 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000137
138 // Create and return a placeholder, which will later be RAUW'd.
139 Constant *C = new ConstantPlaceHolder(Ty);
140 Uses[Idx].init(C, this);
141 return C;
142}
143
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000144Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
145 if (Idx >= size()) {
146 // Insert a bunch of null values.
147 Uses.resize(Idx+1);
148 OperandList = &Uses[0];
149 NumOperands = Idx+1;
150 }
151
152 if (Value *V = Uses[Idx]) {
153 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
154 return V;
155 }
156
Chris Lattner01ff65f2007-05-02 05:16:49 +0000157 // No type specified, must be invalid reference.
158 if (Ty == 0) return 0;
159
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000160 // Create and return a placeholder, which will later be RAUW'd.
161 Value *V = new Argument(Ty);
162 Uses[Idx].init(V, this);
163 return V;
164}
165
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000166
167const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
168 // If the TypeID is in range, return it.
169 if (ID < TypeList.size())
170 return TypeList[ID].get();
171 if (!isTypeTable) return 0;
172
173 // The type table allows forward references. Push as many Opaque types as
174 // needed to get up to ID.
175 while (TypeList.size() <= ID)
176 TypeList.push_back(OpaqueType::get());
177 return TypeList.back().get();
178}
179
Chris Lattner48c85b82007-05-04 03:30:17 +0000180//===----------------------------------------------------------------------===//
181// Functions for parsing blocks from the bitcode file
182//===----------------------------------------------------------------------===//
183
184bool BitcodeReader::ParseParamAttrBlock() {
185 if (Stream.EnterSubBlock())
186 return Error("Malformed block record");
187
188 if (!ParamAttrs.empty())
189 return Error("Multiple PARAMATTR blocks found!");
190
191 SmallVector<uint64_t, 64> Record;
192
193 ParamAttrsVector Attrs;
194
195 // Read all the records.
196 while (1) {
197 unsigned Code = Stream.ReadCode();
198 if (Code == bitc::END_BLOCK) {
199 if (Stream.ReadBlockEnd())
200 return Error("Error at end of PARAMATTR block");
201 return false;
202 }
203
204 if (Code == bitc::ENTER_SUBBLOCK) {
205 // No known subblocks, always skip them.
206 Stream.ReadSubBlockID();
207 if (Stream.SkipBlock())
208 return Error("Malformed block record");
209 continue;
210 }
211
212 if (Code == bitc::DEFINE_ABBREV) {
213 Stream.ReadAbbrevRecord();
214 continue;
215 }
216
217 // Read a record.
218 Record.clear();
219 switch (Stream.ReadRecord(Code, Record)) {
220 default: // Default behavior: ignore.
221 break;
222 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
223 if (Record.size() & 1)
224 return Error("Invalid ENTRY record");
225
226 ParamAttrsWithIndex PAWI;
227 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
228 PAWI.index = Record[i];
229 PAWI.attrs = Record[i+1];
230 Attrs.push_back(PAWI);
231 }
232 ParamAttrs.push_back(ParamAttrsList::get(Attrs));
233 Attrs.clear();
234 break;
235 }
236 }
237 }
238}
239
240
Chris Lattner86697142007-05-01 05:01:34 +0000241bool BitcodeReader::ParseTypeTable() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000242 if (Stream.EnterSubBlock())
243 return Error("Malformed block record");
244
245 if (!TypeList.empty())
246 return Error("Multiple TYPE_BLOCKs found!");
247
248 SmallVector<uint64_t, 64> Record;
249 unsigned NumRecords = 0;
250
251 // Read all the records for this type table.
252 while (1) {
253 unsigned Code = Stream.ReadCode();
254 if (Code == bitc::END_BLOCK) {
255 if (NumRecords != TypeList.size())
256 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000257 if (Stream.ReadBlockEnd())
258 return Error("Error at end of type table block");
259 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000260 }
261
262 if (Code == bitc::ENTER_SUBBLOCK) {
263 // No known subblocks, always skip them.
264 Stream.ReadSubBlockID();
265 if (Stream.SkipBlock())
266 return Error("Malformed block record");
267 continue;
268 }
269
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000270 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000271 Stream.ReadAbbrevRecord();
272 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000273 }
274
275 // Read a record.
276 Record.clear();
277 const Type *ResultTy = 0;
278 switch (Stream.ReadRecord(Code, Record)) {
279 default: // Default behavior: unknown type.
280 ResultTy = 0;
281 break;
282 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
283 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
284 // type list. This allows us to reserve space.
285 if (Record.size() < 1)
286 return Error("Invalid TYPE_CODE_NUMENTRY record");
287 TypeList.reserve(Record[0]);
288 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000289 case bitc::TYPE_CODE_VOID: // VOID
290 ResultTy = Type::VoidTy;
291 break;
292 case bitc::TYPE_CODE_FLOAT: // FLOAT
293 ResultTy = Type::FloatTy;
294 break;
295 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
296 ResultTy = Type::DoubleTy;
297 break;
298 case bitc::TYPE_CODE_LABEL: // LABEL
299 ResultTy = Type::LabelTy;
300 break;
301 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
302 ResultTy = 0;
303 break;
304 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
305 if (Record.size() < 1)
306 return Error("Invalid Integer type record");
307
308 ResultTy = IntegerType::get(Record[0]);
309 break;
310 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
311 if (Record.size() < 1)
312 return Error("Invalid POINTER type record");
313 ResultTy = PointerType::get(getTypeByID(Record[0], true));
314 break;
315 case bitc::TYPE_CODE_FUNCTION: {
316 // FUNCTION: [vararg, retty, #pararms, paramty N]
317 if (Record.size() < 3 || Record.size() < Record[2]+3)
318 return Error("Invalid FUNCTION type record");
319 std::vector<const Type*> ArgTys;
320 for (unsigned i = 0, e = Record[2]; i != e; ++i)
321 ArgTys.push_back(getTypeByID(Record[3+i], true));
322
323 // FIXME: PARAM TYS.
324 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
325 Record[0]);
326 break;
327 }
328 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
329 if (Record.size() < 2 || Record.size() < Record[1]+2)
330 return Error("Invalid STRUCT type record");
331 std::vector<const Type*> EltTys;
332 for (unsigned i = 0, e = Record[1]; i != e; ++i)
333 EltTys.push_back(getTypeByID(Record[2+i], true));
334 ResultTy = StructType::get(EltTys, Record[0]);
335 break;
336 }
337 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
338 if (Record.size() < 2)
339 return Error("Invalid ARRAY type record");
340 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
341 break;
342 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
343 if (Record.size() < 2)
344 return Error("Invalid VECTOR type record");
345 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
346 break;
347 }
348
349 if (NumRecords == TypeList.size()) {
350 // If this is a new type slot, just append it.
351 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
352 ++NumRecords;
353 } else if (ResultTy == 0) {
354 // Otherwise, this was forward referenced, so an opaque type was created,
355 // but the result type is actually just an opaque. Leave the one we
356 // created previously.
357 ++NumRecords;
358 } else {
359 // Otherwise, this was forward referenced, so an opaque type was created.
360 // Resolve the opaque type to the real type now.
361 assert(NumRecords < TypeList.size() && "Typelist imbalance");
362 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
363
364 // Don't directly push the new type on the Tab. Instead we want to replace
365 // the opaque type we previously inserted with the new concrete value. The
366 // refinement from the abstract (opaque) type to the new type causes all
367 // uses of the abstract type to use the concrete type (NewTy). This will
368 // also cause the opaque type to be deleted.
369 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
370
371 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000372 // value table... or with a preexisting type that was already in the
373 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000374 assert(TypeList[NumRecords-1].get() != OldTy &&
375 "refineAbstractType didn't work!");
376 }
377 }
378}
379
380
Chris Lattner86697142007-05-01 05:01:34 +0000381bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000382 if (Stream.EnterSubBlock())
383 return Error("Malformed block record");
384
385 SmallVector<uint64_t, 64> Record;
386
387 // Read all the records for this type table.
388 std::string TypeName;
389 while (1) {
390 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000391 if (Code == bitc::END_BLOCK) {
392 if (Stream.ReadBlockEnd())
393 return Error("Error at end of type symbol table block");
394 return false;
395 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000396
397 if (Code == bitc::ENTER_SUBBLOCK) {
398 // No known subblocks, always skip them.
399 Stream.ReadSubBlockID();
400 if (Stream.SkipBlock())
401 return Error("Malformed block record");
402 continue;
403 }
404
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000405 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000406 Stream.ReadAbbrevRecord();
407 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000408 }
409
410 // Read a record.
411 Record.clear();
412 switch (Stream.ReadRecord(Code, Record)) {
413 default: // Default behavior: unknown type.
414 break;
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000415 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000416 if (ConvertToString(Record, 1, TypeName))
417 return Error("Invalid TST_ENTRY record");
418 unsigned TypeID = Record[0];
419 if (TypeID >= TypeList.size())
420 return Error("Invalid Type ID in TST_ENTRY record");
421
422 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
423 TypeName.clear();
424 break;
425 }
426 }
427}
428
Chris Lattner86697142007-05-01 05:01:34 +0000429bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000430 if (Stream.EnterSubBlock())
431 return Error("Malformed block record");
432
433 SmallVector<uint64_t, 64> Record;
434
435 // Read all the records for this value table.
436 SmallString<128> ValueName;
437 while (1) {
438 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000439 if (Code == bitc::END_BLOCK) {
440 if (Stream.ReadBlockEnd())
441 return Error("Error at end of value symbol table block");
442 return false;
443 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000444 if (Code == bitc::ENTER_SUBBLOCK) {
445 // No known subblocks, always skip them.
446 Stream.ReadSubBlockID();
447 if (Stream.SkipBlock())
448 return Error("Malformed block record");
449 continue;
450 }
451
452 if (Code == bitc::DEFINE_ABBREV) {
453 Stream.ReadAbbrevRecord();
454 continue;
455 }
456
457 // Read a record.
458 Record.clear();
459 switch (Stream.ReadRecord(Code, Record)) {
460 default: // Default behavior: unknown type.
461 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000462 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namelen, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000463 if (ConvertToString(Record, 1, ValueName))
464 return Error("Invalid TST_ENTRY record");
465 unsigned ValueID = Record[0];
466 if (ValueID >= ValueList.size())
467 return Error("Invalid Value ID in VST_ENTRY record");
468 Value *V = ValueList[ValueID];
469
470 V->setName(&ValueName[0], ValueName.size());
471 ValueName.clear();
472 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000473 }
474 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000475 if (ConvertToString(Record, 1, ValueName))
476 return Error("Invalid VST_BBENTRY record");
477 BasicBlock *BB = getBasicBlock(Record[0]);
478 if (BB == 0)
479 return Error("Invalid BB ID in VST_BBENTRY record");
480
481 BB->setName(&ValueName[0], ValueName.size());
482 ValueName.clear();
483 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000484 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000485 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000486 }
487}
488
Chris Lattner0eef0802007-04-24 04:04:35 +0000489/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
490/// the LSB for dense VBR encoding.
491static uint64_t DecodeSignRotatedValue(uint64_t V) {
492 if ((V & 1) == 0)
493 return V >> 1;
494 if (V != 1)
495 return -(V >> 1);
496 // There is no such thing as -0 with integers. "-0" really means MININT.
497 return 1ULL << 63;
498}
499
Chris Lattner07d98b42007-04-26 02:46:40 +0000500/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
501/// values and aliases that we can.
502bool BitcodeReader::ResolveGlobalAndAliasInits() {
503 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
504 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
505
506 GlobalInitWorklist.swap(GlobalInits);
507 AliasInitWorklist.swap(AliasInits);
508
509 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000510 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000511 if (ValID >= ValueList.size()) {
512 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000513 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000514 } else {
515 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
516 GlobalInitWorklist.back().first->setInitializer(C);
517 else
518 return Error("Global variable initializer is not a constant!");
519 }
520 GlobalInitWorklist.pop_back();
521 }
522
523 while (!AliasInitWorklist.empty()) {
524 unsigned ValID = AliasInitWorklist.back().second;
525 if (ValID >= ValueList.size()) {
526 AliasInits.push_back(AliasInitWorklist.back());
527 } else {
528 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000529 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000530 else
531 return Error("Alias initializer is not a constant!");
532 }
533 AliasInitWorklist.pop_back();
534 }
535 return false;
536}
537
538
Chris Lattner86697142007-05-01 05:01:34 +0000539bool BitcodeReader::ParseConstants() {
Chris Lattnere16504e2007-04-24 03:30:34 +0000540 if (Stream.EnterSubBlock())
541 return Error("Malformed block record");
542
543 SmallVector<uint64_t, 64> Record;
544
545 // Read all the records for this value table.
546 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000547 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000548 while (1) {
549 unsigned Code = Stream.ReadCode();
550 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000551 if (NextCstNo != ValueList.size())
552 return Error("Invalid constant reference!");
553
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000554 if (Stream.ReadBlockEnd())
555 return Error("Error at end of constants block");
556 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000557 }
558
559 if (Code == bitc::ENTER_SUBBLOCK) {
560 // No known subblocks, always skip them.
561 Stream.ReadSubBlockID();
562 if (Stream.SkipBlock())
563 return Error("Malformed block record");
564 continue;
565 }
566
567 if (Code == bitc::DEFINE_ABBREV) {
568 Stream.ReadAbbrevRecord();
569 continue;
570 }
571
572 // Read a record.
573 Record.clear();
574 Value *V = 0;
575 switch (Stream.ReadRecord(Code, Record)) {
576 default: // Default behavior: unknown constant
577 case bitc::CST_CODE_UNDEF: // UNDEF
578 V = UndefValue::get(CurTy);
579 break;
580 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
581 if (Record.empty())
582 return Error("Malformed CST_SETTYPE record");
583 if (Record[0] >= TypeList.size())
584 return Error("Invalid Type ID in CST_SETTYPE record");
585 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000586 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000587 case bitc::CST_CODE_NULL: // NULL
588 V = Constant::getNullValue(CurTy);
589 break;
590 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000591 if (!isa<IntegerType>(CurTy) || Record.empty())
592 return Error("Invalid CST_INTEGER record");
593 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
594 break;
595 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
596 if (!isa<IntegerType>(CurTy) || Record.empty() ||
597 Record.size() < Record[0]+1)
598 return Error("Invalid WIDE_INTEGER record");
599
600 unsigned NumWords = Record[0];
Chris Lattner084a8442007-04-24 17:22:05 +0000601 SmallVector<uint64_t, 8> Words;
602 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000603 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner084a8442007-04-24 17:22:05 +0000604 Words[i] = DecodeSignRotatedValue(Record[i+1]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000605 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000606 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000607 break;
608 }
609 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
610 if (Record.empty())
611 return Error("Invalid FLOAT record");
612 if (CurTy == Type::FloatTy)
613 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
614 else if (CurTy == Type::DoubleTy)
615 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
Chris Lattnere16504e2007-04-24 03:30:34 +0000616 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000617 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000618 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000619
620 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
621 if (Record.empty() || Record.size() < Record[0]+1)
622 return Error("Invalid CST_AGGREGATE record");
623
624 unsigned Size = Record[0];
625 std::vector<Constant*> Elts;
626
627 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
628 for (unsigned i = 0; i != Size; ++i)
629 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
630 STy->getElementType(i)));
631 V = ConstantStruct::get(STy, Elts);
632 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
633 const Type *EltTy = ATy->getElementType();
634 for (unsigned i = 0; i != Size; ++i)
635 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
636 V = ConstantArray::get(ATy, Elts);
637 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
638 const Type *EltTy = VTy->getElementType();
639 for (unsigned i = 0; i != Size; ++i)
640 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
641 V = ConstantVector::get(Elts);
642 } else {
643 V = UndefValue::get(CurTy);
644 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000645 break;
646 }
647
648 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
649 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
650 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000651 if (Opc < 0) {
652 V = UndefValue::get(CurTy); // Unknown binop.
653 } else {
654 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
655 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
656 V = ConstantExpr::get(Opc, LHS, RHS);
657 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000658 break;
659 }
660 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
661 if (Record.size() < 3) return Error("Invalid CE_CAST record");
662 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000663 if (Opc < 0) {
664 V = UndefValue::get(CurTy); // Unknown cast.
665 } else {
666 const Type *OpTy = getTypeByID(Record[1]);
667 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
668 V = ConstantExpr::getCast(Opc, Op, CurTy);
669 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000670 break;
671 }
672 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
673 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
674 SmallVector<Constant*, 16> Elts;
675 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
676 const Type *ElTy = getTypeByID(Record[i]);
677 if (!ElTy) return Error("Invalid CE_GEP record");
678 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
679 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000680 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
681 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000682 }
683 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
684 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
685 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
686 Type::Int1Ty),
687 ValueList.getConstantFwdRef(Record[1],CurTy),
688 ValueList.getConstantFwdRef(Record[2],CurTy));
689 break;
690 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
691 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
692 const VectorType *OpTy =
693 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
694 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
695 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
696 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
697 OpTy->getElementType());
698 V = ConstantExpr::getExtractElement(Op0, Op1);
699 break;
700 }
701 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
702 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
703 if (Record.size() < 3 || OpTy == 0)
704 return Error("Invalid CE_INSERTELT record");
705 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
706 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
707 OpTy->getElementType());
708 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
709 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
710 break;
711 }
712 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
713 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
714 if (Record.size() < 3 || OpTy == 0)
715 return Error("Invalid CE_INSERTELT record");
716 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
717 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
718 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
719 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
720 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
721 break;
722 }
723 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
724 if (Record.size() < 4) return Error("Invalid CE_CMP record");
725 const Type *OpTy = getTypeByID(Record[0]);
726 if (OpTy == 0) return Error("Invalid CE_CMP record");
727 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
728 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
729
730 if (OpTy->isFloatingPoint())
731 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
732 else
733 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
734 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000735 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000736 }
737
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000738 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000739 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000740 }
741}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000742
Chris Lattner980e5aa2007-05-01 05:52:21 +0000743/// RememberAndSkipFunctionBody - When we see the block for a function body,
744/// remember where it is and then skip it. This lets us lazily deserialize the
745/// functions.
746bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000747 // Get the function we are talking about.
748 if (FunctionsWithBodies.empty())
749 return Error("Insufficient function protos");
750
751 Function *Fn = FunctionsWithBodies.back();
752 FunctionsWithBodies.pop_back();
753
754 // Save the current stream state.
755 uint64_t CurBit = Stream.GetCurrentBitNo();
756 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
757
758 // Set the functions linkage to GhostLinkage so we know it is lazily
759 // deserialized.
760 Fn->setLinkage(GlobalValue::GhostLinkage);
761
762 // Skip over the function block for now.
763 if (Stream.SkipBlock())
764 return Error("Malformed block record");
765 return false;
766}
767
Chris Lattner86697142007-05-01 05:01:34 +0000768bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000769 // Reject multiple MODULE_BLOCK's in a single bitstream.
770 if (TheModule)
771 return Error("Multiple MODULE_BLOCKs in same stream");
772
773 if (Stream.EnterSubBlock())
774 return Error("Malformed block record");
775
776 // Otherwise, create the module.
777 TheModule = new Module(ModuleID);
778
779 SmallVector<uint64_t, 64> Record;
780 std::vector<std::string> SectionTable;
781
782 // Read all the records for this module.
783 while (!Stream.AtEndOfStream()) {
784 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000785 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000786 if (Stream.ReadBlockEnd())
787 return Error("Error at end of module block");
788
789 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000790 ResolveGlobalAndAliasInits();
791 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000792 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000793 if (!FunctionsWithBodies.empty())
794 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000795
796 // Force deallocation of memory for these vectors to favor the client that
797 // want lazy deserialization.
798 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
799 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
800 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000801 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000802 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000803
804 if (Code == bitc::ENTER_SUBBLOCK) {
805 switch (Stream.ReadSubBlockID()) {
806 default: // Skip unknown content.
807 if (Stream.SkipBlock())
808 return Error("Malformed block record");
809 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000810 case bitc::PARAMATTR_BLOCK_ID:
811 if (ParseParamAttrBlock())
812 return true;
813 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000814 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000815 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000816 return true;
817 break;
818 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000819 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000820 return true;
821 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000822 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000823 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000824 return true;
825 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000826 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000827 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000828 return true;
829 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000830 case bitc::FUNCTION_BLOCK_ID:
831 // If this is the first function body we've seen, reverse the
832 // FunctionsWithBodies list.
833 if (!HasReversedFunctionsWithBodies) {
834 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
835 HasReversedFunctionsWithBodies = true;
836 }
837
Chris Lattner980e5aa2007-05-01 05:52:21 +0000838 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000839 return true;
840 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000841 }
842 continue;
843 }
844
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000845 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000846 Stream.ReadAbbrevRecord();
847 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000848 }
849
850 // Read a record.
851 switch (Stream.ReadRecord(Code, Record)) {
852 default: break; // Default behavior, ignore unknown content.
853 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
854 if (Record.size() < 1)
855 return Error("Malformed MODULE_CODE_VERSION");
856 // Only version #0 is supported so far.
857 if (Record[0] != 0)
858 return Error("Unknown bitstream version!");
859 break;
860 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
861 std::string S;
862 if (ConvertToString(Record, 0, S))
863 return Error("Invalid MODULE_CODE_TRIPLE record");
864 TheModule->setTargetTriple(S);
865 break;
866 }
867 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
868 std::string S;
869 if (ConvertToString(Record, 0, S))
870 return Error("Invalid MODULE_CODE_DATALAYOUT record");
871 TheModule->setDataLayout(S);
872 break;
873 }
874 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
875 std::string S;
876 if (ConvertToString(Record, 0, S))
877 return Error("Invalid MODULE_CODE_ASM record");
878 TheModule->setModuleInlineAsm(S);
879 break;
880 }
881 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
882 std::string S;
883 if (ConvertToString(Record, 0, S))
884 return Error("Invalid MODULE_CODE_DEPLIB record");
885 TheModule->addLibrary(S);
886 break;
887 }
888 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
889 std::string S;
890 if (ConvertToString(Record, 0, S))
891 return Error("Invalid MODULE_CODE_SECTIONNAME record");
892 SectionTable.push_back(S);
893 break;
894 }
895 // GLOBALVAR: [type, isconst, initid,
896 // linkage, alignment, section, visibility, threadlocal]
897 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000898 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000899 return Error("Invalid MODULE_CODE_GLOBALVAR record");
900 const Type *Ty = getTypeByID(Record[0]);
901 if (!isa<PointerType>(Ty))
902 return Error("Global not a pointer type!");
903 Ty = cast<PointerType>(Ty)->getElementType();
904
905 bool isConstant = Record[1];
906 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
907 unsigned Alignment = (1 << Record[4]) >> 1;
908 std::string Section;
909 if (Record[5]) {
910 if (Record[5]-1 >= SectionTable.size())
911 return Error("Invalid section ID");
912 Section = SectionTable[Record[5]-1];
913 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000914 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
915 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
916 bool isThreadLocal = false;
917 if (Record.size() >= 7) isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000918
919 GlobalVariable *NewGV =
920 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
921 NewGV->setAlignment(Alignment);
922 if (!Section.empty())
923 NewGV->setSection(Section);
924 NewGV->setVisibility(Visibility);
925 NewGV->setThreadLocal(isThreadLocal);
926
Chris Lattner0b2482a2007-04-23 21:26:05 +0000927 ValueList.push_back(NewGV);
928
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000929 // Remember which value to use for the global initializer.
930 if (unsigned InitID = Record[2])
931 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000932 break;
933 }
934 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
935 // visibility]
936 case bitc::MODULE_CODE_FUNCTION: {
937 if (Record.size() < 7)
938 return Error("Invalid MODULE_CODE_FUNCTION record");
939 const Type *Ty = getTypeByID(Record[0]);
940 if (!isa<PointerType>(Ty))
941 return Error("Function not a pointer type!");
942 const FunctionType *FTy =
943 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
944 if (!FTy)
945 return Error("Function not a pointer to function type!");
946
947 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
948 "", TheModule);
949
950 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +0000951 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000952 Func->setLinkage(GetDecodedLinkage(Record[3]));
953 Func->setAlignment((1 << Record[4]) >> 1);
954 if (Record[5]) {
955 if (Record[5]-1 >= SectionTable.size())
956 return Error("Invalid section ID");
957 Func->setSection(SectionTable[Record[5]-1]);
958 }
959 Func->setVisibility(GetDecodedVisibility(Record[6]));
960
Chris Lattner0b2482a2007-04-23 21:26:05 +0000961 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +0000962
963 // If this is a function with a body, remember the prototype we are
964 // creating now, so that we can match up the body with them later.
965 if (!isProto)
966 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000967 break;
968 }
Chris Lattner07d98b42007-04-26 02:46:40 +0000969 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +0000970 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +0000971 if (Record.size() < 3)
972 return Error("Invalid MODULE_ALIAS record");
973 const Type *Ty = getTypeByID(Record[0]);
974 if (!isa<PointerType>(Ty))
975 return Error("Function not a pointer type!");
976
977 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
978 "", 0, TheModule);
979 ValueList.push_back(NewGA);
980 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
981 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000982 }
Chris Lattner198f34a2007-04-26 03:27:58 +0000983 /// MODULE_CODE_PURGEVALS: [numvals]
984 case bitc::MODULE_CODE_PURGEVALS:
985 // Trim down the value list to the specified size.
986 if (Record.size() < 1 || Record[0] > ValueList.size())
987 return Error("Invalid MODULE_PURGEVALS record");
988 ValueList.shrinkTo(Record[0]);
989 break;
990 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000991 Record.clear();
992 }
993
994 return Error("Premature end of bitstream");
995}
996
997
Chris Lattnerc453f762007-04-29 07:54:31 +0000998bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000999 TheModule = 0;
1000
Chris Lattnerc453f762007-04-29 07:54:31 +00001001 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001002 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1003
Chris Lattnerc453f762007-04-29 07:54:31 +00001004 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001005 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001006
1007 // Sniff for the signature.
1008 if (Stream.Read(8) != 'B' ||
1009 Stream.Read(8) != 'C' ||
1010 Stream.Read(4) != 0x0 ||
1011 Stream.Read(4) != 0xC ||
1012 Stream.Read(4) != 0xE ||
1013 Stream.Read(4) != 0xD)
1014 return Error("Invalid bitcode signature");
1015
1016 // We expect a number of well-defined blocks, though we don't necessarily
1017 // need to understand them all.
1018 while (!Stream.AtEndOfStream()) {
1019 unsigned Code = Stream.ReadCode();
1020
1021 if (Code != bitc::ENTER_SUBBLOCK)
1022 return Error("Invalid record at top-level");
1023
1024 unsigned BlockID = Stream.ReadSubBlockID();
1025
1026 // We only know the MODULE subblock ID.
1027 if (BlockID == bitc::MODULE_BLOCK_ID) {
Chris Lattner86697142007-05-01 05:01:34 +00001028 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001029 return true;
1030 } else if (Stream.SkipBlock()) {
1031 return Error("Malformed block record");
1032 }
1033 }
1034
1035 return false;
1036}
Chris Lattnerc453f762007-04-29 07:54:31 +00001037
Chris Lattner48f84872007-05-01 04:59:48 +00001038
1039bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1040 // If it already is material, ignore the request.
1041 if (!F->hasNotBeenReadFromBytecode()) return false;
1042
1043 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1044 DeferredFunctionInfo.find(F);
1045 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1046
1047 // Move the bit stream to the saved position of the deferred function body and
1048 // restore the real linkage type for the function.
1049 Stream.JumpToBit(DFII->second.first);
1050 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1051 DeferredFunctionInfo.erase(DFII);
1052
Chris Lattner980e5aa2007-05-01 05:52:21 +00001053 if (ParseFunctionBody(F)) {
1054 if (ErrInfo) *ErrInfo = ErrorString;
1055 return true;
1056 }
1057
1058 return false;
1059}
1060
1061Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1062 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1063 DeferredFunctionInfo.begin();
1064 while (!DeferredFunctionInfo.empty()) {
1065 Function *F = (*I++).first;
1066 assert(F->hasNotBeenReadFromBytecode() &&
1067 "Deserialized function found in map!");
1068 if (materializeFunction(F, ErrInfo))
1069 return 0;
1070 }
1071 return TheModule;
1072}
1073
1074
1075/// ParseFunctionBody - Lazily parse the specified function body block.
1076bool BitcodeReader::ParseFunctionBody(Function *F) {
1077 if (Stream.EnterSubBlock())
1078 return Error("Malformed block record");
1079
1080 unsigned ModuleValueListSize = ValueList.size();
1081
1082 // Add all the function arguments to the value table.
1083 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1084 ValueList.push_back(I);
1085
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001086 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001087 BasicBlock *CurBB = 0;
1088 unsigned CurBBNo = 0;
1089
Chris Lattner980e5aa2007-05-01 05:52:21 +00001090 // Read all the records.
1091 SmallVector<uint64_t, 64> Record;
1092 while (1) {
1093 unsigned Code = Stream.ReadCode();
1094 if (Code == bitc::END_BLOCK) {
1095 if (Stream.ReadBlockEnd())
1096 return Error("Error at end of function block");
1097 break;
1098 }
1099
1100 if (Code == bitc::ENTER_SUBBLOCK) {
1101 switch (Stream.ReadSubBlockID()) {
1102 default: // Skip unknown content.
1103 if (Stream.SkipBlock())
1104 return Error("Malformed block record");
1105 break;
1106 case bitc::CONSTANTS_BLOCK_ID:
1107 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001108 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001109 break;
1110 case bitc::VALUE_SYMTAB_BLOCK_ID:
1111 if (ParseValueSymbolTable()) return true;
1112 break;
1113 }
1114 continue;
1115 }
1116
1117 if (Code == bitc::DEFINE_ABBREV) {
1118 Stream.ReadAbbrevRecord();
1119 continue;
1120 }
1121
1122 // Read a record.
1123 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001124 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001125 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001126 default: // Default behavior: reject
1127 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001128 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001129 if (Record.size() < 1 || Record[0] == 0)
1130 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001131 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001132 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001133 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1134 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001135 CurBB = FunctionBBs[0];
1136 continue;
1137
Chris Lattner231cbcb2007-05-02 04:27:25 +00001138 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001139 if (Record.size() < 4) return Error("Invalid BINOP record");
1140 const Type *Ty = getTypeByID(Record[1]);
1141 int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1142 Value *LHS = getFnValueByID(Record[2], Ty);
1143 Value *RHS = getFnValueByID(Record[3], Ty);
1144 if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1145 return Error("Invalid BINOP record");
1146 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001147 break;
1148 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001149 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
1150 if (Record.size() < 4) return Error("Invalid CAST record");
1151 int Opc = GetDecodedCastOpcode(Record[0]);
1152 const Type *ResTy = getTypeByID(Record[1]);
1153 const Type *OpTy = getTypeByID(Record[2]);
1154 Value *Op = getFnValueByID(Record[3], OpTy);
1155 if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1156 return Error("Invalid CAST record");
1157 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1158 break;
1159 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001160 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n, n x operands]
1161 if (Record.size() < 2 || (Record.size() & 1))
1162 return Error("Invalid GEP record");
1163 const Type *OpTy = getTypeByID(Record[0]);
1164 Value *Op = getFnValueByID(Record[1], OpTy);
1165 if (OpTy == 0 || Op == 0)
1166 return Error("Invalid GEP record");
1167
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001168 SmallVector<Value*, 16> GEPIdx;
Chris Lattner01ff65f2007-05-02 05:16:49 +00001169 for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
1170 const Type *IdxTy = getTypeByID(Record[i*2]);
1171 Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
1172 if (IdxTy == 0 || Idx == 0)
1173 return Error("Invalid GEP record");
1174 GEPIdx.push_back(Idx);
1175 }
1176
1177 I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
1178 break;
1179 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001180
Chris Lattner01ff65f2007-05-02 05:16:49 +00001181 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
1182 if (Record.size() < 4) return Error("Invalid SELECT record");
1183 const Type *Ty = getTypeByID(Record[0]);
1184 Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
1185 Value *LHS = getFnValueByID(Record[2], Ty);
1186 Value *RHS = getFnValueByID(Record[3], Ty);
1187 if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
1188 return Error("Invalid SELECT record");
1189 I = new SelectInst(Cond, LHS, RHS);
1190 break;
1191 }
1192
1193 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1194 if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
1195 const Type *OpTy = getTypeByID(Record[0]);
1196 Value *Vec = getFnValueByID(Record[1], OpTy);
1197 Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
1198 if (OpTy == 0 || Vec == 0 || Idx == 0)
1199 return Error("Invalid EXTRACTELT record");
1200 I = new ExtractElementInst(Vec, Idx);
1201 break;
1202 }
1203
1204 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1205 if (Record.size() < 4) return Error("Invalid INSERTELT record");
1206 const VectorType *OpTy =
1207 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1208 if (OpTy == 0) return Error("Invalid INSERTELT record");
1209 Value *Vec = getFnValueByID(Record[1], OpTy);
1210 Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
1211 Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
1212 if (Vec == 0 || Elt == 0 || Idx == 0)
1213 return Error("Invalid INSERTELT record");
1214 I = new InsertElementInst(Vec, Elt, Idx);
1215 break;
1216 }
1217
1218 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
1219 if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
1220 const VectorType *OpTy =
1221 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1222 if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
1223 Value *Vec1 = getFnValueByID(Record[1], OpTy);
1224 Value *Vec2 = getFnValueByID(Record[2], OpTy);
1225 Value *Mask = getFnValueByID(Record[3],
1226 VectorType::get(Type::Int32Ty,
1227 OpTy->getNumElements()));
1228 if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
1229 return Error("Invalid SHUFFLEVEC record");
1230 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1231 break;
1232 }
1233
1234 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1235 if (Record.size() < 4) return Error("Invalid CMP record");
1236 const Type *OpTy = getTypeByID(Record[0]);
1237 Value *LHS = getFnValueByID(Record[1], OpTy);
1238 Value *RHS = getFnValueByID(Record[2], OpTy);
1239 if (OpTy == 0 || LHS == 0 || RHS == 0)
1240 return Error("Invalid CMP record");
1241 if (OpTy->isFPOrFPVector())
1242 I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
1243 else
1244 I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
1245 break;
1246 }
1247
Chris Lattner231cbcb2007-05-02 04:27:25 +00001248 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1249 if (Record.size() == 0) {
1250 I = new ReturnInst();
1251 break;
1252 }
1253 if (Record.size() == 2) {
1254 const Type *OpTy = getTypeByID(Record[0]);
1255 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001256 if (!OpTy || !Op)
1257 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001258 I = new ReturnInst(Op);
1259 break;
1260 }
1261 return Error("Invalid RET record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001262 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001263 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001264 return Error("Invalid BR record");
1265 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1266 if (TrueDest == 0)
1267 return Error("Invalid BR record");
1268
1269 if (Record.size() == 1)
1270 I = new BranchInst(TrueDest);
1271 else {
1272 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1273 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1274 if (FalseDest == 0 || Cond == 0)
1275 return Error("Invalid BR record");
1276 I = new BranchInst(TrueDest, FalseDest, Cond);
1277 }
1278 break;
1279 }
1280 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1281 if (Record.size() < 3 || (Record.size() & 1) == 0)
1282 return Error("Invalid SWITCH record");
1283 const Type *OpTy = getTypeByID(Record[0]);
1284 Value *Cond = getFnValueByID(Record[1], OpTy);
1285 BasicBlock *Default = getBasicBlock(Record[2]);
1286 if (OpTy == 0 || Cond == 0 || Default == 0)
1287 return Error("Invalid SWITCH record");
1288 unsigned NumCases = (Record.size()-3)/2;
1289 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1290 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1291 ConstantInt *CaseVal =
1292 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1293 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1294 if (CaseVal == 0 || DestBB == 0) {
1295 delete SI;
1296 return Error("Invalid SWITCH record!");
1297 }
1298 SI->addCase(CaseVal, DestBB);
1299 }
1300 I = SI;
1301 break;
1302 }
1303
Chris Lattner76520192007-05-03 22:34:03 +00001304 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1305 if (Record.size() < 5)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001306 return Error("Invalid INVOKE record");
Chris Lattner76520192007-05-03 22:34:03 +00001307 unsigned CCInfo = Record[0];
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001308 const PointerType *CalleeTy =
Chris Lattner76520192007-05-03 22:34:03 +00001309 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
1310 Value *Callee = getFnValueByID(Record[2], CalleeTy);
1311 BasicBlock *NormalBB = getBasicBlock(Record[3]);
1312 BasicBlock *UnwindBB = getBasicBlock(Record[4]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001313 if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
1314 return Error("Invalid INVOKE record");
1315
1316 const FunctionType *FTy =
1317 dyn_cast<FunctionType>(CalleeTy->getElementType());
1318
1319 // Check that the right number of fixed parameters are here.
Chris Lattner76520192007-05-03 22:34:03 +00001320 if (FTy == 0 || Record.size() < 5+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001321 return Error("Invalid INVOKE record");
1322
1323 SmallVector<Value*, 16> Ops;
1324 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
Chris Lattner76520192007-05-03 22:34:03 +00001325 Ops.push_back(getFnValueByID(Record[5+i], FTy->getParamType(i)));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001326 if (Ops.back() == 0)
1327 return Error("Invalid INVOKE record");
1328 }
1329
Chris Lattner76520192007-05-03 22:34:03 +00001330 unsigned FirstVarargParam = 5+FTy->getNumParams();
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001331 if (FTy->isVarArg()) {
1332 // Read type/value pairs for varargs params.
1333 if ((Record.size()-FirstVarargParam) & 1)
1334 return Error("Invalid INVOKE record");
1335
1336 for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
1337 const Type *ArgTy = getTypeByID(Record[i]);
1338 Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
1339 if (Ops.back() == 0 || ArgTy == 0)
1340 return Error("Invalid INVOKE record");
1341 }
1342 } else {
1343 if (Record.size() != FirstVarargParam)
1344 return Error("Invalid INVOKE record");
1345 }
1346
1347 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
Chris Lattner76520192007-05-03 22:34:03 +00001348 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001349 break;
1350 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001351 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1352 I = new UnwindInst();
1353 break;
1354 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1355 I = new UnreachableInst();
1356 break;
Chris Lattner2a98cca2007-05-03 18:58:09 +00001357 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
1358 if (Record.size() < 2 || Record.size() < 2+Record[1] || (Record[1]&1))
1359 return Error("Invalid PHI record");
1360 const Type *Ty = getTypeByID(Record[0]);
1361 if (!Ty) return Error("Invalid PHI record");
1362
1363 PHINode *PN = new PHINode(Ty);
1364 PN->reserveOperandSpace(Record[1]);
1365
1366 for (unsigned i = 0, e = Record[1]; i != e; i += 2) {
1367 Value *V = getFnValueByID(Record[2+i], Ty);
1368 BasicBlock *BB = getBasicBlock(Record[3+i]);
1369 if (!V || !BB) return Error("Invalid PHI record");
1370 PN->addIncoming(V, BB);
1371 }
1372 I = PN;
1373 break;
1374 }
1375
1376 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1377 if (Record.size() < 3)
1378 return Error("Invalid MALLOC record");
1379 const PointerType *Ty =
1380 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1381 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1382 unsigned Align = Record[2];
1383 if (!Ty || !Size) return Error("Invalid MALLOC record");
1384 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1385 break;
1386 }
1387 case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
1388 if (Record.size() < 2)
1389 return Error("Invalid FREE record");
1390 const Type *OpTy = getTypeByID(Record[0]);
1391 Value *Op = getFnValueByID(Record[1], OpTy);
1392 if (!OpTy || !Op)
1393 return Error("Invalid FREE record");
1394 I = new FreeInst(Op);
1395 break;
1396 }
1397 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1398 if (Record.size() < 3)
1399 return Error("Invalid ALLOCA record");
1400 const PointerType *Ty =
1401 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1402 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1403 unsigned Align = Record[2];
1404 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1405 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1406 break;
1407 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001408 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1409 if (Record.size() < 4)
1410 return Error("Invalid LOAD record");
1411 const Type *OpTy = getTypeByID(Record[0]);
1412 Value *Op = getFnValueByID(Record[1], OpTy);
1413 if (!OpTy || !Op)
1414 return Error("Invalid LOAD record");
1415 I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001416 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001417 }
1418 case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
1419 if (Record.size() < 5)
1420 return Error("Invalid LOAD record");
Chris Lattnerc9c55a92007-05-03 22:21:59 +00001421 const PointerType *OpTy =
1422 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1423 Value *Op = getFnValueByID(Record[1], OpTy ? OpTy->getElementType() : 0);
1424 Value *Ptr = getFnValueByID(Record[2], OpTy);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001425 if (!OpTy || !Op || !Ptr)
1426 return Error("Invalid STORE record");
1427 I = new StoreInst(Op, Ptr, (1 << Record[3]) >> 1, Record[4]);
1428 break;
1429 }
Chris Lattner76520192007-05-03 22:34:03 +00001430 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1431 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001432 return Error("Invalid CALL record");
Chris Lattner76520192007-05-03 22:34:03 +00001433 unsigned CCInfo = Record[0];
Chris Lattner0579f7f2007-05-03 22:04:19 +00001434 const PointerType *OpTy =
Chris Lattner76520192007-05-03 22:34:03 +00001435 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001436 const FunctionType *FTy = 0;
1437 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner76520192007-05-03 22:34:03 +00001438 Value *Callee = getFnValueByID(Record[2], OpTy);
1439 if (!FTy || !Callee || Record.size() < FTy->getNumParams()+3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001440 return Error("Invalid CALL record");
1441
1442 SmallVector<Value*, 16> Args;
1443 // Read the fixed params.
1444 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
Chris Lattner76520192007-05-03 22:34:03 +00001445 Args.push_back(getFnValueByID(Record[i+3], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001446 if (Args.back() == 0) return Error("Invalid CALL record");
1447 }
1448
1449
1450 // Read type/value pairs for varargs params.
Chris Lattner76520192007-05-03 22:34:03 +00001451 unsigned NextArg = FTy->getNumParams()+3;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001452 if (!FTy->isVarArg()) {
1453 if (NextArg != Record.size())
1454 return Error("Invalid CALL record");
1455 } else {
1456 if ((Record.size()-NextArg) & 1)
1457 return Error("Invalid CALL record");
1458 for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
1459 Args.push_back(getFnValueByID(Record[NextArg+1],
1460 getTypeByID(Record[NextArg])));
1461 if (Args.back() == 0) return Error("Invalid CALL record");
1462 }
1463 }
1464
1465 I = new CallInst(Callee, &Args[0], Args.size());
Chris Lattner76520192007-05-03 22:34:03 +00001466 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1467 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001468 break;
1469 }
1470 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1471 if (Record.size() < 3)
1472 return Error("Invalid VAARG record");
1473 const Type *OpTy = getTypeByID(Record[0]);
1474 Value *Op = getFnValueByID(Record[1], OpTy);
1475 const Type *ResTy = getTypeByID(Record[2]);
1476 if (!OpTy || !Op || !ResTy)
1477 return Error("Invalid VAARG record");
1478 I = new VAArgInst(Op, ResTy);
1479 break;
1480 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001481 }
1482
1483 // Add instruction to end of current BB. If there is no current BB, reject
1484 // this file.
1485 if (CurBB == 0) {
1486 delete I;
1487 return Error("Invalid instruction with no BB");
1488 }
1489 CurBB->getInstList().push_back(I);
1490
1491 // If this was a terminator instruction, move to the next block.
1492 if (isa<TerminatorInst>(I)) {
1493 ++CurBBNo;
1494 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1495 }
1496
1497 // Non-void values get registered in the value table for future use.
1498 if (I && I->getType() != Type::VoidTy)
1499 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001500 }
1501
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001502 // Check the function list for unresolved values.
1503 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1504 if (A->getParent() == 0) {
1505 // We found at least one unresolved value. Nuke them all to avoid leaks.
1506 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1507 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1508 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1509 delete A;
1510 }
1511 }
1512 }
1513 return Error("Never resolved value found in function!");
1514 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001515
1516 // Trim the value list down to the size it was before we parsed this function.
1517 ValueList.shrinkTo(ModuleValueListSize);
1518 std::vector<BasicBlock*>().swap(FunctionBBs);
1519
Chris Lattner48f84872007-05-01 04:59:48 +00001520 return false;
1521}
1522
1523
Chris Lattnerc453f762007-04-29 07:54:31 +00001524//===----------------------------------------------------------------------===//
1525// External interface
1526//===----------------------------------------------------------------------===//
1527
1528/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1529///
1530ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1531 std::string *ErrMsg) {
1532 BitcodeReader *R = new BitcodeReader(Buffer);
1533 if (R->ParseBitcode()) {
1534 if (ErrMsg)
1535 *ErrMsg = R->getErrorString();
1536
1537 // Don't let the BitcodeReader dtor delete 'Buffer'.
1538 R->releaseMemoryBuffer();
1539 delete R;
1540 return 0;
1541 }
1542 return R;
1543}
1544
1545/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1546/// If an error occurs, return null and fill in *ErrMsg if non-null.
1547Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1548 BitcodeReader *R;
1549 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1550 if (!R) return 0;
1551
1552 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1553 // delete it when its dtor is run.
1554 Module *M = R->releaseModule(ErrMsg);
1555
1556 // Don't let the BitcodeReader dtor delete 'Buffer'.
1557 R->releaseMemoryBuffer();
1558 delete R;
1559 return M;
1560}