blob: 23d632a33091ee33cdb31073058f135e2446e78e [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 Lattner15e6d172007-05-04 19:11:41 +000039 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000040 return true;
41
Chris Lattner15e6d172007-05-04 19:11:41 +000042 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
43 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000044 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() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000185 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000186 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 Lattnere17b6582007-05-05 00:17:00 +0000242 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000243 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: {
Chris Lattner15e6d172007-05-04 19:11:41 +0000316 // FUNCTION: [vararg, attrid, retty, paramty x N]
317 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000318 return Error("Invalid FUNCTION type record");
319 std::vector<const Type*> ArgTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000320 for (unsigned i = 3, e = Record.size(); i != e; ++i)
321 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000322
Chris Lattner9113e732007-05-04 03:41:34 +0000323 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
324 Record[0], getParamAttrs(Record[1]));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000325 break;
326 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000327 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
328 if (Record.size() < 2)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000329 return Error("Invalid STRUCT type record");
330 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000331 for (unsigned i = 1, e = Record.size(); i != e; ++i)
332 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000333 ResultTy = StructType::get(EltTys, Record[0]);
334 break;
335 }
336 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
337 if (Record.size() < 2)
338 return Error("Invalid ARRAY type record");
339 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
340 break;
341 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
342 if (Record.size() < 2)
343 return Error("Invalid VECTOR type record");
344 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
345 break;
346 }
347
348 if (NumRecords == TypeList.size()) {
349 // If this is a new type slot, just append it.
350 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
351 ++NumRecords;
352 } else if (ResultTy == 0) {
353 // Otherwise, this was forward referenced, so an opaque type was created,
354 // but the result type is actually just an opaque. Leave the one we
355 // created previously.
356 ++NumRecords;
357 } else {
358 // Otherwise, this was forward referenced, so an opaque type was created.
359 // Resolve the opaque type to the real type now.
360 assert(NumRecords < TypeList.size() && "Typelist imbalance");
361 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
362
363 // Don't directly push the new type on the Tab. Instead we want to replace
364 // the opaque type we previously inserted with the new concrete value. The
365 // refinement from the abstract (opaque) type to the new type causes all
366 // uses of the abstract type to use the concrete type (NewTy). This will
367 // also cause the opaque type to be deleted.
368 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
369
370 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000371 // value table... or with a preexisting type that was already in the
372 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000373 assert(TypeList[NumRecords-1].get() != OldTy &&
374 "refineAbstractType didn't work!");
375 }
376 }
377}
378
379
Chris Lattner86697142007-05-01 05:01:34 +0000380bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000381 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000382 return Error("Malformed block record");
383
384 SmallVector<uint64_t, 64> Record;
385
386 // Read all the records for this type table.
387 std::string TypeName;
388 while (1) {
389 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000390 if (Code == bitc::END_BLOCK) {
391 if (Stream.ReadBlockEnd())
392 return Error("Error at end of type symbol table block");
393 return false;
394 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000395
396 if (Code == bitc::ENTER_SUBBLOCK) {
397 // No known subblocks, always skip them.
398 Stream.ReadSubBlockID();
399 if (Stream.SkipBlock())
400 return Error("Malformed block record");
401 continue;
402 }
403
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000404 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000405 Stream.ReadAbbrevRecord();
406 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000407 }
408
409 // Read a record.
410 Record.clear();
411 switch (Stream.ReadRecord(Code, Record)) {
412 default: // Default behavior: unknown type.
413 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000414 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000415 if (ConvertToString(Record, 1, TypeName))
416 return Error("Invalid TST_ENTRY record");
417 unsigned TypeID = Record[0];
418 if (TypeID >= TypeList.size())
419 return Error("Invalid Type ID in TST_ENTRY record");
420
421 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
422 TypeName.clear();
423 break;
424 }
425 }
426}
427
Chris Lattner86697142007-05-01 05:01:34 +0000428bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000429 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000430 return Error("Malformed block record");
431
432 SmallVector<uint64_t, 64> Record;
433
434 // Read all the records for this value table.
435 SmallString<128> ValueName;
436 while (1) {
437 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000438 if (Code == bitc::END_BLOCK) {
439 if (Stream.ReadBlockEnd())
440 return Error("Error at end of value symbol table block");
441 return false;
442 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000443 if (Code == bitc::ENTER_SUBBLOCK) {
444 // No known subblocks, always skip them.
445 Stream.ReadSubBlockID();
446 if (Stream.SkipBlock())
447 return Error("Malformed block record");
448 continue;
449 }
450
451 if (Code == bitc::DEFINE_ABBREV) {
452 Stream.ReadAbbrevRecord();
453 continue;
454 }
455
456 // Read a record.
457 Record.clear();
458 switch (Stream.ReadRecord(Code, Record)) {
459 default: // Default behavior: unknown type.
460 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000461 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000462 if (ConvertToString(Record, 1, ValueName))
463 return Error("Invalid TST_ENTRY record");
464 unsigned ValueID = Record[0];
465 if (ValueID >= ValueList.size())
466 return Error("Invalid Value ID in VST_ENTRY record");
467 Value *V = ValueList[ValueID];
468
469 V->setName(&ValueName[0], ValueName.size());
470 ValueName.clear();
471 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000472 }
473 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000474 if (ConvertToString(Record, 1, ValueName))
475 return Error("Invalid VST_BBENTRY record");
476 BasicBlock *BB = getBasicBlock(Record[0]);
477 if (BB == 0)
478 return Error("Invalid BB ID in VST_BBENTRY record");
479
480 BB->setName(&ValueName[0], ValueName.size());
481 ValueName.clear();
482 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000483 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000484 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000485 }
486}
487
Chris Lattner0eef0802007-04-24 04:04:35 +0000488/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
489/// the LSB for dense VBR encoding.
490static uint64_t DecodeSignRotatedValue(uint64_t V) {
491 if ((V & 1) == 0)
492 return V >> 1;
493 if (V != 1)
494 return -(V >> 1);
495 // There is no such thing as -0 with integers. "-0" really means MININT.
496 return 1ULL << 63;
497}
498
Chris Lattner07d98b42007-04-26 02:46:40 +0000499/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
500/// values and aliases that we can.
501bool BitcodeReader::ResolveGlobalAndAliasInits() {
502 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
503 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
504
505 GlobalInitWorklist.swap(GlobalInits);
506 AliasInitWorklist.swap(AliasInits);
507
508 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000509 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000510 if (ValID >= ValueList.size()) {
511 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000512 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000513 } else {
514 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
515 GlobalInitWorklist.back().first->setInitializer(C);
516 else
517 return Error("Global variable initializer is not a constant!");
518 }
519 GlobalInitWorklist.pop_back();
520 }
521
522 while (!AliasInitWorklist.empty()) {
523 unsigned ValID = AliasInitWorklist.back().second;
524 if (ValID >= ValueList.size()) {
525 AliasInits.push_back(AliasInitWorklist.back());
526 } else {
527 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000528 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000529 else
530 return Error("Alias initializer is not a constant!");
531 }
532 AliasInitWorklist.pop_back();
533 }
534 return false;
535}
536
537
Chris Lattner86697142007-05-01 05:01:34 +0000538bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000539 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000540 return Error("Malformed block record");
541
542 SmallVector<uint64_t, 64> Record;
543
544 // Read all the records for this value table.
545 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000546 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000547 while (1) {
548 unsigned Code = Stream.ReadCode();
549 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000550 if (NextCstNo != ValueList.size())
551 return Error("Invalid constant reference!");
552
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000553 if (Stream.ReadBlockEnd())
554 return Error("Error at end of constants block");
555 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000556 }
557
558 if (Code == bitc::ENTER_SUBBLOCK) {
559 // No known subblocks, always skip them.
560 Stream.ReadSubBlockID();
561 if (Stream.SkipBlock())
562 return Error("Malformed block record");
563 continue;
564 }
565
566 if (Code == bitc::DEFINE_ABBREV) {
567 Stream.ReadAbbrevRecord();
568 continue;
569 }
570
571 // Read a record.
572 Record.clear();
573 Value *V = 0;
574 switch (Stream.ReadRecord(Code, Record)) {
575 default: // Default behavior: unknown constant
576 case bitc::CST_CODE_UNDEF: // UNDEF
577 V = UndefValue::get(CurTy);
578 break;
579 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
580 if (Record.empty())
581 return Error("Malformed CST_SETTYPE record");
582 if (Record[0] >= TypeList.size())
583 return Error("Invalid Type ID in CST_SETTYPE record");
584 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000585 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000586 case bitc::CST_CODE_NULL: // NULL
587 V = Constant::getNullValue(CurTy);
588 break;
589 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000590 if (!isa<IntegerType>(CurTy) || Record.empty())
591 return Error("Invalid CST_INTEGER record");
592 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
593 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000594 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
595 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000596 return Error("Invalid WIDE_INTEGER record");
597
Chris Lattner15e6d172007-05-04 19:11:41 +0000598 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000599 SmallVector<uint64_t, 8> Words;
600 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000601 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000602 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000603 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000604 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000605 break;
606 }
607 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
608 if (Record.empty())
609 return Error("Invalid FLOAT record");
610 if (CurTy == Type::FloatTy)
611 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
612 else if (CurTy == Type::DoubleTy)
613 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
Chris Lattnere16504e2007-04-24 03:30:34 +0000614 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000615 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000616 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000617
Chris Lattner15e6d172007-05-04 19:11:41 +0000618 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
619 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000620 return Error("Invalid CST_AGGREGATE record");
621
Chris Lattner15e6d172007-05-04 19:11:41 +0000622 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000623 std::vector<Constant*> Elts;
624
625 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
626 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000627 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000628 STy->getElementType(i)));
629 V = ConstantStruct::get(STy, Elts);
630 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
631 const Type *EltTy = ATy->getElementType();
632 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000633 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000634 V = ConstantArray::get(ATy, Elts);
635 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
636 const Type *EltTy = VTy->getElementType();
637 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000638 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000639 V = ConstantVector::get(Elts);
640 } else {
641 V = UndefValue::get(CurTy);
642 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000643 break;
644 }
645
646 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
647 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
648 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000649 if (Opc < 0) {
650 V = UndefValue::get(CurTy); // Unknown binop.
651 } else {
652 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
653 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
654 V = ConstantExpr::get(Opc, LHS, RHS);
655 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000656 break;
657 }
658 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
659 if (Record.size() < 3) return Error("Invalid CE_CAST record");
660 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000661 if (Opc < 0) {
662 V = UndefValue::get(CurTy); // Unknown cast.
663 } else {
664 const Type *OpTy = getTypeByID(Record[1]);
665 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
666 V = ConstantExpr::getCast(Opc, Op, CurTy);
667 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000668 break;
669 }
670 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000671 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000672 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000673 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000674 const Type *ElTy = getTypeByID(Record[i]);
675 if (!ElTy) return Error("Invalid CE_GEP record");
676 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
677 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000678 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
679 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000680 }
681 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
682 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
683 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
684 Type::Int1Ty),
685 ValueList.getConstantFwdRef(Record[1],CurTy),
686 ValueList.getConstantFwdRef(Record[2],CurTy));
687 break;
688 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
689 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
690 const VectorType *OpTy =
691 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
692 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
693 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
694 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
695 OpTy->getElementType());
696 V = ConstantExpr::getExtractElement(Op0, Op1);
697 break;
698 }
699 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
700 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
701 if (Record.size() < 3 || OpTy == 0)
702 return Error("Invalid CE_INSERTELT record");
703 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
704 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
705 OpTy->getElementType());
706 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
707 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
708 break;
709 }
710 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
711 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
712 if (Record.size() < 3 || OpTy == 0)
713 return Error("Invalid CE_INSERTELT record");
714 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
715 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
716 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
717 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
718 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
719 break;
720 }
721 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
722 if (Record.size() < 4) return Error("Invalid CE_CMP record");
723 const Type *OpTy = getTypeByID(Record[0]);
724 if (OpTy == 0) return Error("Invalid CE_CMP record");
725 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
726 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
727
728 if (OpTy->isFloatingPoint())
729 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
730 else
731 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
732 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000733 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000734 }
735
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000736 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000737 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000738 }
739}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000740
Chris Lattner980e5aa2007-05-01 05:52:21 +0000741/// RememberAndSkipFunctionBody - When we see the block for a function body,
742/// remember where it is and then skip it. This lets us lazily deserialize the
743/// functions.
744bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000745 // Get the function we are talking about.
746 if (FunctionsWithBodies.empty())
747 return Error("Insufficient function protos");
748
749 Function *Fn = FunctionsWithBodies.back();
750 FunctionsWithBodies.pop_back();
751
752 // Save the current stream state.
753 uint64_t CurBit = Stream.GetCurrentBitNo();
754 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
755
756 // Set the functions linkage to GhostLinkage so we know it is lazily
757 // deserialized.
758 Fn->setLinkage(GlobalValue::GhostLinkage);
759
760 // Skip over the function block for now.
761 if (Stream.SkipBlock())
762 return Error("Malformed block record");
763 return false;
764}
765
Chris Lattner86697142007-05-01 05:01:34 +0000766bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000767 // Reject multiple MODULE_BLOCK's in a single bitstream.
768 if (TheModule)
769 return Error("Multiple MODULE_BLOCKs in same stream");
770
Chris Lattnere17b6582007-05-05 00:17:00 +0000771 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000772 return Error("Malformed block record");
773
774 // Otherwise, create the module.
775 TheModule = new Module(ModuleID);
776
777 SmallVector<uint64_t, 64> Record;
778 std::vector<std::string> SectionTable;
779
780 // Read all the records for this module.
781 while (!Stream.AtEndOfStream()) {
782 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000783 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000784 if (Stream.ReadBlockEnd())
785 return Error("Error at end of module block");
786
787 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000788 ResolveGlobalAndAliasInits();
789 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000790 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000791 if (!FunctionsWithBodies.empty())
792 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000793
794 // Force deallocation of memory for these vectors to favor the client that
795 // want lazy deserialization.
796 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
797 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
798 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000799 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000800 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000801
802 if (Code == bitc::ENTER_SUBBLOCK) {
803 switch (Stream.ReadSubBlockID()) {
804 default: // Skip unknown content.
805 if (Stream.SkipBlock())
806 return Error("Malformed block record");
807 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000808 case bitc::PARAMATTR_BLOCK_ID:
809 if (ParseParamAttrBlock())
810 return true;
811 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000812 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000813 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000814 return true;
815 break;
816 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000817 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000818 return true;
819 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000820 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000821 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000822 return true;
823 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000824 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000825 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000826 return true;
827 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000828 case bitc::FUNCTION_BLOCK_ID:
829 // If this is the first function body we've seen, reverse the
830 // FunctionsWithBodies list.
831 if (!HasReversedFunctionsWithBodies) {
832 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
833 HasReversedFunctionsWithBodies = true;
834 }
835
Chris Lattner980e5aa2007-05-01 05:52:21 +0000836 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000837 return true;
838 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000839 }
840 continue;
841 }
842
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000843 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000844 Stream.ReadAbbrevRecord();
845 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000846 }
847
848 // Read a record.
849 switch (Stream.ReadRecord(Code, Record)) {
850 default: break; // Default behavior, ignore unknown content.
851 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
852 if (Record.size() < 1)
853 return Error("Malformed MODULE_CODE_VERSION");
854 // Only version #0 is supported so far.
855 if (Record[0] != 0)
856 return Error("Unknown bitstream version!");
857 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000858 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000859 std::string S;
860 if (ConvertToString(Record, 0, S))
861 return Error("Invalid MODULE_CODE_TRIPLE record");
862 TheModule->setTargetTriple(S);
863 break;
864 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000865 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000866 std::string S;
867 if (ConvertToString(Record, 0, S))
868 return Error("Invalid MODULE_CODE_DATALAYOUT record");
869 TheModule->setDataLayout(S);
870 break;
871 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000872 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000873 std::string S;
874 if (ConvertToString(Record, 0, S))
875 return Error("Invalid MODULE_CODE_ASM record");
876 TheModule->setModuleInlineAsm(S);
877 break;
878 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000879 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000880 std::string S;
881 if (ConvertToString(Record, 0, S))
882 return Error("Invalid MODULE_CODE_DEPLIB record");
883 TheModule->addLibrary(S);
884 break;
885 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000886 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000887 std::string S;
888 if (ConvertToString(Record, 0, S))
889 return Error("Invalid MODULE_CODE_SECTIONNAME record");
890 SectionTable.push_back(S);
891 break;
892 }
893 // GLOBALVAR: [type, isconst, initid,
894 // linkage, alignment, section, visibility, threadlocal]
895 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000896 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000897 return Error("Invalid MODULE_CODE_GLOBALVAR record");
898 const Type *Ty = getTypeByID(Record[0]);
899 if (!isa<PointerType>(Ty))
900 return Error("Global not a pointer type!");
901 Ty = cast<PointerType>(Ty)->getElementType();
902
903 bool isConstant = Record[1];
904 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
905 unsigned Alignment = (1 << Record[4]) >> 1;
906 std::string Section;
907 if (Record[5]) {
908 if (Record[5]-1 >= SectionTable.size())
909 return Error("Invalid section ID");
910 Section = SectionTable[Record[5]-1];
911 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000912 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
913 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
914 bool isThreadLocal = false;
915 if (Record.size() >= 7) isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000916
917 GlobalVariable *NewGV =
918 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
919 NewGV->setAlignment(Alignment);
920 if (!Section.empty())
921 NewGV->setSection(Section);
922 NewGV->setVisibility(Visibility);
923 NewGV->setThreadLocal(isThreadLocal);
924
Chris Lattner0b2482a2007-04-23 21:26:05 +0000925 ValueList.push_back(NewGV);
926
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000927 // Remember which value to use for the global initializer.
928 if (unsigned InitID = Record[2])
929 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000930 break;
931 }
932 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
933 // visibility]
934 case bitc::MODULE_CODE_FUNCTION: {
935 if (Record.size() < 7)
936 return Error("Invalid MODULE_CODE_FUNCTION record");
937 const Type *Ty = getTypeByID(Record[0]);
938 if (!isa<PointerType>(Ty))
939 return Error("Function not a pointer type!");
940 const FunctionType *FTy =
941 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
942 if (!FTy)
943 return Error("Function not a pointer to function type!");
944
945 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
946 "", TheModule);
947
948 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +0000949 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000950 Func->setLinkage(GetDecodedLinkage(Record[3]));
951 Func->setAlignment((1 << Record[4]) >> 1);
952 if (Record[5]) {
953 if (Record[5]-1 >= SectionTable.size())
954 return Error("Invalid section ID");
955 Func->setSection(SectionTable[Record[5]-1]);
956 }
957 Func->setVisibility(GetDecodedVisibility(Record[6]));
958
Chris Lattner0b2482a2007-04-23 21:26:05 +0000959 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +0000960
961 // If this is a function with a body, remember the prototype we are
962 // creating now, so that we can match up the body with them later.
963 if (!isProto)
964 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000965 break;
966 }
Chris Lattner07d98b42007-04-26 02:46:40 +0000967 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +0000968 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +0000969 if (Record.size() < 3)
970 return Error("Invalid MODULE_ALIAS record");
971 const Type *Ty = getTypeByID(Record[0]);
972 if (!isa<PointerType>(Ty))
973 return Error("Function not a pointer type!");
974
975 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
976 "", 0, TheModule);
977 ValueList.push_back(NewGA);
978 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
979 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000980 }
Chris Lattner198f34a2007-04-26 03:27:58 +0000981 /// MODULE_CODE_PURGEVALS: [numvals]
982 case bitc::MODULE_CODE_PURGEVALS:
983 // Trim down the value list to the specified size.
984 if (Record.size() < 1 || Record[0] > ValueList.size())
985 return Error("Invalid MODULE_PURGEVALS record");
986 ValueList.shrinkTo(Record[0]);
987 break;
988 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000989 Record.clear();
990 }
991
992 return Error("Premature end of bitstream");
993}
994
995
Chris Lattnerc453f762007-04-29 07:54:31 +0000996bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000997 TheModule = 0;
998
Chris Lattnerc453f762007-04-29 07:54:31 +0000999 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001000 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1001
Chris Lattnerc453f762007-04-29 07:54:31 +00001002 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001003 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001004
1005 // Sniff for the signature.
1006 if (Stream.Read(8) != 'B' ||
1007 Stream.Read(8) != 'C' ||
1008 Stream.Read(4) != 0x0 ||
1009 Stream.Read(4) != 0xC ||
1010 Stream.Read(4) != 0xE ||
1011 Stream.Read(4) != 0xD)
1012 return Error("Invalid bitcode signature");
1013
1014 // We expect a number of well-defined blocks, though we don't necessarily
1015 // need to understand them all.
1016 while (!Stream.AtEndOfStream()) {
1017 unsigned Code = Stream.ReadCode();
1018
1019 if (Code != bitc::ENTER_SUBBLOCK)
1020 return Error("Invalid record at top-level");
1021
1022 unsigned BlockID = Stream.ReadSubBlockID();
1023
1024 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001025 switch (BlockID) {
1026 case bitc::BLOCKINFO_BLOCK_ID:
1027 if (Stream.ReadBlockInfoBlock())
1028 return Error("Malformed BlockInfoBlock");
1029 break;
1030 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001031 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001032 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001033 break;
1034 default:
1035 if (Stream.SkipBlock())
1036 return Error("Malformed block record");
1037 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001038 }
1039 }
1040
1041 return false;
1042}
Chris Lattnerc453f762007-04-29 07:54:31 +00001043
Chris Lattner48f84872007-05-01 04:59:48 +00001044
1045bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1046 // If it already is material, ignore the request.
1047 if (!F->hasNotBeenReadFromBytecode()) return false;
1048
1049 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1050 DeferredFunctionInfo.find(F);
1051 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1052
1053 // Move the bit stream to the saved position of the deferred function body and
1054 // restore the real linkage type for the function.
1055 Stream.JumpToBit(DFII->second.first);
1056 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1057 DeferredFunctionInfo.erase(DFII);
1058
Chris Lattner980e5aa2007-05-01 05:52:21 +00001059 if (ParseFunctionBody(F)) {
1060 if (ErrInfo) *ErrInfo = ErrorString;
1061 return true;
1062 }
1063
1064 return false;
1065}
1066
1067Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1068 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1069 DeferredFunctionInfo.begin();
1070 while (!DeferredFunctionInfo.empty()) {
1071 Function *F = (*I++).first;
1072 assert(F->hasNotBeenReadFromBytecode() &&
1073 "Deserialized function found in map!");
1074 if (materializeFunction(F, ErrInfo))
1075 return 0;
1076 }
1077 return TheModule;
1078}
1079
1080
1081/// ParseFunctionBody - Lazily parse the specified function body block.
1082bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001083 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001084 return Error("Malformed block record");
1085
1086 unsigned ModuleValueListSize = ValueList.size();
1087
1088 // Add all the function arguments to the value table.
1089 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1090 ValueList.push_back(I);
1091
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001092 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001093 BasicBlock *CurBB = 0;
1094 unsigned CurBBNo = 0;
1095
Chris Lattner980e5aa2007-05-01 05:52:21 +00001096 // Read all the records.
1097 SmallVector<uint64_t, 64> Record;
1098 while (1) {
1099 unsigned Code = Stream.ReadCode();
1100 if (Code == bitc::END_BLOCK) {
1101 if (Stream.ReadBlockEnd())
1102 return Error("Error at end of function block");
1103 break;
1104 }
1105
1106 if (Code == bitc::ENTER_SUBBLOCK) {
1107 switch (Stream.ReadSubBlockID()) {
1108 default: // Skip unknown content.
1109 if (Stream.SkipBlock())
1110 return Error("Malformed block record");
1111 break;
1112 case bitc::CONSTANTS_BLOCK_ID:
1113 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001114 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001115 break;
1116 case bitc::VALUE_SYMTAB_BLOCK_ID:
1117 if (ParseValueSymbolTable()) return true;
1118 break;
1119 }
1120 continue;
1121 }
1122
1123 if (Code == bitc::DEFINE_ABBREV) {
1124 Stream.ReadAbbrevRecord();
1125 continue;
1126 }
1127
1128 // Read a record.
1129 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001130 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001131 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001132 default: // Default behavior: reject
1133 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001134 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001135 if (Record.size() < 1 || Record[0] == 0)
1136 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001137 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001138 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001139 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1140 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001141 CurBB = FunctionBBs[0];
1142 continue;
1143
Chris Lattner231cbcb2007-05-02 04:27:25 +00001144 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001145 if (Record.size() < 4) return Error("Invalid BINOP record");
1146 const Type *Ty = getTypeByID(Record[1]);
1147 int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1148 Value *LHS = getFnValueByID(Record[2], Ty);
1149 Value *RHS = getFnValueByID(Record[3], Ty);
1150 if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1151 return Error("Invalid BINOP record");
1152 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001153 break;
1154 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001155 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
1156 if (Record.size() < 4) return Error("Invalid CAST record");
1157 int Opc = GetDecodedCastOpcode(Record[0]);
1158 const Type *ResTy = getTypeByID(Record[1]);
1159 const Type *OpTy = getTypeByID(Record[2]);
1160 Value *Op = getFnValueByID(Record[3], OpTy);
1161 if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1162 return Error("Invalid CAST record");
1163 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1164 break;
1165 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001166 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner01ff65f2007-05-02 05:16:49 +00001167 if (Record.size() < 2 || (Record.size() & 1))
1168 return Error("Invalid GEP record");
1169 const Type *OpTy = getTypeByID(Record[0]);
1170 Value *Op = getFnValueByID(Record[1], OpTy);
1171 if (OpTy == 0 || Op == 0)
1172 return Error("Invalid GEP record");
1173
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001174 SmallVector<Value*, 16> GEPIdx;
Chris Lattner01ff65f2007-05-02 05:16:49 +00001175 for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
1176 const Type *IdxTy = getTypeByID(Record[i*2]);
1177 Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
1178 if (IdxTy == 0 || Idx == 0)
1179 return Error("Invalid GEP record");
1180 GEPIdx.push_back(Idx);
1181 }
1182
1183 I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
1184 break;
1185 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001186
Chris Lattner01ff65f2007-05-02 05:16:49 +00001187 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
1188 if (Record.size() < 4) return Error("Invalid SELECT record");
1189 const Type *Ty = getTypeByID(Record[0]);
1190 Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
1191 Value *LHS = getFnValueByID(Record[2], Ty);
1192 Value *RHS = getFnValueByID(Record[3], Ty);
1193 if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
1194 return Error("Invalid SELECT record");
1195 I = new SelectInst(Cond, LHS, RHS);
1196 break;
1197 }
1198
1199 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1200 if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
1201 const Type *OpTy = getTypeByID(Record[0]);
1202 Value *Vec = getFnValueByID(Record[1], OpTy);
1203 Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
1204 if (OpTy == 0 || Vec == 0 || Idx == 0)
1205 return Error("Invalid EXTRACTELT record");
1206 I = new ExtractElementInst(Vec, Idx);
1207 break;
1208 }
1209
1210 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1211 if (Record.size() < 4) return Error("Invalid INSERTELT record");
1212 const VectorType *OpTy =
1213 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1214 if (OpTy == 0) return Error("Invalid INSERTELT record");
1215 Value *Vec = getFnValueByID(Record[1], OpTy);
1216 Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
1217 Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
1218 if (Vec == 0 || Elt == 0 || Idx == 0)
1219 return Error("Invalid INSERTELT record");
1220 I = new InsertElementInst(Vec, Elt, Idx);
1221 break;
1222 }
1223
1224 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
1225 if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
1226 const VectorType *OpTy =
1227 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1228 if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
1229 Value *Vec1 = getFnValueByID(Record[1], OpTy);
1230 Value *Vec2 = getFnValueByID(Record[2], OpTy);
1231 Value *Mask = getFnValueByID(Record[3],
1232 VectorType::get(Type::Int32Ty,
1233 OpTy->getNumElements()));
1234 if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
1235 return Error("Invalid SHUFFLEVEC record");
1236 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1237 break;
1238 }
1239
1240 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1241 if (Record.size() < 4) return Error("Invalid CMP record");
1242 const Type *OpTy = getTypeByID(Record[0]);
1243 Value *LHS = getFnValueByID(Record[1], OpTy);
1244 Value *RHS = getFnValueByID(Record[2], OpTy);
1245 if (OpTy == 0 || LHS == 0 || RHS == 0)
1246 return Error("Invalid CMP record");
1247 if (OpTy->isFPOrFPVector())
1248 I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
1249 else
1250 I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
1251 break;
1252 }
1253
Chris Lattner231cbcb2007-05-02 04:27:25 +00001254 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1255 if (Record.size() == 0) {
1256 I = new ReturnInst();
1257 break;
1258 }
1259 if (Record.size() == 2) {
1260 const Type *OpTy = getTypeByID(Record[0]);
1261 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001262 if (!OpTy || !Op)
1263 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001264 I = new ReturnInst(Op);
1265 break;
1266 }
1267 return Error("Invalid RET record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001268 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001269 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001270 return Error("Invalid BR record");
1271 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1272 if (TrueDest == 0)
1273 return Error("Invalid BR record");
1274
1275 if (Record.size() == 1)
1276 I = new BranchInst(TrueDest);
1277 else {
1278 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1279 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1280 if (FalseDest == 0 || Cond == 0)
1281 return Error("Invalid BR record");
1282 I = new BranchInst(TrueDest, FalseDest, Cond);
1283 }
1284 break;
1285 }
1286 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1287 if (Record.size() < 3 || (Record.size() & 1) == 0)
1288 return Error("Invalid SWITCH record");
1289 const Type *OpTy = getTypeByID(Record[0]);
1290 Value *Cond = getFnValueByID(Record[1], OpTy);
1291 BasicBlock *Default = getBasicBlock(Record[2]);
1292 if (OpTy == 0 || Cond == 0 || Default == 0)
1293 return Error("Invalid SWITCH record");
1294 unsigned NumCases = (Record.size()-3)/2;
1295 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1296 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1297 ConstantInt *CaseVal =
1298 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1299 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1300 if (CaseVal == 0 || DestBB == 0) {
1301 delete SI;
1302 return Error("Invalid SWITCH record!");
1303 }
1304 SI->addCase(CaseVal, DestBB);
1305 }
1306 I = SI;
1307 break;
1308 }
1309
Chris Lattner76520192007-05-03 22:34:03 +00001310 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1311 if (Record.size() < 5)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001312 return Error("Invalid INVOKE record");
Chris Lattner76520192007-05-03 22:34:03 +00001313 unsigned CCInfo = Record[0];
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001314 const PointerType *CalleeTy =
Chris Lattner76520192007-05-03 22:34:03 +00001315 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
1316 Value *Callee = getFnValueByID(Record[2], CalleeTy);
1317 BasicBlock *NormalBB = getBasicBlock(Record[3]);
1318 BasicBlock *UnwindBB = getBasicBlock(Record[4]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001319 if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
1320 return Error("Invalid INVOKE record");
1321
1322 const FunctionType *FTy =
1323 dyn_cast<FunctionType>(CalleeTy->getElementType());
1324
1325 // Check that the right number of fixed parameters are here.
Chris Lattner76520192007-05-03 22:34:03 +00001326 if (FTy == 0 || Record.size() < 5+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001327 return Error("Invalid INVOKE record");
1328
1329 SmallVector<Value*, 16> Ops;
1330 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
Chris Lattner76520192007-05-03 22:34:03 +00001331 Ops.push_back(getFnValueByID(Record[5+i], FTy->getParamType(i)));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001332 if (Ops.back() == 0)
1333 return Error("Invalid INVOKE record");
1334 }
1335
Chris Lattner76520192007-05-03 22:34:03 +00001336 unsigned FirstVarargParam = 5+FTy->getNumParams();
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001337 if (FTy->isVarArg()) {
1338 // Read type/value pairs for varargs params.
1339 if ((Record.size()-FirstVarargParam) & 1)
1340 return Error("Invalid INVOKE record");
1341
1342 for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
1343 const Type *ArgTy = getTypeByID(Record[i]);
1344 Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
1345 if (Ops.back() == 0 || ArgTy == 0)
1346 return Error("Invalid INVOKE record");
1347 }
1348 } else {
1349 if (Record.size() != FirstVarargParam)
1350 return Error("Invalid INVOKE record");
1351 }
1352
1353 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
Chris Lattner76520192007-05-03 22:34:03 +00001354 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001355 break;
1356 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001357 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1358 I = new UnwindInst();
1359 break;
1360 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1361 I = new UnreachableInst();
1362 break;
Chris Lattner2a98cca2007-05-03 18:58:09 +00001363 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001364 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001365 return Error("Invalid PHI record");
1366 const Type *Ty = getTypeByID(Record[0]);
1367 if (!Ty) return Error("Invalid PHI record");
1368
1369 PHINode *PN = new PHINode(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001370 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001371
Chris Lattner15e6d172007-05-04 19:11:41 +00001372 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1373 Value *V = getFnValueByID(Record[1+i], Ty);
1374 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001375 if (!V || !BB) return Error("Invalid PHI record");
1376 PN->addIncoming(V, BB);
1377 }
1378 I = PN;
1379 break;
1380 }
1381
1382 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1383 if (Record.size() < 3)
1384 return Error("Invalid MALLOC record");
1385 const PointerType *Ty =
1386 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1387 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1388 unsigned Align = Record[2];
1389 if (!Ty || !Size) return Error("Invalid MALLOC record");
1390 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1391 break;
1392 }
1393 case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
1394 if (Record.size() < 2)
1395 return Error("Invalid FREE record");
1396 const Type *OpTy = getTypeByID(Record[0]);
1397 Value *Op = getFnValueByID(Record[1], OpTy);
1398 if (!OpTy || !Op)
1399 return Error("Invalid FREE record");
1400 I = new FreeInst(Op);
1401 break;
1402 }
1403 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1404 if (Record.size() < 3)
1405 return Error("Invalid ALLOCA record");
1406 const PointerType *Ty =
1407 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1408 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1409 unsigned Align = Record[2];
1410 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1411 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1412 break;
1413 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001414 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1415 if (Record.size() < 4)
1416 return Error("Invalid LOAD record");
1417 const Type *OpTy = getTypeByID(Record[0]);
1418 Value *Op = getFnValueByID(Record[1], OpTy);
1419 if (!OpTy || !Op)
1420 return Error("Invalid LOAD record");
1421 I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001422 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001423 }
1424 case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
1425 if (Record.size() < 5)
1426 return Error("Invalid LOAD record");
Chris Lattnerc9c55a92007-05-03 22:21:59 +00001427 const PointerType *OpTy =
1428 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1429 Value *Op = getFnValueByID(Record[1], OpTy ? OpTy->getElementType() : 0);
1430 Value *Ptr = getFnValueByID(Record[2], OpTy);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001431 if (!OpTy || !Op || !Ptr)
1432 return Error("Invalid STORE record");
Chris Lattner964b5f22007-05-04 03:57:30 +00001433 I = new StoreInst(Op, Ptr, Record[4], (1 << Record[3]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001434 break;
1435 }
Chris Lattner76520192007-05-03 22:34:03 +00001436 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1437 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001438 return Error("Invalid CALL record");
Chris Lattner76520192007-05-03 22:34:03 +00001439 unsigned CCInfo = Record[0];
Chris Lattner0579f7f2007-05-03 22:04:19 +00001440 const PointerType *OpTy =
Chris Lattner76520192007-05-03 22:34:03 +00001441 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001442 const FunctionType *FTy = 0;
1443 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner76520192007-05-03 22:34:03 +00001444 Value *Callee = getFnValueByID(Record[2], OpTy);
1445 if (!FTy || !Callee || Record.size() < FTy->getNumParams()+3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001446 return Error("Invalid CALL record");
1447
1448 SmallVector<Value*, 16> Args;
1449 // Read the fixed params.
1450 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
Chris Lattner76520192007-05-03 22:34:03 +00001451 Args.push_back(getFnValueByID(Record[i+3], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001452 if (Args.back() == 0) return Error("Invalid CALL record");
1453 }
1454
1455
1456 // Read type/value pairs for varargs params.
Chris Lattner76520192007-05-03 22:34:03 +00001457 unsigned NextArg = FTy->getNumParams()+3;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001458 if (!FTy->isVarArg()) {
1459 if (NextArg != Record.size())
1460 return Error("Invalid CALL record");
1461 } else {
1462 if ((Record.size()-NextArg) & 1)
1463 return Error("Invalid CALL record");
1464 for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
1465 Args.push_back(getFnValueByID(Record[NextArg+1],
1466 getTypeByID(Record[NextArg])));
1467 if (Args.back() == 0) return Error("Invalid CALL record");
1468 }
1469 }
1470
1471 I = new CallInst(Callee, &Args[0], Args.size());
Chris Lattner76520192007-05-03 22:34:03 +00001472 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1473 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001474 break;
1475 }
1476 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1477 if (Record.size() < 3)
1478 return Error("Invalid VAARG record");
1479 const Type *OpTy = getTypeByID(Record[0]);
1480 Value *Op = getFnValueByID(Record[1], OpTy);
1481 const Type *ResTy = getTypeByID(Record[2]);
1482 if (!OpTy || !Op || !ResTy)
1483 return Error("Invalid VAARG record");
1484 I = new VAArgInst(Op, ResTy);
1485 break;
1486 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001487 }
1488
1489 // Add instruction to end of current BB. If there is no current BB, reject
1490 // this file.
1491 if (CurBB == 0) {
1492 delete I;
1493 return Error("Invalid instruction with no BB");
1494 }
1495 CurBB->getInstList().push_back(I);
1496
1497 // If this was a terminator instruction, move to the next block.
1498 if (isa<TerminatorInst>(I)) {
1499 ++CurBBNo;
1500 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1501 }
1502
1503 // Non-void values get registered in the value table for future use.
1504 if (I && I->getType() != Type::VoidTy)
1505 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001506 }
1507
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001508 // Check the function list for unresolved values.
1509 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1510 if (A->getParent() == 0) {
1511 // We found at least one unresolved value. Nuke them all to avoid leaks.
1512 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1513 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1514 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1515 delete A;
1516 }
1517 }
Chris Lattner35a04702007-05-04 03:50:29 +00001518 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001519 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001520 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001521
1522 // Trim the value list down to the size it was before we parsed this function.
1523 ValueList.shrinkTo(ModuleValueListSize);
1524 std::vector<BasicBlock*>().swap(FunctionBBs);
1525
Chris Lattner48f84872007-05-01 04:59:48 +00001526 return false;
1527}
1528
1529
Chris Lattnerc453f762007-04-29 07:54:31 +00001530//===----------------------------------------------------------------------===//
1531// External interface
1532//===----------------------------------------------------------------------===//
1533
1534/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1535///
1536ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1537 std::string *ErrMsg) {
1538 BitcodeReader *R = new BitcodeReader(Buffer);
1539 if (R->ParseBitcode()) {
1540 if (ErrMsg)
1541 *ErrMsg = R->getErrorString();
1542
1543 // Don't let the BitcodeReader dtor delete 'Buffer'.
1544 R->releaseMemoryBuffer();
1545 delete R;
1546 return 0;
1547 }
1548 return R;
1549}
1550
1551/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1552/// If an error occurs, return null and fill in *ErrMsg if non-null.
1553Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1554 BitcodeReader *R;
1555 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1556 if (!R) return 0;
1557
1558 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1559 // delete it when its dtor is run.
1560 Module *M = R->releaseModule(ErrMsg);
1561
1562 // Don't let the BitcodeReader dtor delete 'Buffer'.
1563 R->releaseMemoryBuffer();
1564 delete R;
1565 return M;
1566}