blob: 283cd1df7751fe03f929c4ac88dbc11282de1d7e [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 Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Chris Lattnera7c49aa2007-05-01 07:01:57 +000019#include "llvm/Instructions.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Chris Lattner48c85b82007-05-04 03:30:17 +000021#include "llvm/ParameterAttributes.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000022#include "llvm/ADT/SmallString.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000023#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000024#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000025using namespace llvm;
26
Chris Lattnerc453f762007-04-29 07:54:31 +000027BitcodeReader::~BitcodeReader() {
28 delete Buffer;
29}
30
Chris Lattner48c85b82007-05-04 03:30:17 +000031//===----------------------------------------------------------------------===//
32// Helper functions to implement forward reference resolution, etc.
33//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000034
Chris Lattnercaee0dc2007-04-22 06:23:29 +000035/// ConvertToString - Convert a string from a record into an std::string, return
36/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000037template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000038static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000039 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000040 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000041 return true;
42
Chris Lattner15e6d172007-05-04 19:11:41 +000043 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
44 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000045 return false;
46}
47
48static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
49 switch (Val) {
50 default: // Map unknown/new linkages to external
51 case 0: return GlobalValue::ExternalLinkage;
52 case 1: return GlobalValue::WeakLinkage;
53 case 2: return GlobalValue::AppendingLinkage;
54 case 3: return GlobalValue::InternalLinkage;
55 case 4: return GlobalValue::LinkOnceLinkage;
56 case 5: return GlobalValue::DLLImportLinkage;
57 case 6: return GlobalValue::DLLExportLinkage;
58 case 7: return GlobalValue::ExternalWeakLinkage;
59 }
60}
61
62static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
63 switch (Val) {
64 default: // Map unknown visibilities to default.
65 case 0: return GlobalValue::DefaultVisibility;
66 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000067 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000068 }
69}
70
Chris Lattnerf581c3b2007-04-24 07:07:11 +000071static int GetDecodedCastOpcode(unsigned Val) {
72 switch (Val) {
73 default: return -1;
74 case bitc::CAST_TRUNC : return Instruction::Trunc;
75 case bitc::CAST_ZEXT : return Instruction::ZExt;
76 case bitc::CAST_SEXT : return Instruction::SExt;
77 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
78 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
79 case bitc::CAST_UITOFP : return Instruction::UIToFP;
80 case bitc::CAST_SITOFP : return Instruction::SIToFP;
81 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
82 case bitc::CAST_FPEXT : return Instruction::FPExt;
83 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
84 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
85 case bitc::CAST_BITCAST : return Instruction::BitCast;
86 }
87}
88static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
89 switch (Val) {
90 default: return -1;
91 case bitc::BINOP_ADD: return Instruction::Add;
92 case bitc::BINOP_SUB: return Instruction::Sub;
93 case bitc::BINOP_MUL: return Instruction::Mul;
94 case bitc::BINOP_UDIV: return Instruction::UDiv;
95 case bitc::BINOP_SDIV:
96 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
97 case bitc::BINOP_UREM: return Instruction::URem;
98 case bitc::BINOP_SREM:
99 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
100 case bitc::BINOP_SHL: return Instruction::Shl;
101 case bitc::BINOP_LSHR: return Instruction::LShr;
102 case bitc::BINOP_ASHR: return Instruction::AShr;
103 case bitc::BINOP_AND: return Instruction::And;
104 case bitc::BINOP_OR: return Instruction::Or;
105 case bitc::BINOP_XOR: return Instruction::Xor;
106 }
107}
108
109
Chris Lattner522b7b12007-04-24 05:48:56 +0000110namespace {
111 /// @brief A class for maintaining the slot number definition
112 /// as a placeholder for the actual definition for forward constants defs.
113 class ConstantPlaceHolder : public ConstantExpr {
114 ConstantPlaceHolder(); // DO NOT IMPLEMENT
115 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000116 public:
117 Use Op;
118 ConstantPlaceHolder(const Type *Ty)
119 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
120 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000121 }
122 };
123}
124
125Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
126 const Type *Ty) {
127 if (Idx >= size()) {
128 // Insert a bunch of null values.
129 Uses.resize(Idx+1);
130 OperandList = &Uses[0];
131 NumOperands = Idx+1;
132 }
133
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000134 if (Value *V = Uses[Idx]) {
135 assert(Ty == V->getType() && "Type mismatch in constant table!");
136 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000137 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000138
139 // Create and return a placeholder, which will later be RAUW'd.
140 Constant *C = new ConstantPlaceHolder(Ty);
141 Uses[Idx].init(C, this);
142 return C;
143}
144
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000145Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
146 if (Idx >= size()) {
147 // Insert a bunch of null values.
148 Uses.resize(Idx+1);
149 OperandList = &Uses[0];
150 NumOperands = Idx+1;
151 }
152
153 if (Value *V = Uses[Idx]) {
154 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
155 return V;
156 }
157
Chris Lattner01ff65f2007-05-02 05:16:49 +0000158 // No type specified, must be invalid reference.
159 if (Ty == 0) return 0;
160
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000161 // Create and return a placeholder, which will later be RAUW'd.
162 Value *V = new Argument(Ty);
163 Uses[Idx].init(V, this);
164 return V;
165}
166
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000167
168const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
169 // If the TypeID is in range, return it.
170 if (ID < TypeList.size())
171 return TypeList[ID].get();
172 if (!isTypeTable) return 0;
173
174 // The type table allows forward references. Push as many Opaque types as
175 // needed to get up to ID.
176 while (TypeList.size() <= ID)
177 TypeList.push_back(OpaqueType::get());
178 return TypeList.back().get();
179}
180
Chris Lattner48c85b82007-05-04 03:30:17 +0000181//===----------------------------------------------------------------------===//
182// Functions for parsing blocks from the bitcode file
183//===----------------------------------------------------------------------===//
184
185bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000186 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000187 return Error("Malformed block record");
188
189 if (!ParamAttrs.empty())
190 return Error("Multiple PARAMATTR blocks found!");
191
192 SmallVector<uint64_t, 64> Record;
193
194 ParamAttrsVector Attrs;
195
196 // Read all the records.
197 while (1) {
198 unsigned Code = Stream.ReadCode();
199 if (Code == bitc::END_BLOCK) {
200 if (Stream.ReadBlockEnd())
201 return Error("Error at end of PARAMATTR block");
202 return false;
203 }
204
205 if (Code == bitc::ENTER_SUBBLOCK) {
206 // No known subblocks, always skip them.
207 Stream.ReadSubBlockID();
208 if (Stream.SkipBlock())
209 return Error("Malformed block record");
210 continue;
211 }
212
213 if (Code == bitc::DEFINE_ABBREV) {
214 Stream.ReadAbbrevRecord();
215 continue;
216 }
217
218 // Read a record.
219 Record.clear();
220 switch (Stream.ReadRecord(Code, Record)) {
221 default: // Default behavior: ignore.
222 break;
223 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
224 if (Record.size() & 1)
225 return Error("Invalid ENTRY record");
226
227 ParamAttrsWithIndex PAWI;
228 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
229 PAWI.index = Record[i];
230 PAWI.attrs = Record[i+1];
231 Attrs.push_back(PAWI);
232 }
233 ParamAttrs.push_back(ParamAttrsList::get(Attrs));
234 Attrs.clear();
235 break;
236 }
237 }
238 }
239}
240
241
Chris Lattner86697142007-05-01 05:01:34 +0000242bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000243 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000244 return Error("Malformed block record");
245
246 if (!TypeList.empty())
247 return Error("Multiple TYPE_BLOCKs found!");
248
249 SmallVector<uint64_t, 64> Record;
250 unsigned NumRecords = 0;
251
252 // Read all the records for this type table.
253 while (1) {
254 unsigned Code = Stream.ReadCode();
255 if (Code == bitc::END_BLOCK) {
256 if (NumRecords != TypeList.size())
257 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000258 if (Stream.ReadBlockEnd())
259 return Error("Error at end of type table block");
260 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000261 }
262
263 if (Code == bitc::ENTER_SUBBLOCK) {
264 // No known subblocks, always skip them.
265 Stream.ReadSubBlockID();
266 if (Stream.SkipBlock())
267 return Error("Malformed block record");
268 continue;
269 }
270
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000271 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000272 Stream.ReadAbbrevRecord();
273 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000274 }
275
276 // Read a record.
277 Record.clear();
278 const Type *ResultTy = 0;
279 switch (Stream.ReadRecord(Code, Record)) {
280 default: // Default behavior: unknown type.
281 ResultTy = 0;
282 break;
283 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
284 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
285 // type list. This allows us to reserve space.
286 if (Record.size() < 1)
287 return Error("Invalid TYPE_CODE_NUMENTRY record");
288 TypeList.reserve(Record[0]);
289 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000290 case bitc::TYPE_CODE_VOID: // VOID
291 ResultTy = Type::VoidTy;
292 break;
293 case bitc::TYPE_CODE_FLOAT: // FLOAT
294 ResultTy = Type::FloatTy;
295 break;
296 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
297 ResultTy = Type::DoubleTy;
298 break;
299 case bitc::TYPE_CODE_LABEL: // LABEL
300 ResultTy = Type::LabelTy;
301 break;
302 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
303 ResultTy = 0;
304 break;
305 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
306 if (Record.size() < 1)
307 return Error("Invalid Integer type record");
308
309 ResultTy = IntegerType::get(Record[0]);
310 break;
311 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
312 if (Record.size() < 1)
313 return Error("Invalid POINTER type record");
314 ResultTy = PointerType::get(getTypeByID(Record[0], true));
315 break;
316 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattner15e6d172007-05-04 19:11:41 +0000317 // FUNCTION: [vararg, attrid, retty, paramty x N]
318 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000319 return Error("Invalid FUNCTION type record");
320 std::vector<const Type*> ArgTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000321 for (unsigned i = 3, e = Record.size(); i != e; ++i)
322 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000323
Chris Lattner9113e732007-05-04 03:41:34 +0000324 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
325 Record[0], getParamAttrs(Record[1]));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000326 break;
327 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000328 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
329 if (Record.size() < 2)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000330 return Error("Invalid STRUCT type record");
331 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000332 for (unsigned i = 1, e = Record.size(); i != e; ++i)
333 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000334 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 Lattnere17b6582007-05-05 00:17:00 +0000382 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000383 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 Lattner15e6d172007-05-04 19:11:41 +0000415 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, 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 Lattnere17b6582007-05-05 00:17:00 +0000430 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000431 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;
Chris Lattner15e6d172007-05-04 19:11:41 +0000462 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, 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 Lattnere17b6582007-05-05 00:17:00 +0000540 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000541 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;
Chris Lattner15e6d172007-05-04 19:11:41 +0000595 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
596 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000597 return Error("Invalid WIDE_INTEGER record");
598
Chris Lattner15e6d172007-05-04 19:11:41 +0000599 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000600 SmallVector<uint64_t, 8> Words;
601 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000602 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000603 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000604 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000605 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000606 break;
607 }
608 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
609 if (Record.empty())
610 return Error("Invalid FLOAT record");
611 if (CurTy == Type::FloatTy)
612 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
613 else if (CurTy == Type::DoubleTy)
614 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
Chris Lattnere16504e2007-04-24 03:30:34 +0000615 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000616 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000617 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000618
Chris Lattner15e6d172007-05-04 19:11:41 +0000619 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
620 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000621 return Error("Invalid CST_AGGREGATE record");
622
Chris Lattner15e6d172007-05-04 19:11:41 +0000623 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000624 std::vector<Constant*> Elts;
625
626 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
627 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000628 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000629 STy->getElementType(i)));
630 V = ConstantStruct::get(STy, Elts);
631 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
632 const Type *EltTy = ATy->getElementType();
633 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000634 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000635 V = ConstantArray::get(ATy, Elts);
636 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
637 const Type *EltTy = VTy->getElementType();
638 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000639 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000640 V = ConstantVector::get(Elts);
641 } else {
642 V = UndefValue::get(CurTy);
643 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000644 break;
645 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000646 case bitc::CST_CODE_STRING: { // STRING: [values]
647 if (Record.empty())
648 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000649
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000650 const ArrayType *ATy = cast<ArrayType>(CurTy);
651 const Type *EltTy = ATy->getElementType();
652
653 unsigned Size = Record.size();
654 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000655 for (unsigned i = 0; i != Size; ++i)
656 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
657 V = ConstantArray::get(ATy, Elts);
658 break;
659 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000660 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
661 if (Record.empty())
662 return Error("Invalid CST_AGGREGATE record");
663
664 const ArrayType *ATy = cast<ArrayType>(CurTy);
665 const Type *EltTy = ATy->getElementType();
666
667 unsigned Size = Record.size();
668 std::vector<Constant*> Elts;
669 for (unsigned i = 0; i != Size; ++i)
670 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
671 Elts.push_back(Constant::getNullValue(EltTy));
672 V = ConstantArray::get(ATy, Elts);
673 break;
674 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000675 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
676 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
677 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000678 if (Opc < 0) {
679 V = UndefValue::get(CurTy); // Unknown binop.
680 } else {
681 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
682 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
683 V = ConstantExpr::get(Opc, LHS, RHS);
684 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000685 break;
686 }
687 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
688 if (Record.size() < 3) return Error("Invalid CE_CAST record");
689 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000690 if (Opc < 0) {
691 V = UndefValue::get(CurTy); // Unknown cast.
692 } else {
693 const Type *OpTy = getTypeByID(Record[1]);
694 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
695 V = ConstantExpr::getCast(Opc, Op, CurTy);
696 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000697 break;
698 }
699 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000700 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000701 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000702 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000703 const Type *ElTy = getTypeByID(Record[i]);
704 if (!ElTy) return Error("Invalid CE_GEP record");
705 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
706 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000707 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
708 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000709 }
710 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
711 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
712 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
713 Type::Int1Ty),
714 ValueList.getConstantFwdRef(Record[1],CurTy),
715 ValueList.getConstantFwdRef(Record[2],CurTy));
716 break;
717 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
718 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
719 const VectorType *OpTy =
720 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
721 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
722 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
723 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
724 OpTy->getElementType());
725 V = ConstantExpr::getExtractElement(Op0, Op1);
726 break;
727 }
728 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
729 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
730 if (Record.size() < 3 || OpTy == 0)
731 return Error("Invalid CE_INSERTELT record");
732 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
733 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
734 OpTy->getElementType());
735 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
736 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
737 break;
738 }
739 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
740 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
741 if (Record.size() < 3 || OpTy == 0)
742 return Error("Invalid CE_INSERTELT record");
743 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
744 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
745 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
746 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
747 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
748 break;
749 }
750 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
751 if (Record.size() < 4) return Error("Invalid CE_CMP record");
752 const Type *OpTy = getTypeByID(Record[0]);
753 if (OpTy == 0) return Error("Invalid CE_CMP record");
754 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
755 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
756
757 if (OpTy->isFloatingPoint())
758 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
759 else
760 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
761 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000762 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000763 case bitc::CST_CODE_INLINEASM: {
764 if (Record.size() < 2) return Error("Invalid INLINEASM record");
765 std::string AsmStr, ConstrStr;
766 bool HasSideEffects = Record[0];
767 unsigned AsmStrSize = Record[1];
768 if (2+AsmStrSize >= Record.size())
769 return Error("Invalid INLINEASM record");
770 unsigned ConstStrSize = Record[2+AsmStrSize];
771 if (3+AsmStrSize+ConstStrSize > Record.size())
772 return Error("Invalid INLINEASM record");
773
774 for (unsigned i = 0; i != AsmStrSize; ++i)
775 AsmStr += (char)Record[2+i];
776 for (unsigned i = 0; i != ConstStrSize; ++i)
777 ConstrStr += (char)Record[3+AsmStrSize+i];
778 const PointerType *PTy = cast<PointerType>(CurTy);
779 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
780 AsmStr, ConstrStr, HasSideEffects);
781 break;
782 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000783 }
784
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000785 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000786 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000787 }
788}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000789
Chris Lattner980e5aa2007-05-01 05:52:21 +0000790/// RememberAndSkipFunctionBody - When we see the block for a function body,
791/// remember where it is and then skip it. This lets us lazily deserialize the
792/// functions.
793bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000794 // Get the function we are talking about.
795 if (FunctionsWithBodies.empty())
796 return Error("Insufficient function protos");
797
798 Function *Fn = FunctionsWithBodies.back();
799 FunctionsWithBodies.pop_back();
800
801 // Save the current stream state.
802 uint64_t CurBit = Stream.GetCurrentBitNo();
803 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
804
805 // Set the functions linkage to GhostLinkage so we know it is lazily
806 // deserialized.
807 Fn->setLinkage(GlobalValue::GhostLinkage);
808
809 // Skip over the function block for now.
810 if (Stream.SkipBlock())
811 return Error("Malformed block record");
812 return false;
813}
814
Chris Lattner86697142007-05-01 05:01:34 +0000815bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000816 // Reject multiple MODULE_BLOCK's in a single bitstream.
817 if (TheModule)
818 return Error("Multiple MODULE_BLOCKs in same stream");
819
Chris Lattnere17b6582007-05-05 00:17:00 +0000820 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000821 return Error("Malformed block record");
822
823 // Otherwise, create the module.
824 TheModule = new Module(ModuleID);
825
826 SmallVector<uint64_t, 64> Record;
827 std::vector<std::string> SectionTable;
828
829 // Read all the records for this module.
830 while (!Stream.AtEndOfStream()) {
831 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000832 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000833 if (Stream.ReadBlockEnd())
834 return Error("Error at end of module block");
835
836 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000837 ResolveGlobalAndAliasInits();
838 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000839 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000840 if (!FunctionsWithBodies.empty())
841 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000842
843 // Force deallocation of memory for these vectors to favor the client that
844 // want lazy deserialization.
845 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
846 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
847 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000848 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000849 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000850
851 if (Code == bitc::ENTER_SUBBLOCK) {
852 switch (Stream.ReadSubBlockID()) {
853 default: // Skip unknown content.
854 if (Stream.SkipBlock())
855 return Error("Malformed block record");
856 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000857 case bitc::BLOCKINFO_BLOCK_ID:
858 if (Stream.ReadBlockInfoBlock())
859 return Error("Malformed BlockInfoBlock");
860 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000861 case bitc::PARAMATTR_BLOCK_ID:
862 if (ParseParamAttrBlock())
863 return true;
864 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000865 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000866 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000867 return true;
868 break;
869 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000870 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000871 return true;
872 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000873 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000874 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000875 return true;
876 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000877 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000878 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000879 return true;
880 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000881 case bitc::FUNCTION_BLOCK_ID:
882 // If this is the first function body we've seen, reverse the
883 // FunctionsWithBodies list.
884 if (!HasReversedFunctionsWithBodies) {
885 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
886 HasReversedFunctionsWithBodies = true;
887 }
888
Chris Lattner980e5aa2007-05-01 05:52:21 +0000889 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000890 return true;
891 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000892 }
893 continue;
894 }
895
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000896 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000897 Stream.ReadAbbrevRecord();
898 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000899 }
900
901 // Read a record.
902 switch (Stream.ReadRecord(Code, Record)) {
903 default: break; // Default behavior, ignore unknown content.
904 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
905 if (Record.size() < 1)
906 return Error("Malformed MODULE_CODE_VERSION");
907 // Only version #0 is supported so far.
908 if (Record[0] != 0)
909 return Error("Unknown bitstream version!");
910 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000911 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000912 std::string S;
913 if (ConvertToString(Record, 0, S))
914 return Error("Invalid MODULE_CODE_TRIPLE record");
915 TheModule->setTargetTriple(S);
916 break;
917 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000918 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000919 std::string S;
920 if (ConvertToString(Record, 0, S))
921 return Error("Invalid MODULE_CODE_DATALAYOUT record");
922 TheModule->setDataLayout(S);
923 break;
924 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000925 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000926 std::string S;
927 if (ConvertToString(Record, 0, S))
928 return Error("Invalid MODULE_CODE_ASM record");
929 TheModule->setModuleInlineAsm(S);
930 break;
931 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000932 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000933 std::string S;
934 if (ConvertToString(Record, 0, S))
935 return Error("Invalid MODULE_CODE_DEPLIB record");
936 TheModule->addLibrary(S);
937 break;
938 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000939 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000940 std::string S;
941 if (ConvertToString(Record, 0, S))
942 return Error("Invalid MODULE_CODE_SECTIONNAME record");
943 SectionTable.push_back(S);
944 break;
945 }
946 // GLOBALVAR: [type, isconst, initid,
947 // linkage, alignment, section, visibility, threadlocal]
948 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000949 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000950 return Error("Invalid MODULE_CODE_GLOBALVAR record");
951 const Type *Ty = getTypeByID(Record[0]);
952 if (!isa<PointerType>(Ty))
953 return Error("Global not a pointer type!");
954 Ty = cast<PointerType>(Ty)->getElementType();
955
956 bool isConstant = Record[1];
957 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
958 unsigned Alignment = (1 << Record[4]) >> 1;
959 std::string Section;
960 if (Record[5]) {
961 if (Record[5]-1 >= SectionTable.size())
962 return Error("Invalid section ID");
963 Section = SectionTable[Record[5]-1];
964 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000965 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
966 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
967 bool isThreadLocal = false;
968 if (Record.size() >= 7) isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000969
970 GlobalVariable *NewGV =
971 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
972 NewGV->setAlignment(Alignment);
973 if (!Section.empty())
974 NewGV->setSection(Section);
975 NewGV->setVisibility(Visibility);
976 NewGV->setThreadLocal(isThreadLocal);
977
Chris Lattner0b2482a2007-04-23 21:26:05 +0000978 ValueList.push_back(NewGV);
979
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000980 // Remember which value to use for the global initializer.
981 if (unsigned InitID = Record[2])
982 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000983 break;
984 }
985 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
986 // visibility]
987 case bitc::MODULE_CODE_FUNCTION: {
988 if (Record.size() < 7)
989 return Error("Invalid MODULE_CODE_FUNCTION record");
990 const Type *Ty = getTypeByID(Record[0]);
991 if (!isa<PointerType>(Ty))
992 return Error("Function not a pointer type!");
993 const FunctionType *FTy =
994 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
995 if (!FTy)
996 return Error("Function not a pointer to function type!");
997
998 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
999 "", TheModule);
1000
1001 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001002 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001003 Func->setLinkage(GetDecodedLinkage(Record[3]));
1004 Func->setAlignment((1 << Record[4]) >> 1);
1005 if (Record[5]) {
1006 if (Record[5]-1 >= SectionTable.size())
1007 return Error("Invalid section ID");
1008 Func->setSection(SectionTable[Record[5]-1]);
1009 }
1010 Func->setVisibility(GetDecodedVisibility(Record[6]));
1011
Chris Lattner0b2482a2007-04-23 21:26:05 +00001012 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001013
1014 // If this is a function with a body, remember the prototype we are
1015 // creating now, so that we can match up the body with them later.
1016 if (!isProto)
1017 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001018 break;
1019 }
Chris Lattner07d98b42007-04-26 02:46:40 +00001020 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +00001021 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001022 if (Record.size() < 3)
1023 return Error("Invalid MODULE_ALIAS record");
1024 const Type *Ty = getTypeByID(Record[0]);
1025 if (!isa<PointerType>(Ty))
1026 return Error("Function not a pointer type!");
1027
1028 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1029 "", 0, TheModule);
1030 ValueList.push_back(NewGA);
1031 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1032 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001033 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001034 /// MODULE_CODE_PURGEVALS: [numvals]
1035 case bitc::MODULE_CODE_PURGEVALS:
1036 // Trim down the value list to the specified size.
1037 if (Record.size() < 1 || Record[0] > ValueList.size())
1038 return Error("Invalid MODULE_PURGEVALS record");
1039 ValueList.shrinkTo(Record[0]);
1040 break;
1041 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001042 Record.clear();
1043 }
1044
1045 return Error("Premature end of bitstream");
1046}
1047
1048
Chris Lattnerc453f762007-04-29 07:54:31 +00001049bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001050 TheModule = 0;
1051
Chris Lattnerc453f762007-04-29 07:54:31 +00001052 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001053 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1054
Chris Lattnerc453f762007-04-29 07:54:31 +00001055 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001056 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001057
1058 // Sniff for the signature.
1059 if (Stream.Read(8) != 'B' ||
1060 Stream.Read(8) != 'C' ||
1061 Stream.Read(4) != 0x0 ||
1062 Stream.Read(4) != 0xC ||
1063 Stream.Read(4) != 0xE ||
1064 Stream.Read(4) != 0xD)
1065 return Error("Invalid bitcode signature");
1066
1067 // We expect a number of well-defined blocks, though we don't necessarily
1068 // need to understand them all.
1069 while (!Stream.AtEndOfStream()) {
1070 unsigned Code = Stream.ReadCode();
1071
1072 if (Code != bitc::ENTER_SUBBLOCK)
1073 return Error("Invalid record at top-level");
1074
1075 unsigned BlockID = Stream.ReadSubBlockID();
1076
1077 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001078 switch (BlockID) {
1079 case bitc::BLOCKINFO_BLOCK_ID:
1080 if (Stream.ReadBlockInfoBlock())
1081 return Error("Malformed BlockInfoBlock");
1082 break;
1083 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001084 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001085 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001086 break;
1087 default:
1088 if (Stream.SkipBlock())
1089 return Error("Malformed block record");
1090 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001091 }
1092 }
1093
1094 return false;
1095}
Chris Lattnerc453f762007-04-29 07:54:31 +00001096
Chris Lattner48f84872007-05-01 04:59:48 +00001097
1098bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1099 // If it already is material, ignore the request.
1100 if (!F->hasNotBeenReadFromBytecode()) return false;
1101
1102 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1103 DeferredFunctionInfo.find(F);
1104 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1105
1106 // Move the bit stream to the saved position of the deferred function body and
1107 // restore the real linkage type for the function.
1108 Stream.JumpToBit(DFII->second.first);
1109 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1110 DeferredFunctionInfo.erase(DFII);
1111
Chris Lattner980e5aa2007-05-01 05:52:21 +00001112 if (ParseFunctionBody(F)) {
1113 if (ErrInfo) *ErrInfo = ErrorString;
1114 return true;
1115 }
1116
1117 return false;
1118}
1119
1120Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1121 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1122 DeferredFunctionInfo.begin();
1123 while (!DeferredFunctionInfo.empty()) {
1124 Function *F = (*I++).first;
1125 assert(F->hasNotBeenReadFromBytecode() &&
1126 "Deserialized function found in map!");
1127 if (materializeFunction(F, ErrInfo))
1128 return 0;
1129 }
1130 return TheModule;
1131}
1132
1133
1134/// ParseFunctionBody - Lazily parse the specified function body block.
1135bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001136 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001137 return Error("Malformed block record");
1138
1139 unsigned ModuleValueListSize = ValueList.size();
1140
1141 // Add all the function arguments to the value table.
1142 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1143 ValueList.push_back(I);
1144
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001145 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001146 BasicBlock *CurBB = 0;
1147 unsigned CurBBNo = 0;
1148
Chris Lattner980e5aa2007-05-01 05:52:21 +00001149 // Read all the records.
1150 SmallVector<uint64_t, 64> Record;
1151 while (1) {
1152 unsigned Code = Stream.ReadCode();
1153 if (Code == bitc::END_BLOCK) {
1154 if (Stream.ReadBlockEnd())
1155 return Error("Error at end of function block");
1156 break;
1157 }
1158
1159 if (Code == bitc::ENTER_SUBBLOCK) {
1160 switch (Stream.ReadSubBlockID()) {
1161 default: // Skip unknown content.
1162 if (Stream.SkipBlock())
1163 return Error("Malformed block record");
1164 break;
1165 case bitc::CONSTANTS_BLOCK_ID:
1166 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001167 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001168 break;
1169 case bitc::VALUE_SYMTAB_BLOCK_ID:
1170 if (ParseValueSymbolTable()) return true;
1171 break;
1172 }
1173 continue;
1174 }
1175
1176 if (Code == bitc::DEFINE_ABBREV) {
1177 Stream.ReadAbbrevRecord();
1178 continue;
1179 }
1180
1181 // Read a record.
1182 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001183 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001184 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001185 default: // Default behavior: reject
1186 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001187 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001188 if (Record.size() < 1 || Record[0] == 0)
1189 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001190 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001191 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001192 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1193 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001194 CurBB = FunctionBBs[0];
1195 continue;
1196
Chris Lattnerabfbf852007-05-06 00:21:25 +00001197 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1198 unsigned OpNum = 0;
1199 Value *LHS, *RHS;
1200 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1201 getValue(Record, OpNum, LHS->getType(), RHS) ||
1202 OpNum+1 != Record.size())
1203 return Error("Invalid BINOP record");
1204
1205 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1206 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001207 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001208 break;
1209 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001210 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1211 unsigned OpNum = 0;
1212 Value *Op;
1213 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1214 OpNum+2 != Record.size())
1215 return Error("Invalid CAST record");
1216
1217 const Type *ResTy = getTypeByID(Record[OpNum]);
1218 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1219 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001220 return Error("Invalid CAST record");
1221 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1222 break;
1223 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001224 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001225 unsigned OpNum = 0;
1226 Value *BasePtr;
1227 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001228 return Error("Invalid GEP record");
1229
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001230 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001231 while (OpNum != Record.size()) {
1232 Value *Op;
1233 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001234 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001235 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001236 }
1237
Chris Lattner7337ab92007-05-06 00:00:00 +00001238 I = new GetElementPtrInst(BasePtr, &GEPIdx[0], GEPIdx.size());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001239 break;
1240 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001241
Chris Lattnerabfbf852007-05-06 00:21:25 +00001242 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1243 unsigned OpNum = 0;
1244 Value *TrueVal, *FalseVal, *Cond;
1245 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1246 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1247 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001248 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001249
1250 I = new SelectInst(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001251 break;
1252 }
1253
1254 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001255 unsigned OpNum = 0;
1256 Value *Vec, *Idx;
1257 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1258 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001259 return Error("Invalid EXTRACTELT record");
1260 I = new ExtractElementInst(Vec, Idx);
1261 break;
1262 }
1263
1264 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001265 unsigned OpNum = 0;
1266 Value *Vec, *Elt, *Idx;
1267 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1268 getValue(Record, OpNum,
1269 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1270 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001271 return Error("Invalid INSERTELT record");
1272 I = new InsertElementInst(Vec, Elt, Idx);
1273 break;
1274 }
1275
Chris Lattnerabfbf852007-05-06 00:21:25 +00001276 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1277 unsigned OpNum = 0;
1278 Value *Vec1, *Vec2, *Mask;
1279 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1280 getValue(Record, OpNum, Vec1->getType(), Vec2))
1281 return Error("Invalid SHUFFLEVEC record");
1282
1283 const Type *MaskTy =
1284 VectorType::get(Type::Int32Ty,
1285 cast<VectorType>(Vec1->getType())->getNumElements());
1286
1287 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001288 return Error("Invalid SHUFFLEVEC record");
1289 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1290 break;
1291 }
1292
1293 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001294 unsigned OpNum = 0;
1295 Value *LHS, *RHS;
1296 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1297 getValue(Record, OpNum, LHS->getType(), RHS) ||
1298 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001299 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001300
1301 if (LHS->getType()->isFPOrFPVector())
1302 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001303 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001304 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001305 break;
1306 }
1307
Chris Lattner231cbcb2007-05-02 04:27:25 +00001308 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1309 if (Record.size() == 0) {
1310 I = new ReturnInst();
1311 break;
Chris Lattner7337ab92007-05-06 00:00:00 +00001312 } else {
1313 unsigned OpNum = 0;
1314 Value *Op;
1315 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1316 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001317 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001318 I = new ReturnInst(Op);
1319 break;
1320 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001321 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001322 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001323 return Error("Invalid BR record");
1324 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1325 if (TrueDest == 0)
1326 return Error("Invalid BR record");
1327
1328 if (Record.size() == 1)
1329 I = new BranchInst(TrueDest);
1330 else {
1331 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1332 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1333 if (FalseDest == 0 || Cond == 0)
1334 return Error("Invalid BR record");
1335 I = new BranchInst(TrueDest, FalseDest, Cond);
1336 }
1337 break;
1338 }
1339 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1340 if (Record.size() < 3 || (Record.size() & 1) == 0)
1341 return Error("Invalid SWITCH record");
1342 const Type *OpTy = getTypeByID(Record[0]);
1343 Value *Cond = getFnValueByID(Record[1], OpTy);
1344 BasicBlock *Default = getBasicBlock(Record[2]);
1345 if (OpTy == 0 || Cond == 0 || Default == 0)
1346 return Error("Invalid SWITCH record");
1347 unsigned NumCases = (Record.size()-3)/2;
1348 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1349 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1350 ConstantInt *CaseVal =
1351 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1352 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1353 if (CaseVal == 0 || DestBB == 0) {
1354 delete SI;
1355 return Error("Invalid SWITCH record!");
1356 }
1357 SI->addCase(CaseVal, DestBB);
1358 }
1359 I = SI;
1360 break;
1361 }
1362
Chris Lattner76520192007-05-03 22:34:03 +00001363 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
Chris Lattner7337ab92007-05-06 00:00:00 +00001364 if (Record.size() < 3) return Error("Invalid INVOKE record");
Chris Lattner76520192007-05-03 22:34:03 +00001365 unsigned CCInfo = Record[0];
Chris Lattner7337ab92007-05-06 00:00:00 +00001366 BasicBlock *NormalBB = getBasicBlock(Record[1]);
1367 BasicBlock *UnwindBB = getBasicBlock(Record[2]);
1368
1369 unsigned OpNum = 3;
1370 Value *Callee;
1371 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001372 return Error("Invalid INVOKE record");
1373
Chris Lattner7337ab92007-05-06 00:00:00 +00001374 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1375 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001376 dyn_cast<FunctionType>(CalleeTy->getElementType());
1377
1378 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001379 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1380 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001381 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001382
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001383 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001384 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1385 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1386 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001387 }
1388
Chris Lattner7337ab92007-05-06 00:00:00 +00001389 if (!FTy->isVarArg()) {
1390 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001391 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001392 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001393 // Read type/value pairs for varargs params.
1394 while (OpNum != Record.size()) {
1395 Value *Op;
1396 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1397 return Error("Invalid INVOKE record");
1398 Ops.push_back(Op);
1399 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001400 }
1401
1402 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
Chris Lattner76520192007-05-03 22:34:03 +00001403 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001404 break;
1405 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001406 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1407 I = new UnwindInst();
1408 break;
1409 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1410 I = new UnreachableInst();
1411 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001412 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001413 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001414 return Error("Invalid PHI record");
1415 const Type *Ty = getTypeByID(Record[0]);
1416 if (!Ty) return Error("Invalid PHI record");
1417
1418 PHINode *PN = new PHINode(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001419 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001420
Chris Lattner15e6d172007-05-04 19:11:41 +00001421 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1422 Value *V = getFnValueByID(Record[1+i], Ty);
1423 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001424 if (!V || !BB) return Error("Invalid PHI record");
1425 PN->addIncoming(V, BB);
1426 }
1427 I = PN;
1428 break;
1429 }
1430
1431 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1432 if (Record.size() < 3)
1433 return Error("Invalid MALLOC record");
1434 const PointerType *Ty =
1435 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1436 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1437 unsigned Align = Record[2];
1438 if (!Ty || !Size) return Error("Invalid MALLOC record");
1439 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1440 break;
1441 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001442 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1443 unsigned OpNum = 0;
1444 Value *Op;
1445 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1446 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001447 return Error("Invalid FREE record");
1448 I = new FreeInst(Op);
1449 break;
1450 }
1451 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1452 if (Record.size() < 3)
1453 return Error("Invalid ALLOCA record");
1454 const PointerType *Ty =
1455 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1456 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1457 unsigned Align = Record[2];
1458 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1459 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1460 break;
1461 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001462 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001463 unsigned OpNum = 0;
1464 Value *Op;
1465 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1466 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001467 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001468
1469 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001470 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001471 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001472 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1473 unsigned OpNum = 0;
1474 Value *Val, *Ptr;
1475 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1476 getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1477 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001478 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001479
1480 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001481 break;
1482 }
Chris Lattner76520192007-05-03 22:34:03 +00001483 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
Chris Lattner7337ab92007-05-06 00:00:00 +00001484 if (Record.size() < 1)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001485 return Error("Invalid CALL record");
Chris Lattner76520192007-05-03 22:34:03 +00001486 unsigned CCInfo = Record[0];
Chris Lattner7337ab92007-05-06 00:00:00 +00001487
1488 unsigned OpNum = 1;
1489 Value *Callee;
1490 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1491 return Error("Invalid CALL record");
1492
1493 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001494 const FunctionType *FTy = 0;
1495 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001496 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001497 return Error("Invalid CALL record");
1498
1499 SmallVector<Value*, 16> Args;
1500 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001501 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1502 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001503 if (Args.back() == 0) return Error("Invalid CALL record");
1504 }
1505
Chris Lattner0579f7f2007-05-03 22:04:19 +00001506 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001507 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001508 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001509 return Error("Invalid CALL record");
1510 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001511 while (OpNum != Record.size()) {
1512 Value *Op;
1513 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1514 return Error("Invalid CALL record");
1515 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001516 }
1517 }
1518
1519 I = new CallInst(Callee, &Args[0], Args.size());
Chris Lattner76520192007-05-03 22:34:03 +00001520 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1521 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001522 break;
1523 }
1524 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1525 if (Record.size() < 3)
1526 return Error("Invalid VAARG record");
1527 const Type *OpTy = getTypeByID(Record[0]);
1528 Value *Op = getFnValueByID(Record[1], OpTy);
1529 const Type *ResTy = getTypeByID(Record[2]);
1530 if (!OpTy || !Op || !ResTy)
1531 return Error("Invalid VAARG record");
1532 I = new VAArgInst(Op, ResTy);
1533 break;
1534 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001535 }
1536
1537 // Add instruction to end of current BB. If there is no current BB, reject
1538 // this file.
1539 if (CurBB == 0) {
1540 delete I;
1541 return Error("Invalid instruction with no BB");
1542 }
1543 CurBB->getInstList().push_back(I);
1544
1545 // If this was a terminator instruction, move to the next block.
1546 if (isa<TerminatorInst>(I)) {
1547 ++CurBBNo;
1548 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1549 }
1550
1551 // Non-void values get registered in the value table for future use.
1552 if (I && I->getType() != Type::VoidTy)
1553 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001554 }
1555
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001556 // Check the function list for unresolved values.
1557 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1558 if (A->getParent() == 0) {
1559 // We found at least one unresolved value. Nuke them all to avoid leaks.
1560 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1561 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1562 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1563 delete A;
1564 }
1565 }
Chris Lattner35a04702007-05-04 03:50:29 +00001566 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001567 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001568 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001569
1570 // Trim the value list down to the size it was before we parsed this function.
1571 ValueList.shrinkTo(ModuleValueListSize);
1572 std::vector<BasicBlock*>().swap(FunctionBBs);
1573
Chris Lattner48f84872007-05-01 04:59:48 +00001574 return false;
1575}
1576
1577
Chris Lattnerc453f762007-04-29 07:54:31 +00001578//===----------------------------------------------------------------------===//
1579// External interface
1580//===----------------------------------------------------------------------===//
1581
1582/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1583///
1584ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1585 std::string *ErrMsg) {
1586 BitcodeReader *R = new BitcodeReader(Buffer);
1587 if (R->ParseBitcode()) {
1588 if (ErrMsg)
1589 *ErrMsg = R->getErrorString();
1590
1591 // Don't let the BitcodeReader dtor delete 'Buffer'.
1592 R->releaseMemoryBuffer();
1593 delete R;
1594 return 0;
1595 }
1596 return R;
1597}
1598
1599/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1600/// If an error occurs, return null and fill in *ErrMsg if non-null.
1601Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1602 BitcodeReader *R;
1603 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1604 if (!R) return 0;
1605
1606 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1607 // delete it when its dtor is run.
1608 Module *M = R->releaseModule(ErrMsg);
1609
1610 // Don't let the BitcodeReader dtor delete 'Buffer'.
1611 R->releaseMemoryBuffer();
1612 delete R;
1613 return M;
1614}