blob: ee6ed0ab7ece28b9c79fcd594d9903e58e34d686 [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 Lattnerb348bb82007-05-18 04:02:46 +000027void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000028 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000029 Buffer = 0;
30 std::vector<PATypeHolder>().swap(TypeList);
31 ValueList.clear();
32 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
33 std::vector<BasicBlock*>().swap(FunctionBBs);
34 std::vector<Function*>().swap(FunctionsWithBodies);
35 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000036}
37
Chris Lattner48c85b82007-05-04 03:30:17 +000038//===----------------------------------------------------------------------===//
39// Helper functions to implement forward reference resolution, etc.
40//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000041
Chris Lattnercaee0dc2007-04-22 06:23:29 +000042/// ConvertToString - Convert a string from a record into an std::string, return
43/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000044template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000045static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000046 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000047 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000048 return true;
49
Chris Lattner15e6d172007-05-04 19:11:41 +000050 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
51 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000052 return false;
53}
54
55static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
56 switch (Val) {
57 default: // Map unknown/new linkages to external
58 case 0: return GlobalValue::ExternalLinkage;
59 case 1: return GlobalValue::WeakLinkage;
60 case 2: return GlobalValue::AppendingLinkage;
61 case 3: return GlobalValue::InternalLinkage;
62 case 4: return GlobalValue::LinkOnceLinkage;
63 case 5: return GlobalValue::DLLImportLinkage;
64 case 6: return GlobalValue::DLLExportLinkage;
65 case 7: return GlobalValue::ExternalWeakLinkage;
66 }
67}
68
69static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
70 switch (Val) {
71 default: // Map unknown visibilities to default.
72 case 0: return GlobalValue::DefaultVisibility;
73 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000074 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000075 }
76}
77
Chris Lattnerf581c3b2007-04-24 07:07:11 +000078static int GetDecodedCastOpcode(unsigned Val) {
79 switch (Val) {
80 default: return -1;
81 case bitc::CAST_TRUNC : return Instruction::Trunc;
82 case bitc::CAST_ZEXT : return Instruction::ZExt;
83 case bitc::CAST_SEXT : return Instruction::SExt;
84 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
85 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
86 case bitc::CAST_UITOFP : return Instruction::UIToFP;
87 case bitc::CAST_SITOFP : return Instruction::SIToFP;
88 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
89 case bitc::CAST_FPEXT : return Instruction::FPExt;
90 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
91 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
92 case bitc::CAST_BITCAST : return Instruction::BitCast;
93 }
94}
95static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
96 switch (Val) {
97 default: return -1;
98 case bitc::BINOP_ADD: return Instruction::Add;
99 case bitc::BINOP_SUB: return Instruction::Sub;
100 case bitc::BINOP_MUL: return Instruction::Mul;
101 case bitc::BINOP_UDIV: return Instruction::UDiv;
102 case bitc::BINOP_SDIV:
103 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
104 case bitc::BINOP_UREM: return Instruction::URem;
105 case bitc::BINOP_SREM:
106 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
107 case bitc::BINOP_SHL: return Instruction::Shl;
108 case bitc::BINOP_LSHR: return Instruction::LShr;
109 case bitc::BINOP_ASHR: return Instruction::AShr;
110 case bitc::BINOP_AND: return Instruction::And;
111 case bitc::BINOP_OR: return Instruction::Or;
112 case bitc::BINOP_XOR: return Instruction::Xor;
113 }
114}
115
116
Chris Lattner522b7b12007-04-24 05:48:56 +0000117namespace {
118 /// @brief A class for maintaining the slot number definition
119 /// as a placeholder for the actual definition for forward constants defs.
120 class ConstantPlaceHolder : public ConstantExpr {
121 ConstantPlaceHolder(); // DO NOT IMPLEMENT
122 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000123 public:
124 Use Op;
125 ConstantPlaceHolder(const Type *Ty)
126 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
127 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000128 }
129 };
130}
131
132Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
133 const Type *Ty) {
134 if (Idx >= size()) {
135 // Insert a bunch of null values.
136 Uses.resize(Idx+1);
137 OperandList = &Uses[0];
138 NumOperands = Idx+1;
139 }
140
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000141 if (Value *V = Uses[Idx]) {
142 assert(Ty == V->getType() && "Type mismatch in constant table!");
143 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000144 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000145
146 // Create and return a placeholder, which will later be RAUW'd.
147 Constant *C = new ConstantPlaceHolder(Ty);
148 Uses[Idx].init(C, this);
149 return C;
150}
151
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000152Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
153 if (Idx >= size()) {
154 // Insert a bunch of null values.
155 Uses.resize(Idx+1);
156 OperandList = &Uses[0];
157 NumOperands = Idx+1;
158 }
159
160 if (Value *V = Uses[Idx]) {
161 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
162 return V;
163 }
164
Chris Lattner01ff65f2007-05-02 05:16:49 +0000165 // No type specified, must be invalid reference.
166 if (Ty == 0) return 0;
167
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000168 // Create and return a placeholder, which will later be RAUW'd.
169 Value *V = new Argument(Ty);
170 Uses[Idx].init(V, this);
171 return V;
172}
173
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000174
175const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
176 // If the TypeID is in range, return it.
177 if (ID < TypeList.size())
178 return TypeList[ID].get();
179 if (!isTypeTable) return 0;
180
181 // The type table allows forward references. Push as many Opaque types as
182 // needed to get up to ID.
183 while (TypeList.size() <= ID)
184 TypeList.push_back(OpaqueType::get());
185 return TypeList.back().get();
186}
187
Chris Lattner48c85b82007-05-04 03:30:17 +0000188//===----------------------------------------------------------------------===//
189// Functions for parsing blocks from the bitcode file
190//===----------------------------------------------------------------------===//
191
192bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000193 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000194 return Error("Malformed block record");
195
196 if (!ParamAttrs.empty())
197 return Error("Multiple PARAMATTR blocks found!");
198
199 SmallVector<uint64_t, 64> Record;
200
201 ParamAttrsVector Attrs;
202
203 // Read all the records.
204 while (1) {
205 unsigned Code = Stream.ReadCode();
206 if (Code == bitc::END_BLOCK) {
207 if (Stream.ReadBlockEnd())
208 return Error("Error at end of PARAMATTR block");
209 return false;
210 }
211
212 if (Code == bitc::ENTER_SUBBLOCK) {
213 // No known subblocks, always skip them.
214 Stream.ReadSubBlockID();
215 if (Stream.SkipBlock())
216 return Error("Malformed block record");
217 continue;
218 }
219
220 if (Code == bitc::DEFINE_ABBREV) {
221 Stream.ReadAbbrevRecord();
222 continue;
223 }
224
225 // Read a record.
226 Record.clear();
227 switch (Stream.ReadRecord(Code, Record)) {
228 default: // Default behavior: ignore.
229 break;
230 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
231 if (Record.size() & 1)
232 return Error("Invalid ENTRY record");
233
234 ParamAttrsWithIndex PAWI;
235 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
236 PAWI.index = Record[i];
237 PAWI.attrs = Record[i+1];
238 Attrs.push_back(PAWI);
239 }
240 ParamAttrs.push_back(ParamAttrsList::get(Attrs));
241 Attrs.clear();
242 break;
243 }
244 }
245 }
246}
247
248
Chris Lattner86697142007-05-01 05:01:34 +0000249bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000250 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000251 return Error("Malformed block record");
252
253 if (!TypeList.empty())
254 return Error("Multiple TYPE_BLOCKs found!");
255
256 SmallVector<uint64_t, 64> Record;
257 unsigned NumRecords = 0;
258
259 // Read all the records for this type table.
260 while (1) {
261 unsigned Code = Stream.ReadCode();
262 if (Code == bitc::END_BLOCK) {
263 if (NumRecords != TypeList.size())
264 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000265 if (Stream.ReadBlockEnd())
266 return Error("Error at end of type table block");
267 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000268 }
269
270 if (Code == bitc::ENTER_SUBBLOCK) {
271 // No known subblocks, always skip them.
272 Stream.ReadSubBlockID();
273 if (Stream.SkipBlock())
274 return Error("Malformed block record");
275 continue;
276 }
277
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000278 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000279 Stream.ReadAbbrevRecord();
280 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000281 }
282
283 // Read a record.
284 Record.clear();
285 const Type *ResultTy = 0;
286 switch (Stream.ReadRecord(Code, Record)) {
287 default: // Default behavior: unknown type.
288 ResultTy = 0;
289 break;
290 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
291 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
292 // type list. This allows us to reserve space.
293 if (Record.size() < 1)
294 return Error("Invalid TYPE_CODE_NUMENTRY record");
295 TypeList.reserve(Record[0]);
296 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000297 case bitc::TYPE_CODE_VOID: // VOID
298 ResultTy = Type::VoidTy;
299 break;
300 case bitc::TYPE_CODE_FLOAT: // FLOAT
301 ResultTy = Type::FloatTy;
302 break;
303 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
304 ResultTy = Type::DoubleTy;
305 break;
306 case bitc::TYPE_CODE_LABEL: // LABEL
307 ResultTy = Type::LabelTy;
308 break;
309 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
310 ResultTy = 0;
311 break;
312 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
313 if (Record.size() < 1)
314 return Error("Invalid Integer type record");
315
316 ResultTy = IntegerType::get(Record[0]);
317 break;
318 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
319 if (Record.size() < 1)
320 return Error("Invalid POINTER type record");
321 ResultTy = PointerType::get(getTypeByID(Record[0], true));
322 break;
323 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattner15e6d172007-05-04 19:11:41 +0000324 // FUNCTION: [vararg, attrid, retty, paramty x N]
325 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000326 return Error("Invalid FUNCTION type record");
327 std::vector<const Type*> ArgTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000328 for (unsigned i = 3, e = Record.size(); i != e; ++i)
329 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000330
Chris Lattner9113e732007-05-04 03:41:34 +0000331 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
332 Record[0], getParamAttrs(Record[1]));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000333 break;
334 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000335 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000336 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000337 return Error("Invalid STRUCT type record");
338 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000339 for (unsigned i = 1, e = Record.size(); i != e; ++i)
340 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000341 ResultTy = StructType::get(EltTys, Record[0]);
342 break;
343 }
344 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
345 if (Record.size() < 2)
346 return Error("Invalid ARRAY type record");
347 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
348 break;
349 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
350 if (Record.size() < 2)
351 return Error("Invalid VECTOR type record");
352 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
353 break;
354 }
355
356 if (NumRecords == TypeList.size()) {
357 // If this is a new type slot, just append it.
358 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
359 ++NumRecords;
360 } else if (ResultTy == 0) {
361 // Otherwise, this was forward referenced, so an opaque type was created,
362 // but the result type is actually just an opaque. Leave the one we
363 // created previously.
364 ++NumRecords;
365 } else {
366 // Otherwise, this was forward referenced, so an opaque type was created.
367 // Resolve the opaque type to the real type now.
368 assert(NumRecords < TypeList.size() && "Typelist imbalance");
369 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
370
371 // Don't directly push the new type on the Tab. Instead we want to replace
372 // the opaque type we previously inserted with the new concrete value. The
373 // refinement from the abstract (opaque) type to the new type causes all
374 // uses of the abstract type to use the concrete type (NewTy). This will
375 // also cause the opaque type to be deleted.
376 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
377
378 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000379 // value table... or with a preexisting type that was already in the
380 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000381 assert(TypeList[NumRecords-1].get() != OldTy &&
382 "refineAbstractType didn't work!");
383 }
384 }
385}
386
387
Chris Lattner86697142007-05-01 05:01:34 +0000388bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000389 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000390 return Error("Malformed block record");
391
392 SmallVector<uint64_t, 64> Record;
393
394 // Read all the records for this type table.
395 std::string TypeName;
396 while (1) {
397 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000398 if (Code == bitc::END_BLOCK) {
399 if (Stream.ReadBlockEnd())
400 return Error("Error at end of type symbol table block");
401 return false;
402 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000403
404 if (Code == bitc::ENTER_SUBBLOCK) {
405 // No known subblocks, always skip them.
406 Stream.ReadSubBlockID();
407 if (Stream.SkipBlock())
408 return Error("Malformed block record");
409 continue;
410 }
411
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000412 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000413 Stream.ReadAbbrevRecord();
414 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000415 }
416
417 // Read a record.
418 Record.clear();
419 switch (Stream.ReadRecord(Code, Record)) {
420 default: // Default behavior: unknown type.
421 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000422 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000423 if (ConvertToString(Record, 1, TypeName))
424 return Error("Invalid TST_ENTRY record");
425 unsigned TypeID = Record[0];
426 if (TypeID >= TypeList.size())
427 return Error("Invalid Type ID in TST_ENTRY record");
428
429 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
430 TypeName.clear();
431 break;
432 }
433 }
434}
435
Chris Lattner86697142007-05-01 05:01:34 +0000436bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000437 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000438 return Error("Malformed block record");
439
440 SmallVector<uint64_t, 64> Record;
441
442 // Read all the records for this value table.
443 SmallString<128> ValueName;
444 while (1) {
445 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000446 if (Code == bitc::END_BLOCK) {
447 if (Stream.ReadBlockEnd())
448 return Error("Error at end of value symbol table block");
449 return false;
450 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000451 if (Code == bitc::ENTER_SUBBLOCK) {
452 // No known subblocks, always skip them.
453 Stream.ReadSubBlockID();
454 if (Stream.SkipBlock())
455 return Error("Malformed block record");
456 continue;
457 }
458
459 if (Code == bitc::DEFINE_ABBREV) {
460 Stream.ReadAbbrevRecord();
461 continue;
462 }
463
464 // Read a record.
465 Record.clear();
466 switch (Stream.ReadRecord(Code, Record)) {
467 default: // Default behavior: unknown type.
468 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000469 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000470 if (ConvertToString(Record, 1, ValueName))
471 return Error("Invalid TST_ENTRY record");
472 unsigned ValueID = Record[0];
473 if (ValueID >= ValueList.size())
474 return Error("Invalid Value ID in VST_ENTRY record");
475 Value *V = ValueList[ValueID];
476
477 V->setName(&ValueName[0], ValueName.size());
478 ValueName.clear();
479 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000480 }
481 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000482 if (ConvertToString(Record, 1, ValueName))
483 return Error("Invalid VST_BBENTRY record");
484 BasicBlock *BB = getBasicBlock(Record[0]);
485 if (BB == 0)
486 return Error("Invalid BB ID in VST_BBENTRY record");
487
488 BB->setName(&ValueName[0], ValueName.size());
489 ValueName.clear();
490 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000491 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000492 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000493 }
494}
495
Chris Lattner0eef0802007-04-24 04:04:35 +0000496/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
497/// the LSB for dense VBR encoding.
498static uint64_t DecodeSignRotatedValue(uint64_t V) {
499 if ((V & 1) == 0)
500 return V >> 1;
501 if (V != 1)
502 return -(V >> 1);
503 // There is no such thing as -0 with integers. "-0" really means MININT.
504 return 1ULL << 63;
505}
506
Chris Lattner07d98b42007-04-26 02:46:40 +0000507/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
508/// values and aliases that we can.
509bool BitcodeReader::ResolveGlobalAndAliasInits() {
510 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
511 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
512
513 GlobalInitWorklist.swap(GlobalInits);
514 AliasInitWorklist.swap(AliasInits);
515
516 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000517 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000518 if (ValID >= ValueList.size()) {
519 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000520 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000521 } else {
522 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
523 GlobalInitWorklist.back().first->setInitializer(C);
524 else
525 return Error("Global variable initializer is not a constant!");
526 }
527 GlobalInitWorklist.pop_back();
528 }
529
530 while (!AliasInitWorklist.empty()) {
531 unsigned ValID = AliasInitWorklist.back().second;
532 if (ValID >= ValueList.size()) {
533 AliasInits.push_back(AliasInitWorklist.back());
534 } else {
535 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000536 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000537 else
538 return Error("Alias initializer is not a constant!");
539 }
540 AliasInitWorklist.pop_back();
541 }
542 return false;
543}
544
545
Chris Lattner86697142007-05-01 05:01:34 +0000546bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000547 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000548 return Error("Malformed block record");
549
550 SmallVector<uint64_t, 64> Record;
551
552 // Read all the records for this value table.
553 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000554 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000555 while (1) {
556 unsigned Code = Stream.ReadCode();
557 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000558 if (NextCstNo != ValueList.size())
559 return Error("Invalid constant reference!");
560
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000561 if (Stream.ReadBlockEnd())
562 return Error("Error at end of constants block");
563 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000564 }
565
566 if (Code == bitc::ENTER_SUBBLOCK) {
567 // No known subblocks, always skip them.
568 Stream.ReadSubBlockID();
569 if (Stream.SkipBlock())
570 return Error("Malformed block record");
571 continue;
572 }
573
574 if (Code == bitc::DEFINE_ABBREV) {
575 Stream.ReadAbbrevRecord();
576 continue;
577 }
578
579 // Read a record.
580 Record.clear();
581 Value *V = 0;
582 switch (Stream.ReadRecord(Code, Record)) {
583 default: // Default behavior: unknown constant
584 case bitc::CST_CODE_UNDEF: // UNDEF
585 V = UndefValue::get(CurTy);
586 break;
587 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
588 if (Record.empty())
589 return Error("Malformed CST_SETTYPE record");
590 if (Record[0] >= TypeList.size())
591 return Error("Invalid Type ID in CST_SETTYPE record");
592 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000593 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000594 case bitc::CST_CODE_NULL: // NULL
595 V = Constant::getNullValue(CurTy);
596 break;
597 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000598 if (!isa<IntegerType>(CurTy) || Record.empty())
599 return Error("Invalid CST_INTEGER record");
600 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
601 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000602 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
603 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000604 return Error("Invalid WIDE_INTEGER record");
605
Chris Lattner15e6d172007-05-04 19:11:41 +0000606 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000607 SmallVector<uint64_t, 8> Words;
608 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000609 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000610 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000611 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000612 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000613 break;
614 }
615 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
616 if (Record.empty())
617 return Error("Invalid FLOAT record");
618 if (CurTy == Type::FloatTy)
619 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
620 else if (CurTy == Type::DoubleTy)
621 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
Chris Lattnere16504e2007-04-24 03:30:34 +0000622 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000623 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000624 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000625
Chris Lattner15e6d172007-05-04 19:11:41 +0000626 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
627 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000628 return Error("Invalid CST_AGGREGATE record");
629
Chris Lattner15e6d172007-05-04 19:11:41 +0000630 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000631 std::vector<Constant*> Elts;
632
633 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
634 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000635 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000636 STy->getElementType(i)));
637 V = ConstantStruct::get(STy, Elts);
638 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
639 const Type *EltTy = ATy->getElementType();
640 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000641 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000642 V = ConstantArray::get(ATy, Elts);
643 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
644 const Type *EltTy = VTy->getElementType();
645 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000646 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000647 V = ConstantVector::get(Elts);
648 } else {
649 V = UndefValue::get(CurTy);
650 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000651 break;
652 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000653 case bitc::CST_CODE_STRING: { // STRING: [values]
654 if (Record.empty())
655 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000656
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000657 const ArrayType *ATy = cast<ArrayType>(CurTy);
658 const Type *EltTy = ATy->getElementType();
659
660 unsigned Size = Record.size();
661 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000662 for (unsigned i = 0; i != Size; ++i)
663 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
664 V = ConstantArray::get(ATy, Elts);
665 break;
666 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000667 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
668 if (Record.empty())
669 return Error("Invalid CST_AGGREGATE record");
670
671 const ArrayType *ATy = cast<ArrayType>(CurTy);
672 const Type *EltTy = ATy->getElementType();
673
674 unsigned Size = Record.size();
675 std::vector<Constant*> Elts;
676 for (unsigned i = 0; i != Size; ++i)
677 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
678 Elts.push_back(Constant::getNullValue(EltTy));
679 V = ConstantArray::get(ATy, Elts);
680 break;
681 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000682 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
683 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
684 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000685 if (Opc < 0) {
686 V = UndefValue::get(CurTy); // Unknown binop.
687 } else {
688 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
689 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
690 V = ConstantExpr::get(Opc, LHS, RHS);
691 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000692 break;
693 }
694 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
695 if (Record.size() < 3) return Error("Invalid CE_CAST record");
696 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000697 if (Opc < 0) {
698 V = UndefValue::get(CurTy); // Unknown cast.
699 } else {
700 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000701 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000702 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
703 V = ConstantExpr::getCast(Opc, Op, CurTy);
704 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000705 break;
706 }
707 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000708 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000709 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000710 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000711 const Type *ElTy = getTypeByID(Record[i]);
712 if (!ElTy) return Error("Invalid CE_GEP record");
713 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
714 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000715 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
716 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000717 }
718 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
719 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
720 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
721 Type::Int1Ty),
722 ValueList.getConstantFwdRef(Record[1],CurTy),
723 ValueList.getConstantFwdRef(Record[2],CurTy));
724 break;
725 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
726 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
727 const VectorType *OpTy =
728 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
729 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
730 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
731 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
732 OpTy->getElementType());
733 V = ConstantExpr::getExtractElement(Op0, Op1);
734 break;
735 }
736 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
737 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
738 if (Record.size() < 3 || OpTy == 0)
739 return Error("Invalid CE_INSERTELT record");
740 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
741 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
742 OpTy->getElementType());
743 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
744 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
745 break;
746 }
747 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
748 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
749 if (Record.size() < 3 || OpTy == 0)
750 return Error("Invalid CE_INSERTELT record");
751 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
752 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
753 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
754 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
755 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
756 break;
757 }
758 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
759 if (Record.size() < 4) return Error("Invalid CE_CMP record");
760 const Type *OpTy = getTypeByID(Record[0]);
761 if (OpTy == 0) return Error("Invalid CE_CMP record");
762 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
763 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
764
765 if (OpTy->isFloatingPoint())
766 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
767 else
768 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
769 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000770 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000771 case bitc::CST_CODE_INLINEASM: {
772 if (Record.size() < 2) return Error("Invalid INLINEASM record");
773 std::string AsmStr, ConstrStr;
774 bool HasSideEffects = Record[0];
775 unsigned AsmStrSize = Record[1];
776 if (2+AsmStrSize >= Record.size())
777 return Error("Invalid INLINEASM record");
778 unsigned ConstStrSize = Record[2+AsmStrSize];
779 if (3+AsmStrSize+ConstStrSize > Record.size())
780 return Error("Invalid INLINEASM record");
781
782 for (unsigned i = 0; i != AsmStrSize; ++i)
783 AsmStr += (char)Record[2+i];
784 for (unsigned i = 0; i != ConstStrSize; ++i)
785 ConstrStr += (char)Record[3+AsmStrSize+i];
786 const PointerType *PTy = cast<PointerType>(CurTy);
787 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
788 AsmStr, ConstrStr, HasSideEffects);
789 break;
790 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000791 }
792
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000793 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000794 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000795 }
796}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000797
Chris Lattner980e5aa2007-05-01 05:52:21 +0000798/// RememberAndSkipFunctionBody - When we see the block for a function body,
799/// remember where it is and then skip it. This lets us lazily deserialize the
800/// functions.
801bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000802 // Get the function we are talking about.
803 if (FunctionsWithBodies.empty())
804 return Error("Insufficient function protos");
805
806 Function *Fn = FunctionsWithBodies.back();
807 FunctionsWithBodies.pop_back();
808
809 // Save the current stream state.
810 uint64_t CurBit = Stream.GetCurrentBitNo();
811 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
812
813 // Set the functions linkage to GhostLinkage so we know it is lazily
814 // deserialized.
815 Fn->setLinkage(GlobalValue::GhostLinkage);
816
817 // Skip over the function block for now.
818 if (Stream.SkipBlock())
819 return Error("Malformed block record");
820 return false;
821}
822
Chris Lattner86697142007-05-01 05:01:34 +0000823bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000824 // Reject multiple MODULE_BLOCK's in a single bitstream.
825 if (TheModule)
826 return Error("Multiple MODULE_BLOCKs in same stream");
827
Chris Lattnere17b6582007-05-05 00:17:00 +0000828 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000829 return Error("Malformed block record");
830
831 // Otherwise, create the module.
832 TheModule = new Module(ModuleID);
833
834 SmallVector<uint64_t, 64> Record;
835 std::vector<std::string> SectionTable;
836
837 // Read all the records for this module.
838 while (!Stream.AtEndOfStream()) {
839 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000840 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000841 if (Stream.ReadBlockEnd())
842 return Error("Error at end of module block");
843
844 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000845 ResolveGlobalAndAliasInits();
846 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000847 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000848 if (!FunctionsWithBodies.empty())
849 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000850
851 // Force deallocation of memory for these vectors to favor the client that
852 // want lazy deserialization.
853 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
854 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
855 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000856 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000857 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000858
859 if (Code == bitc::ENTER_SUBBLOCK) {
860 switch (Stream.ReadSubBlockID()) {
861 default: // Skip unknown content.
862 if (Stream.SkipBlock())
863 return Error("Malformed block record");
864 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000865 case bitc::BLOCKINFO_BLOCK_ID:
866 if (Stream.ReadBlockInfoBlock())
867 return Error("Malformed BlockInfoBlock");
868 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000869 case bitc::PARAMATTR_BLOCK_ID:
870 if (ParseParamAttrBlock())
871 return true;
872 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000873 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000874 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000875 return true;
876 break;
877 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000878 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000879 return true;
880 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000881 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000882 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000883 return true;
884 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000885 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000886 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000887 return true;
888 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000889 case bitc::FUNCTION_BLOCK_ID:
890 // If this is the first function body we've seen, reverse the
891 // FunctionsWithBodies list.
892 if (!HasReversedFunctionsWithBodies) {
893 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
894 HasReversedFunctionsWithBodies = true;
895 }
896
Chris Lattner980e5aa2007-05-01 05:52:21 +0000897 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000898 return true;
899 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000900 }
901 continue;
902 }
903
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000904 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000905 Stream.ReadAbbrevRecord();
906 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000907 }
908
909 // Read a record.
910 switch (Stream.ReadRecord(Code, Record)) {
911 default: break; // Default behavior, ignore unknown content.
912 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
913 if (Record.size() < 1)
914 return Error("Malformed MODULE_CODE_VERSION");
915 // Only version #0 is supported so far.
916 if (Record[0] != 0)
917 return Error("Unknown bitstream version!");
918 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000919 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000920 std::string S;
921 if (ConvertToString(Record, 0, S))
922 return Error("Invalid MODULE_CODE_TRIPLE record");
923 TheModule->setTargetTriple(S);
924 break;
925 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000926 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000927 std::string S;
928 if (ConvertToString(Record, 0, S))
929 return Error("Invalid MODULE_CODE_DATALAYOUT record");
930 TheModule->setDataLayout(S);
931 break;
932 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000933 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000934 std::string S;
935 if (ConvertToString(Record, 0, S))
936 return Error("Invalid MODULE_CODE_ASM record");
937 TheModule->setModuleInlineAsm(S);
938 break;
939 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000940 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000941 std::string S;
942 if (ConvertToString(Record, 0, S))
943 return Error("Invalid MODULE_CODE_DEPLIB record");
944 TheModule->addLibrary(S);
945 break;
946 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000947 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000948 std::string S;
949 if (ConvertToString(Record, 0, S))
950 return Error("Invalid MODULE_CODE_SECTIONNAME record");
951 SectionTable.push_back(S);
952 break;
953 }
954 // GLOBALVAR: [type, isconst, initid,
955 // linkage, alignment, section, visibility, threadlocal]
956 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000957 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000958 return Error("Invalid MODULE_CODE_GLOBALVAR record");
959 const Type *Ty = getTypeByID(Record[0]);
960 if (!isa<PointerType>(Ty))
961 return Error("Global not a pointer type!");
962 Ty = cast<PointerType>(Ty)->getElementType();
963
964 bool isConstant = Record[1];
965 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
966 unsigned Alignment = (1 << Record[4]) >> 1;
967 std::string Section;
968 if (Record[5]) {
969 if (Record[5]-1 >= SectionTable.size())
970 return Error("Invalid section ID");
971 Section = SectionTable[Record[5]-1];
972 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000973 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +0000974 if (Record.size() > 6)
975 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000976 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +0000977 if (Record.size() > 7)
978 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000979
980 GlobalVariable *NewGV =
981 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
982 NewGV->setAlignment(Alignment);
983 if (!Section.empty())
984 NewGV->setSection(Section);
985 NewGV->setVisibility(Visibility);
986 NewGV->setThreadLocal(isThreadLocal);
987
Chris Lattner0b2482a2007-04-23 21:26:05 +0000988 ValueList.push_back(NewGV);
989
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000990 // Remember which value to use for the global initializer.
991 if (unsigned InitID = Record[2])
992 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000993 break;
994 }
Chris Lattnera9bb7132007-05-08 05:38:01 +0000995 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
996 // alignment, section, visibility]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000997 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +0000998 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000999 return Error("Invalid MODULE_CODE_FUNCTION record");
1000 const Type *Ty = getTypeByID(Record[0]);
1001 if (!isa<PointerType>(Ty))
1002 return Error("Function not a pointer type!");
1003 const FunctionType *FTy =
1004 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1005 if (!FTy)
1006 return Error("Function not a pointer to function type!");
1007
1008 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1009 "", TheModule);
1010
1011 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001012 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001013 Func->setLinkage(GetDecodedLinkage(Record[3]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001014
1015 assert(Func->getFunctionType()->getParamAttrs() ==
1016 getParamAttrs(Record[4]));
1017
1018 Func->setAlignment((1 << Record[5]) >> 1);
1019 if (Record[6]) {
1020 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001021 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001022 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001023 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001024 Func->setVisibility(GetDecodedVisibility(Record[7]));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001025
Chris Lattner0b2482a2007-04-23 21:26:05 +00001026 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001027
1028 // If this is a function with a body, remember the prototype we are
1029 // creating now, so that we can match up the body with them later.
1030 if (!isProto)
1031 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001032 break;
1033 }
Chris Lattner07d98b42007-04-26 02:46:40 +00001034 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +00001035 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001036 if (Record.size() < 3)
1037 return Error("Invalid MODULE_ALIAS record");
1038 const Type *Ty = getTypeByID(Record[0]);
1039 if (!isa<PointerType>(Ty))
1040 return Error("Function not a pointer type!");
1041
1042 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1043 "", 0, TheModule);
1044 ValueList.push_back(NewGA);
1045 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1046 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001047 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001048 /// MODULE_CODE_PURGEVALS: [numvals]
1049 case bitc::MODULE_CODE_PURGEVALS:
1050 // Trim down the value list to the specified size.
1051 if (Record.size() < 1 || Record[0] > ValueList.size())
1052 return Error("Invalid MODULE_PURGEVALS record");
1053 ValueList.shrinkTo(Record[0]);
1054 break;
1055 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001056 Record.clear();
1057 }
1058
1059 return Error("Premature end of bitstream");
1060}
1061
1062
Chris Lattnerc453f762007-04-29 07:54:31 +00001063bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001064 TheModule = 0;
1065
Chris Lattnerc453f762007-04-29 07:54:31 +00001066 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001067 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1068
Chris Lattnerc453f762007-04-29 07:54:31 +00001069 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001070 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001071
1072 // Sniff for the signature.
1073 if (Stream.Read(8) != 'B' ||
1074 Stream.Read(8) != 'C' ||
1075 Stream.Read(4) != 0x0 ||
1076 Stream.Read(4) != 0xC ||
1077 Stream.Read(4) != 0xE ||
1078 Stream.Read(4) != 0xD)
1079 return Error("Invalid bitcode signature");
1080
1081 // We expect a number of well-defined blocks, though we don't necessarily
1082 // need to understand them all.
1083 while (!Stream.AtEndOfStream()) {
1084 unsigned Code = Stream.ReadCode();
1085
1086 if (Code != bitc::ENTER_SUBBLOCK)
1087 return Error("Invalid record at top-level");
1088
1089 unsigned BlockID = Stream.ReadSubBlockID();
1090
1091 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001092 switch (BlockID) {
1093 case bitc::BLOCKINFO_BLOCK_ID:
1094 if (Stream.ReadBlockInfoBlock())
1095 return Error("Malformed BlockInfoBlock");
1096 break;
1097 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001098 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001099 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001100 break;
1101 default:
1102 if (Stream.SkipBlock())
1103 return Error("Malformed block record");
1104 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001105 }
1106 }
1107
1108 return false;
1109}
Chris Lattnerc453f762007-04-29 07:54:31 +00001110
Chris Lattner48f84872007-05-01 04:59:48 +00001111
Chris Lattner980e5aa2007-05-01 05:52:21 +00001112/// ParseFunctionBody - Lazily parse the specified function body block.
1113bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001114 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001115 return Error("Malformed block record");
1116
1117 unsigned ModuleValueListSize = ValueList.size();
1118
1119 // Add all the function arguments to the value table.
1120 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1121 ValueList.push_back(I);
1122
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001123 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001124 BasicBlock *CurBB = 0;
1125 unsigned CurBBNo = 0;
1126
Chris Lattner980e5aa2007-05-01 05:52:21 +00001127 // Read all the records.
1128 SmallVector<uint64_t, 64> Record;
1129 while (1) {
1130 unsigned Code = Stream.ReadCode();
1131 if (Code == bitc::END_BLOCK) {
1132 if (Stream.ReadBlockEnd())
1133 return Error("Error at end of function block");
1134 break;
1135 }
1136
1137 if (Code == bitc::ENTER_SUBBLOCK) {
1138 switch (Stream.ReadSubBlockID()) {
1139 default: // Skip unknown content.
1140 if (Stream.SkipBlock())
1141 return Error("Malformed block record");
1142 break;
1143 case bitc::CONSTANTS_BLOCK_ID:
1144 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001145 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001146 break;
1147 case bitc::VALUE_SYMTAB_BLOCK_ID:
1148 if (ParseValueSymbolTable()) return true;
1149 break;
1150 }
1151 continue;
1152 }
1153
1154 if (Code == bitc::DEFINE_ABBREV) {
1155 Stream.ReadAbbrevRecord();
1156 continue;
1157 }
1158
1159 // Read a record.
1160 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001161 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001162 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001163 default: // Default behavior: reject
1164 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001165 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001166 if (Record.size() < 1 || Record[0] == 0)
1167 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001168 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001169 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001170 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1171 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001172 CurBB = FunctionBBs[0];
1173 continue;
1174
Chris Lattnerabfbf852007-05-06 00:21:25 +00001175 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1176 unsigned OpNum = 0;
1177 Value *LHS, *RHS;
1178 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1179 getValue(Record, OpNum, LHS->getType(), RHS) ||
1180 OpNum+1 != Record.size())
1181 return Error("Invalid BINOP record");
1182
1183 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1184 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001185 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001186 break;
1187 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001188 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1189 unsigned OpNum = 0;
1190 Value *Op;
1191 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1192 OpNum+2 != Record.size())
1193 return Error("Invalid CAST record");
1194
1195 const Type *ResTy = getTypeByID(Record[OpNum]);
1196 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1197 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001198 return Error("Invalid CAST record");
1199 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1200 break;
1201 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001202 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001203 unsigned OpNum = 0;
1204 Value *BasePtr;
1205 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001206 return Error("Invalid GEP record");
1207
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001208 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001209 while (OpNum != Record.size()) {
1210 Value *Op;
1211 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001212 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001213 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001214 }
1215
Chris Lattner7337ab92007-05-06 00:00:00 +00001216 I = new GetElementPtrInst(BasePtr, &GEPIdx[0], GEPIdx.size());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001217 break;
1218 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001219
Chris Lattnerabfbf852007-05-06 00:21:25 +00001220 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1221 unsigned OpNum = 0;
1222 Value *TrueVal, *FalseVal, *Cond;
1223 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1224 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1225 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001226 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001227
1228 I = new SelectInst(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001229 break;
1230 }
1231
1232 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001233 unsigned OpNum = 0;
1234 Value *Vec, *Idx;
1235 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1236 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001237 return Error("Invalid EXTRACTELT record");
1238 I = new ExtractElementInst(Vec, Idx);
1239 break;
1240 }
1241
1242 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001243 unsigned OpNum = 0;
1244 Value *Vec, *Elt, *Idx;
1245 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1246 getValue(Record, OpNum,
1247 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1248 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001249 return Error("Invalid INSERTELT record");
1250 I = new InsertElementInst(Vec, Elt, Idx);
1251 break;
1252 }
1253
Chris Lattnerabfbf852007-05-06 00:21:25 +00001254 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1255 unsigned OpNum = 0;
1256 Value *Vec1, *Vec2, *Mask;
1257 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1258 getValue(Record, OpNum, Vec1->getType(), Vec2))
1259 return Error("Invalid SHUFFLEVEC record");
1260
1261 const Type *MaskTy =
1262 VectorType::get(Type::Int32Ty,
1263 cast<VectorType>(Vec1->getType())->getNumElements());
1264
1265 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001266 return Error("Invalid SHUFFLEVEC record");
1267 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1268 break;
1269 }
1270
1271 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001272 unsigned OpNum = 0;
1273 Value *LHS, *RHS;
1274 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1275 getValue(Record, OpNum, LHS->getType(), RHS) ||
1276 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001277 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001278
1279 if (LHS->getType()->isFPOrFPVector())
1280 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001281 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001282 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001283 break;
1284 }
1285
Chris Lattner231cbcb2007-05-02 04:27:25 +00001286 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1287 if (Record.size() == 0) {
1288 I = new ReturnInst();
1289 break;
Chris Lattner7337ab92007-05-06 00:00:00 +00001290 } else {
1291 unsigned OpNum = 0;
1292 Value *Op;
1293 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1294 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001295 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001296 I = new ReturnInst(Op);
1297 break;
1298 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001299 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001300 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001301 return Error("Invalid BR record");
1302 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1303 if (TrueDest == 0)
1304 return Error("Invalid BR record");
1305
1306 if (Record.size() == 1)
1307 I = new BranchInst(TrueDest);
1308 else {
1309 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1310 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1311 if (FalseDest == 0 || Cond == 0)
1312 return Error("Invalid BR record");
1313 I = new BranchInst(TrueDest, FalseDest, Cond);
1314 }
1315 break;
1316 }
1317 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1318 if (Record.size() < 3 || (Record.size() & 1) == 0)
1319 return Error("Invalid SWITCH record");
1320 const Type *OpTy = getTypeByID(Record[0]);
1321 Value *Cond = getFnValueByID(Record[1], OpTy);
1322 BasicBlock *Default = getBasicBlock(Record[2]);
1323 if (OpTy == 0 || Cond == 0 || Default == 0)
1324 return Error("Invalid SWITCH record");
1325 unsigned NumCases = (Record.size()-3)/2;
1326 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1327 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1328 ConstantInt *CaseVal =
1329 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1330 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1331 if (CaseVal == 0 || DestBB == 0) {
1332 delete SI;
1333 return Error("Invalid SWITCH record!");
1334 }
1335 SI->addCase(CaseVal, DestBB);
1336 }
1337 I = SI;
1338 break;
1339 }
1340
Chris Lattner76520192007-05-03 22:34:03 +00001341 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001342 if (Record.size() < 4) return Error("Invalid INVOKE record");
1343 unsigned CCInfo = Record[1];
1344 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1345 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001346
Chris Lattnera9bb7132007-05-08 05:38:01 +00001347 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001348 Value *Callee;
1349 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001350 return Error("Invalid INVOKE record");
1351
Chris Lattner7337ab92007-05-06 00:00:00 +00001352 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1353 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001354 dyn_cast<FunctionType>(CalleeTy->getElementType());
1355
1356 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001357 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1358 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001359 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001360
Chris Lattnera9bb7132007-05-08 05:38:01 +00001361 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1362
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001363 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001364 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1365 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1366 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001367 }
1368
Chris Lattner7337ab92007-05-06 00:00:00 +00001369 if (!FTy->isVarArg()) {
1370 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001371 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001372 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001373 // Read type/value pairs for varargs params.
1374 while (OpNum != Record.size()) {
1375 Value *Op;
1376 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1377 return Error("Invalid INVOKE record");
1378 Ops.push_back(Op);
1379 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001380 }
1381
1382 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
Chris Lattner76520192007-05-03 22:34:03 +00001383 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001384 break;
1385 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001386 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1387 I = new UnwindInst();
1388 break;
1389 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1390 I = new UnreachableInst();
1391 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001392 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001393 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001394 return Error("Invalid PHI record");
1395 const Type *Ty = getTypeByID(Record[0]);
1396 if (!Ty) return Error("Invalid PHI record");
1397
1398 PHINode *PN = new PHINode(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001399 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001400
Chris Lattner15e6d172007-05-04 19:11:41 +00001401 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1402 Value *V = getFnValueByID(Record[1+i], Ty);
1403 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001404 if (!V || !BB) return Error("Invalid PHI record");
1405 PN->addIncoming(V, BB);
1406 }
1407 I = PN;
1408 break;
1409 }
1410
1411 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1412 if (Record.size() < 3)
1413 return Error("Invalid MALLOC record");
1414 const PointerType *Ty =
1415 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1416 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1417 unsigned Align = Record[2];
1418 if (!Ty || !Size) return Error("Invalid MALLOC record");
1419 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1420 break;
1421 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001422 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1423 unsigned OpNum = 0;
1424 Value *Op;
1425 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1426 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001427 return Error("Invalid FREE record");
1428 I = new FreeInst(Op);
1429 break;
1430 }
1431 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1432 if (Record.size() < 3)
1433 return Error("Invalid ALLOCA 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 ALLOCA record");
1439 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1440 break;
1441 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001442 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001443 unsigned OpNum = 0;
1444 Value *Op;
1445 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1446 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001447 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001448
1449 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001450 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001451 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001452 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1453 unsigned OpNum = 0;
1454 Value *Val, *Ptr;
1455 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1456 getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1457 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001458 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001459
1460 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001461 break;
1462 }
Chris Lattner76520192007-05-03 22:34:03 +00001463 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001464 if (Record.size() < 2)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001465 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001466
Chris Lattnera9bb7132007-05-08 05:38:01 +00001467 unsigned CCInfo = Record[1];
1468
1469 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001470 Value *Callee;
1471 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1472 return Error("Invalid CALL record");
1473
1474 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001475 const FunctionType *FTy = 0;
1476 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001477 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001478 return Error("Invalid CALL record");
1479
Chris Lattnera9bb7132007-05-08 05:38:01 +00001480 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1481
Chris Lattner0579f7f2007-05-03 22:04:19 +00001482 SmallVector<Value*, 16> Args;
1483 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001484 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1485 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001486 if (Args.back() == 0) return Error("Invalid CALL record");
1487 }
1488
Chris Lattner0579f7f2007-05-03 22:04:19 +00001489 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001490 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001491 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001492 return Error("Invalid CALL record");
1493 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001494 while (OpNum != Record.size()) {
1495 Value *Op;
1496 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1497 return Error("Invalid CALL record");
1498 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001499 }
1500 }
1501
David Greene52eec542007-08-01 03:43:44 +00001502 I = new CallInst(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001503 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1504 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001505 break;
1506 }
1507 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1508 if (Record.size() < 3)
1509 return Error("Invalid VAARG record");
1510 const Type *OpTy = getTypeByID(Record[0]);
1511 Value *Op = getFnValueByID(Record[1], OpTy);
1512 const Type *ResTy = getTypeByID(Record[2]);
1513 if (!OpTy || !Op || !ResTy)
1514 return Error("Invalid VAARG record");
1515 I = new VAArgInst(Op, ResTy);
1516 break;
1517 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001518 }
1519
1520 // Add instruction to end of current BB. If there is no current BB, reject
1521 // this file.
1522 if (CurBB == 0) {
1523 delete I;
1524 return Error("Invalid instruction with no BB");
1525 }
1526 CurBB->getInstList().push_back(I);
1527
1528 // If this was a terminator instruction, move to the next block.
1529 if (isa<TerminatorInst>(I)) {
1530 ++CurBBNo;
1531 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1532 }
1533
1534 // Non-void values get registered in the value table for future use.
1535 if (I && I->getType() != Type::VoidTy)
1536 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001537 }
1538
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001539 // Check the function list for unresolved values.
1540 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1541 if (A->getParent() == 0) {
1542 // We found at least one unresolved value. Nuke them all to avoid leaks.
1543 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1544 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1545 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1546 delete A;
1547 }
1548 }
Chris Lattner35a04702007-05-04 03:50:29 +00001549 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001550 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001551 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001552
1553 // Trim the value list down to the size it was before we parsed this function.
1554 ValueList.shrinkTo(ModuleValueListSize);
1555 std::vector<BasicBlock*>().swap(FunctionBBs);
1556
Chris Lattner48f84872007-05-01 04:59:48 +00001557 return false;
1558}
1559
Chris Lattnerb348bb82007-05-18 04:02:46 +00001560//===----------------------------------------------------------------------===//
1561// ModuleProvider implementation
1562//===----------------------------------------------------------------------===//
1563
1564
1565bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1566 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001567 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001568
1569 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1570 DeferredFunctionInfo.find(F);
1571 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1572
1573 // Move the bit stream to the saved position of the deferred function body and
1574 // restore the real linkage type for the function.
1575 Stream.JumpToBit(DFII->second.first);
1576 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1577
1578 if (ParseFunctionBody(F)) {
1579 if (ErrInfo) *ErrInfo = ErrorString;
1580 return true;
1581 }
1582
1583 return false;
1584}
1585
1586void BitcodeReader::dematerializeFunction(Function *F) {
1587 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001588 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001589 return;
1590
1591 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1592
1593 // Just forget the function body, we can remat it later.
1594 F->deleteBody();
1595 F->setLinkage(GlobalValue::GhostLinkage);
1596}
1597
1598
1599Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1600 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1601 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1602 ++I) {
1603 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001604 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001605 materializeFunction(F, ErrInfo))
1606 return 0;
1607 }
1608 return TheModule;
1609}
1610
1611
1612/// This method is provided by the parent ModuleProvde class and overriden
1613/// here. It simply releases the module from its provided and frees up our
1614/// state.
1615/// @brief Release our hold on the generated module
1616Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1617 // Since we're losing control of this Module, we must hand it back complete
1618 Module *M = ModuleProvider::releaseModule(ErrInfo);
1619 FreeState();
1620 return M;
1621}
1622
Chris Lattner48f84872007-05-01 04:59:48 +00001623
Chris Lattnerc453f762007-04-29 07:54:31 +00001624//===----------------------------------------------------------------------===//
1625// External interface
1626//===----------------------------------------------------------------------===//
1627
1628/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1629///
1630ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1631 std::string *ErrMsg) {
1632 BitcodeReader *R = new BitcodeReader(Buffer);
1633 if (R->ParseBitcode()) {
1634 if (ErrMsg)
1635 *ErrMsg = R->getErrorString();
1636
1637 // Don't let the BitcodeReader dtor delete 'Buffer'.
1638 R->releaseMemoryBuffer();
1639 delete R;
1640 return 0;
1641 }
1642 return R;
1643}
1644
1645/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1646/// If an error occurs, return null and fill in *ErrMsg if non-null.
1647Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1648 BitcodeReader *R;
1649 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1650 if (!R) return 0;
1651
Chris Lattnerb348bb82007-05-18 04:02:46 +00001652 // Read in the entire module.
1653 Module *M = R->materializeModule(ErrMsg);
1654
1655 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1656 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001657 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001658
1659 // If there was no error, tell ModuleProvider not to delete it when its dtor
1660 // is run.
1661 if (M)
1662 M = R->releaseModule(ErrMsg);
1663
Chris Lattnerc453f762007-04-29 07:54:31 +00001664 delete R;
1665 return M;
1666}