blob: 9c1f49e865dc298d2ab955f817995149d8a8ff70 [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;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000306 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
307 ResultTy = Type::X86_FP80Ty;
308 break;
309 case bitc::TYPE_CODE_FP128: // FP128
310 ResultTy = Type::FP128Ty;
311 break;
312 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
313 ResultTy = Type::PPC_FP128Ty;
314 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000315 case bitc::TYPE_CODE_LABEL: // LABEL
316 ResultTy = Type::LabelTy;
317 break;
318 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
319 ResultTy = 0;
320 break;
321 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
322 if (Record.size() < 1)
323 return Error("Invalid Integer type record");
324
325 ResultTy = IntegerType::get(Record[0]);
326 break;
327 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
328 if (Record.size() < 1)
329 return Error("Invalid POINTER type record");
330 ResultTy = PointerType::get(getTypeByID(Record[0], true));
331 break;
332 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattner15e6d172007-05-04 19:11:41 +0000333 // FUNCTION: [vararg, attrid, retty, paramty x N]
334 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000335 return Error("Invalid FUNCTION type record");
336 std::vector<const Type*> ArgTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000337 for (unsigned i = 3, e = Record.size(); i != e; ++i)
338 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000339
Chris Lattner9113e732007-05-04 03:41:34 +0000340 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
341 Record[0], getParamAttrs(Record[1]));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000342 break;
343 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000344 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000345 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000346 return Error("Invalid STRUCT type record");
347 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000348 for (unsigned i = 1, e = Record.size(); i != e; ++i)
349 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000350 ResultTy = StructType::get(EltTys, Record[0]);
351 break;
352 }
353 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
354 if (Record.size() < 2)
355 return Error("Invalid ARRAY type record");
356 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
357 break;
358 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
359 if (Record.size() < 2)
360 return Error("Invalid VECTOR type record");
361 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
362 break;
363 }
364
365 if (NumRecords == TypeList.size()) {
366 // If this is a new type slot, just append it.
367 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
368 ++NumRecords;
369 } else if (ResultTy == 0) {
370 // Otherwise, this was forward referenced, so an opaque type was created,
371 // but the result type is actually just an opaque. Leave the one we
372 // created previously.
373 ++NumRecords;
374 } else {
375 // Otherwise, this was forward referenced, so an opaque type was created.
376 // Resolve the opaque type to the real type now.
377 assert(NumRecords < TypeList.size() && "Typelist imbalance");
378 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
379
380 // Don't directly push the new type on the Tab. Instead we want to replace
381 // the opaque type we previously inserted with the new concrete value. The
382 // refinement from the abstract (opaque) type to the new type causes all
383 // uses of the abstract type to use the concrete type (NewTy). This will
384 // also cause the opaque type to be deleted.
385 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
386
387 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000388 // value table... or with a preexisting type that was already in the
389 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000390 assert(TypeList[NumRecords-1].get() != OldTy &&
391 "refineAbstractType didn't work!");
392 }
393 }
394}
395
396
Chris Lattner86697142007-05-01 05:01:34 +0000397bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000398 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000399 return Error("Malformed block record");
400
401 SmallVector<uint64_t, 64> Record;
402
403 // Read all the records for this type table.
404 std::string TypeName;
405 while (1) {
406 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000407 if (Code == bitc::END_BLOCK) {
408 if (Stream.ReadBlockEnd())
409 return Error("Error at end of type symbol table block");
410 return false;
411 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000412
413 if (Code == bitc::ENTER_SUBBLOCK) {
414 // No known subblocks, always skip them.
415 Stream.ReadSubBlockID();
416 if (Stream.SkipBlock())
417 return Error("Malformed block record");
418 continue;
419 }
420
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000421 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000422 Stream.ReadAbbrevRecord();
423 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000424 }
425
426 // Read a record.
427 Record.clear();
428 switch (Stream.ReadRecord(Code, Record)) {
429 default: // Default behavior: unknown type.
430 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000431 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000432 if (ConvertToString(Record, 1, TypeName))
433 return Error("Invalid TST_ENTRY record");
434 unsigned TypeID = Record[0];
435 if (TypeID >= TypeList.size())
436 return Error("Invalid Type ID in TST_ENTRY record");
437
438 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
439 TypeName.clear();
440 break;
441 }
442 }
443}
444
Chris Lattner86697142007-05-01 05:01:34 +0000445bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000446 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000447 return Error("Malformed block record");
448
449 SmallVector<uint64_t, 64> Record;
450
451 // Read all the records for this value table.
452 SmallString<128> ValueName;
453 while (1) {
454 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000455 if (Code == bitc::END_BLOCK) {
456 if (Stream.ReadBlockEnd())
457 return Error("Error at end of value symbol table block");
458 return false;
459 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000460 if (Code == bitc::ENTER_SUBBLOCK) {
461 // No known subblocks, always skip them.
462 Stream.ReadSubBlockID();
463 if (Stream.SkipBlock())
464 return Error("Malformed block record");
465 continue;
466 }
467
468 if (Code == bitc::DEFINE_ABBREV) {
469 Stream.ReadAbbrevRecord();
470 continue;
471 }
472
473 // Read a record.
474 Record.clear();
475 switch (Stream.ReadRecord(Code, Record)) {
476 default: // Default behavior: unknown type.
477 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000478 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000479 if (ConvertToString(Record, 1, ValueName))
480 return Error("Invalid TST_ENTRY record");
481 unsigned ValueID = Record[0];
482 if (ValueID >= ValueList.size())
483 return Error("Invalid Value ID in VST_ENTRY record");
484 Value *V = ValueList[ValueID];
485
486 V->setName(&ValueName[0], ValueName.size());
487 ValueName.clear();
488 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000489 }
490 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000491 if (ConvertToString(Record, 1, ValueName))
492 return Error("Invalid VST_BBENTRY record");
493 BasicBlock *BB = getBasicBlock(Record[0]);
494 if (BB == 0)
495 return Error("Invalid BB ID in VST_BBENTRY record");
496
497 BB->setName(&ValueName[0], ValueName.size());
498 ValueName.clear();
499 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000500 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000501 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000502 }
503}
504
Chris Lattner0eef0802007-04-24 04:04:35 +0000505/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
506/// the LSB for dense VBR encoding.
507static uint64_t DecodeSignRotatedValue(uint64_t V) {
508 if ((V & 1) == 0)
509 return V >> 1;
510 if (V != 1)
511 return -(V >> 1);
512 // There is no such thing as -0 with integers. "-0" really means MININT.
513 return 1ULL << 63;
514}
515
Chris Lattner07d98b42007-04-26 02:46:40 +0000516/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
517/// values and aliases that we can.
518bool BitcodeReader::ResolveGlobalAndAliasInits() {
519 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
520 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
521
522 GlobalInitWorklist.swap(GlobalInits);
523 AliasInitWorklist.swap(AliasInits);
524
525 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000526 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000527 if (ValID >= ValueList.size()) {
528 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000529 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000530 } else {
531 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
532 GlobalInitWorklist.back().first->setInitializer(C);
533 else
534 return Error("Global variable initializer is not a constant!");
535 }
536 GlobalInitWorklist.pop_back();
537 }
538
539 while (!AliasInitWorklist.empty()) {
540 unsigned ValID = AliasInitWorklist.back().second;
541 if (ValID >= ValueList.size()) {
542 AliasInits.push_back(AliasInitWorklist.back());
543 } else {
544 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000545 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000546 else
547 return Error("Alias initializer is not a constant!");
548 }
549 AliasInitWorklist.pop_back();
550 }
551 return false;
552}
553
554
Chris Lattner86697142007-05-01 05:01:34 +0000555bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000556 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000557 return Error("Malformed block record");
558
559 SmallVector<uint64_t, 64> Record;
560
561 // Read all the records for this value table.
562 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000563 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000564 while (1) {
565 unsigned Code = Stream.ReadCode();
566 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000567 if (NextCstNo != ValueList.size())
568 return Error("Invalid constant reference!");
569
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000570 if (Stream.ReadBlockEnd())
571 return Error("Error at end of constants block");
572 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000573 }
574
575 if (Code == bitc::ENTER_SUBBLOCK) {
576 // No known subblocks, always skip them.
577 Stream.ReadSubBlockID();
578 if (Stream.SkipBlock())
579 return Error("Malformed block record");
580 continue;
581 }
582
583 if (Code == bitc::DEFINE_ABBREV) {
584 Stream.ReadAbbrevRecord();
585 continue;
586 }
587
588 // Read a record.
589 Record.clear();
590 Value *V = 0;
591 switch (Stream.ReadRecord(Code, Record)) {
592 default: // Default behavior: unknown constant
593 case bitc::CST_CODE_UNDEF: // UNDEF
594 V = UndefValue::get(CurTy);
595 break;
596 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
597 if (Record.empty())
598 return Error("Malformed CST_SETTYPE record");
599 if (Record[0] >= TypeList.size())
600 return Error("Invalid Type ID in CST_SETTYPE record");
601 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000602 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000603 case bitc::CST_CODE_NULL: // NULL
604 V = Constant::getNullValue(CurTy);
605 break;
606 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000607 if (!isa<IntegerType>(CurTy) || Record.empty())
608 return Error("Invalid CST_INTEGER record");
609 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
610 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000611 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
612 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000613 return Error("Invalid WIDE_INTEGER record");
614
Chris Lattner15e6d172007-05-04 19:11:41 +0000615 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000616 SmallVector<uint64_t, 8> Words;
617 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000618 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000619 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000620 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000621 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000622 break;
623 }
624 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
625 if (Record.empty())
626 return Error("Invalid FLOAT record");
627 if (CurTy == Type::FloatTy)
628 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
629 else if (CurTy == Type::DoubleTy)
630 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
Chris Lattnere16504e2007-04-24 03:30:34 +0000631 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000632 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000633 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000634
Chris Lattner15e6d172007-05-04 19:11:41 +0000635 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
636 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000637 return Error("Invalid CST_AGGREGATE record");
638
Chris Lattner15e6d172007-05-04 19:11:41 +0000639 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000640 std::vector<Constant*> Elts;
641
642 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
643 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000644 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000645 STy->getElementType(i)));
646 V = ConstantStruct::get(STy, Elts);
647 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
648 const Type *EltTy = ATy->getElementType();
649 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000650 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000651 V = ConstantArray::get(ATy, Elts);
652 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
653 const Type *EltTy = VTy->getElementType();
654 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000655 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000656 V = ConstantVector::get(Elts);
657 } else {
658 V = UndefValue::get(CurTy);
659 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000660 break;
661 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000662 case bitc::CST_CODE_STRING: { // STRING: [values]
663 if (Record.empty())
664 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000665
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000666 const ArrayType *ATy = cast<ArrayType>(CurTy);
667 const Type *EltTy = ATy->getElementType();
668
669 unsigned Size = Record.size();
670 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000671 for (unsigned i = 0; i != Size; ++i)
672 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
673 V = ConstantArray::get(ATy, Elts);
674 break;
675 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000676 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
677 if (Record.empty())
678 return Error("Invalid CST_AGGREGATE record");
679
680 const ArrayType *ATy = cast<ArrayType>(CurTy);
681 const Type *EltTy = ATy->getElementType();
682
683 unsigned Size = Record.size();
684 std::vector<Constant*> Elts;
685 for (unsigned i = 0; i != Size; ++i)
686 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
687 Elts.push_back(Constant::getNullValue(EltTy));
688 V = ConstantArray::get(ATy, Elts);
689 break;
690 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000691 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
692 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
693 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000694 if (Opc < 0) {
695 V = UndefValue::get(CurTy); // Unknown binop.
696 } else {
697 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
698 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
699 V = ConstantExpr::get(Opc, LHS, RHS);
700 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000701 break;
702 }
703 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
704 if (Record.size() < 3) return Error("Invalid CE_CAST record");
705 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000706 if (Opc < 0) {
707 V = UndefValue::get(CurTy); // Unknown cast.
708 } else {
709 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000710 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000711 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
712 V = ConstantExpr::getCast(Opc, Op, CurTy);
713 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000714 break;
715 }
716 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000717 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000718 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000719 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000720 const Type *ElTy = getTypeByID(Record[i]);
721 if (!ElTy) return Error("Invalid CE_GEP record");
722 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
723 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000724 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
725 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000726 }
727 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
728 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
729 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
730 Type::Int1Ty),
731 ValueList.getConstantFwdRef(Record[1],CurTy),
732 ValueList.getConstantFwdRef(Record[2],CurTy));
733 break;
734 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
735 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
736 const VectorType *OpTy =
737 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
738 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
739 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
740 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
741 OpTy->getElementType());
742 V = ConstantExpr::getExtractElement(Op0, Op1);
743 break;
744 }
745 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
746 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
747 if (Record.size() < 3 || OpTy == 0)
748 return Error("Invalid CE_INSERTELT record");
749 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
750 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
751 OpTy->getElementType());
752 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
753 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
754 break;
755 }
756 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
757 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
758 if (Record.size() < 3 || OpTy == 0)
759 return Error("Invalid CE_INSERTELT record");
760 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
761 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
762 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
763 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
764 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
765 break;
766 }
767 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
768 if (Record.size() < 4) return Error("Invalid CE_CMP record");
769 const Type *OpTy = getTypeByID(Record[0]);
770 if (OpTy == 0) return Error("Invalid CE_CMP record");
771 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
772 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
773
774 if (OpTy->isFloatingPoint())
775 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
776 else
777 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
778 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000779 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000780 case bitc::CST_CODE_INLINEASM: {
781 if (Record.size() < 2) return Error("Invalid INLINEASM record");
782 std::string AsmStr, ConstrStr;
783 bool HasSideEffects = Record[0];
784 unsigned AsmStrSize = Record[1];
785 if (2+AsmStrSize >= Record.size())
786 return Error("Invalid INLINEASM record");
787 unsigned ConstStrSize = Record[2+AsmStrSize];
788 if (3+AsmStrSize+ConstStrSize > Record.size())
789 return Error("Invalid INLINEASM record");
790
791 for (unsigned i = 0; i != AsmStrSize; ++i)
792 AsmStr += (char)Record[2+i];
793 for (unsigned i = 0; i != ConstStrSize; ++i)
794 ConstrStr += (char)Record[3+AsmStrSize+i];
795 const PointerType *PTy = cast<PointerType>(CurTy);
796 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
797 AsmStr, ConstrStr, HasSideEffects);
798 break;
799 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000800 }
801
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000802 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000803 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000804 }
805}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000806
Chris Lattner980e5aa2007-05-01 05:52:21 +0000807/// RememberAndSkipFunctionBody - When we see the block for a function body,
808/// remember where it is and then skip it. This lets us lazily deserialize the
809/// functions.
810bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000811 // Get the function we are talking about.
812 if (FunctionsWithBodies.empty())
813 return Error("Insufficient function protos");
814
815 Function *Fn = FunctionsWithBodies.back();
816 FunctionsWithBodies.pop_back();
817
818 // Save the current stream state.
819 uint64_t CurBit = Stream.GetCurrentBitNo();
820 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
821
822 // Set the functions linkage to GhostLinkage so we know it is lazily
823 // deserialized.
824 Fn->setLinkage(GlobalValue::GhostLinkage);
825
826 // Skip over the function block for now.
827 if (Stream.SkipBlock())
828 return Error("Malformed block record");
829 return false;
830}
831
Chris Lattner86697142007-05-01 05:01:34 +0000832bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000833 // Reject multiple MODULE_BLOCK's in a single bitstream.
834 if (TheModule)
835 return Error("Multiple MODULE_BLOCKs in same stream");
836
Chris Lattnere17b6582007-05-05 00:17:00 +0000837 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000838 return Error("Malformed block record");
839
840 // Otherwise, create the module.
841 TheModule = new Module(ModuleID);
842
843 SmallVector<uint64_t, 64> Record;
844 std::vector<std::string> SectionTable;
845
846 // Read all the records for this module.
847 while (!Stream.AtEndOfStream()) {
848 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000849 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000850 if (Stream.ReadBlockEnd())
851 return Error("Error at end of module block");
852
853 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000854 ResolveGlobalAndAliasInits();
855 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000856 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000857 if (!FunctionsWithBodies.empty())
858 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000859
860 // Force deallocation of memory for these vectors to favor the client that
861 // want lazy deserialization.
862 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
863 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
864 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000865 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000866 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000867
868 if (Code == bitc::ENTER_SUBBLOCK) {
869 switch (Stream.ReadSubBlockID()) {
870 default: // Skip unknown content.
871 if (Stream.SkipBlock())
872 return Error("Malformed block record");
873 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000874 case bitc::BLOCKINFO_BLOCK_ID:
875 if (Stream.ReadBlockInfoBlock())
876 return Error("Malformed BlockInfoBlock");
877 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000878 case bitc::PARAMATTR_BLOCK_ID:
879 if (ParseParamAttrBlock())
880 return true;
881 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000882 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000883 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000884 return true;
885 break;
886 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000887 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000888 return true;
889 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000890 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000891 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000892 return true;
893 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000894 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000895 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000896 return true;
897 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000898 case bitc::FUNCTION_BLOCK_ID:
899 // If this is the first function body we've seen, reverse the
900 // FunctionsWithBodies list.
901 if (!HasReversedFunctionsWithBodies) {
902 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
903 HasReversedFunctionsWithBodies = true;
904 }
905
Chris Lattner980e5aa2007-05-01 05:52:21 +0000906 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000907 return true;
908 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000909 }
910 continue;
911 }
912
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000913 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000914 Stream.ReadAbbrevRecord();
915 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000916 }
917
918 // Read a record.
919 switch (Stream.ReadRecord(Code, Record)) {
920 default: break; // Default behavior, ignore unknown content.
921 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
922 if (Record.size() < 1)
923 return Error("Malformed MODULE_CODE_VERSION");
924 // Only version #0 is supported so far.
925 if (Record[0] != 0)
926 return Error("Unknown bitstream version!");
927 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000928 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000929 std::string S;
930 if (ConvertToString(Record, 0, S))
931 return Error("Invalid MODULE_CODE_TRIPLE record");
932 TheModule->setTargetTriple(S);
933 break;
934 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000935 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000936 std::string S;
937 if (ConvertToString(Record, 0, S))
938 return Error("Invalid MODULE_CODE_DATALAYOUT record");
939 TheModule->setDataLayout(S);
940 break;
941 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000942 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000943 std::string S;
944 if (ConvertToString(Record, 0, S))
945 return Error("Invalid MODULE_CODE_ASM record");
946 TheModule->setModuleInlineAsm(S);
947 break;
948 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000949 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000950 std::string S;
951 if (ConvertToString(Record, 0, S))
952 return Error("Invalid MODULE_CODE_DEPLIB record");
953 TheModule->addLibrary(S);
954 break;
955 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000956 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000957 std::string S;
958 if (ConvertToString(Record, 0, S))
959 return Error("Invalid MODULE_CODE_SECTIONNAME record");
960 SectionTable.push_back(S);
961 break;
962 }
963 // GLOBALVAR: [type, isconst, initid,
964 // linkage, alignment, section, visibility, threadlocal]
965 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000966 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000967 return Error("Invalid MODULE_CODE_GLOBALVAR record");
968 const Type *Ty = getTypeByID(Record[0]);
969 if (!isa<PointerType>(Ty))
970 return Error("Global not a pointer type!");
971 Ty = cast<PointerType>(Ty)->getElementType();
972
973 bool isConstant = Record[1];
974 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
975 unsigned Alignment = (1 << Record[4]) >> 1;
976 std::string Section;
977 if (Record[5]) {
978 if (Record[5]-1 >= SectionTable.size())
979 return Error("Invalid section ID");
980 Section = SectionTable[Record[5]-1];
981 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000982 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +0000983 if (Record.size() > 6)
984 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000985 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +0000986 if (Record.size() > 7)
987 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000988
989 GlobalVariable *NewGV =
990 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
991 NewGV->setAlignment(Alignment);
992 if (!Section.empty())
993 NewGV->setSection(Section);
994 NewGV->setVisibility(Visibility);
995 NewGV->setThreadLocal(isThreadLocal);
996
Chris Lattner0b2482a2007-04-23 21:26:05 +0000997 ValueList.push_back(NewGV);
998
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000999 // Remember which value to use for the global initializer.
1000 if (unsigned InitID = Record[2])
1001 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001002 break;
1003 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001004 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1005 // alignment, section, visibility]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001006 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001007 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001008 return Error("Invalid MODULE_CODE_FUNCTION record");
1009 const Type *Ty = getTypeByID(Record[0]);
1010 if (!isa<PointerType>(Ty))
1011 return Error("Function not a pointer type!");
1012 const FunctionType *FTy =
1013 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1014 if (!FTy)
1015 return Error("Function not a pointer to function type!");
1016
1017 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1018 "", TheModule);
1019
1020 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001021 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001022 Func->setLinkage(GetDecodedLinkage(Record[3]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001023
1024 assert(Func->getFunctionType()->getParamAttrs() ==
1025 getParamAttrs(Record[4]));
1026
1027 Func->setAlignment((1 << Record[5]) >> 1);
1028 if (Record[6]) {
1029 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001030 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001031 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001032 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001033 Func->setVisibility(GetDecodedVisibility(Record[7]));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001034
Chris Lattner0b2482a2007-04-23 21:26:05 +00001035 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001036
1037 // If this is a function with a body, remember the prototype we are
1038 // creating now, so that we can match up the body with them later.
1039 if (!isProto)
1040 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001041 break;
1042 }
Chris Lattner07d98b42007-04-26 02:46:40 +00001043 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +00001044 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001045 if (Record.size() < 3)
1046 return Error("Invalid MODULE_ALIAS record");
1047 const Type *Ty = getTypeByID(Record[0]);
1048 if (!isa<PointerType>(Ty))
1049 return Error("Function not a pointer type!");
1050
1051 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1052 "", 0, TheModule);
1053 ValueList.push_back(NewGA);
1054 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1055 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001056 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001057 /// MODULE_CODE_PURGEVALS: [numvals]
1058 case bitc::MODULE_CODE_PURGEVALS:
1059 // Trim down the value list to the specified size.
1060 if (Record.size() < 1 || Record[0] > ValueList.size())
1061 return Error("Invalid MODULE_PURGEVALS record");
1062 ValueList.shrinkTo(Record[0]);
1063 break;
1064 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001065 Record.clear();
1066 }
1067
1068 return Error("Premature end of bitstream");
1069}
1070
1071
Chris Lattnerc453f762007-04-29 07:54:31 +00001072bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001073 TheModule = 0;
1074
Chris Lattnerc453f762007-04-29 07:54:31 +00001075 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001076 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1077
Chris Lattnerc453f762007-04-29 07:54:31 +00001078 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001079 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001080
1081 // Sniff for the signature.
1082 if (Stream.Read(8) != 'B' ||
1083 Stream.Read(8) != 'C' ||
1084 Stream.Read(4) != 0x0 ||
1085 Stream.Read(4) != 0xC ||
1086 Stream.Read(4) != 0xE ||
1087 Stream.Read(4) != 0xD)
1088 return Error("Invalid bitcode signature");
1089
1090 // We expect a number of well-defined blocks, though we don't necessarily
1091 // need to understand them all.
1092 while (!Stream.AtEndOfStream()) {
1093 unsigned Code = Stream.ReadCode();
1094
1095 if (Code != bitc::ENTER_SUBBLOCK)
1096 return Error("Invalid record at top-level");
1097
1098 unsigned BlockID = Stream.ReadSubBlockID();
1099
1100 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001101 switch (BlockID) {
1102 case bitc::BLOCKINFO_BLOCK_ID:
1103 if (Stream.ReadBlockInfoBlock())
1104 return Error("Malformed BlockInfoBlock");
1105 break;
1106 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001107 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001108 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001109 break;
1110 default:
1111 if (Stream.SkipBlock())
1112 return Error("Malformed block record");
1113 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001114 }
1115 }
1116
1117 return false;
1118}
Chris Lattnerc453f762007-04-29 07:54:31 +00001119
Chris Lattner48f84872007-05-01 04:59:48 +00001120
Chris Lattner980e5aa2007-05-01 05:52:21 +00001121/// ParseFunctionBody - Lazily parse the specified function body block.
1122bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001123 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001124 return Error("Malformed block record");
1125
1126 unsigned ModuleValueListSize = ValueList.size();
1127
1128 // Add all the function arguments to the value table.
1129 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1130 ValueList.push_back(I);
1131
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001132 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001133 BasicBlock *CurBB = 0;
1134 unsigned CurBBNo = 0;
1135
Chris Lattner980e5aa2007-05-01 05:52:21 +00001136 // Read all the records.
1137 SmallVector<uint64_t, 64> Record;
1138 while (1) {
1139 unsigned Code = Stream.ReadCode();
1140 if (Code == bitc::END_BLOCK) {
1141 if (Stream.ReadBlockEnd())
1142 return Error("Error at end of function block");
1143 break;
1144 }
1145
1146 if (Code == bitc::ENTER_SUBBLOCK) {
1147 switch (Stream.ReadSubBlockID()) {
1148 default: // Skip unknown content.
1149 if (Stream.SkipBlock())
1150 return Error("Malformed block record");
1151 break;
1152 case bitc::CONSTANTS_BLOCK_ID:
1153 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001154 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001155 break;
1156 case bitc::VALUE_SYMTAB_BLOCK_ID:
1157 if (ParseValueSymbolTable()) return true;
1158 break;
1159 }
1160 continue;
1161 }
1162
1163 if (Code == bitc::DEFINE_ABBREV) {
1164 Stream.ReadAbbrevRecord();
1165 continue;
1166 }
1167
1168 // Read a record.
1169 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001170 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001171 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001172 default: // Default behavior: reject
1173 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001174 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001175 if (Record.size() < 1 || Record[0] == 0)
1176 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001177 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001178 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001179 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1180 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001181 CurBB = FunctionBBs[0];
1182 continue;
1183
Chris Lattnerabfbf852007-05-06 00:21:25 +00001184 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1185 unsigned OpNum = 0;
1186 Value *LHS, *RHS;
1187 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1188 getValue(Record, OpNum, LHS->getType(), RHS) ||
1189 OpNum+1 != Record.size())
1190 return Error("Invalid BINOP record");
1191
1192 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1193 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001194 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001195 break;
1196 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001197 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1198 unsigned OpNum = 0;
1199 Value *Op;
1200 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1201 OpNum+2 != Record.size())
1202 return Error("Invalid CAST record");
1203
1204 const Type *ResTy = getTypeByID(Record[OpNum]);
1205 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1206 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001207 return Error("Invalid CAST record");
1208 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1209 break;
1210 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001211 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001212 unsigned OpNum = 0;
1213 Value *BasePtr;
1214 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001215 return Error("Invalid GEP record");
1216
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001217 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001218 while (OpNum != Record.size()) {
1219 Value *Op;
1220 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001221 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001222 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001223 }
1224
Chris Lattner7337ab92007-05-06 00:00:00 +00001225 I = new GetElementPtrInst(BasePtr, &GEPIdx[0], GEPIdx.size());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001226 break;
1227 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001228
Chris Lattnerabfbf852007-05-06 00:21:25 +00001229 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1230 unsigned OpNum = 0;
1231 Value *TrueVal, *FalseVal, *Cond;
1232 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1233 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1234 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001235 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001236
1237 I = new SelectInst(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001238 break;
1239 }
1240
1241 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001242 unsigned OpNum = 0;
1243 Value *Vec, *Idx;
1244 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1245 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001246 return Error("Invalid EXTRACTELT record");
1247 I = new ExtractElementInst(Vec, Idx);
1248 break;
1249 }
1250
1251 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001252 unsigned OpNum = 0;
1253 Value *Vec, *Elt, *Idx;
1254 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1255 getValue(Record, OpNum,
1256 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1257 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001258 return Error("Invalid INSERTELT record");
1259 I = new InsertElementInst(Vec, Elt, Idx);
1260 break;
1261 }
1262
Chris Lattnerabfbf852007-05-06 00:21:25 +00001263 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1264 unsigned OpNum = 0;
1265 Value *Vec1, *Vec2, *Mask;
1266 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1267 getValue(Record, OpNum, Vec1->getType(), Vec2))
1268 return Error("Invalid SHUFFLEVEC record");
1269
1270 const Type *MaskTy =
1271 VectorType::get(Type::Int32Ty,
1272 cast<VectorType>(Vec1->getType())->getNumElements());
1273
1274 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001275 return Error("Invalid SHUFFLEVEC record");
1276 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1277 break;
1278 }
1279
1280 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001281 unsigned OpNum = 0;
1282 Value *LHS, *RHS;
1283 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1284 getValue(Record, OpNum, LHS->getType(), RHS) ||
1285 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001286 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001287
1288 if (LHS->getType()->isFPOrFPVector())
1289 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001290 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001291 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001292 break;
1293 }
1294
Chris Lattner231cbcb2007-05-02 04:27:25 +00001295 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1296 if (Record.size() == 0) {
1297 I = new ReturnInst();
1298 break;
Chris Lattner7337ab92007-05-06 00:00:00 +00001299 } else {
1300 unsigned OpNum = 0;
1301 Value *Op;
1302 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1303 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001304 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001305 I = new ReturnInst(Op);
1306 break;
1307 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001308 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001309 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001310 return Error("Invalid BR record");
1311 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1312 if (TrueDest == 0)
1313 return Error("Invalid BR record");
1314
1315 if (Record.size() == 1)
1316 I = new BranchInst(TrueDest);
1317 else {
1318 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1319 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1320 if (FalseDest == 0 || Cond == 0)
1321 return Error("Invalid BR record");
1322 I = new BranchInst(TrueDest, FalseDest, Cond);
1323 }
1324 break;
1325 }
1326 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1327 if (Record.size() < 3 || (Record.size() & 1) == 0)
1328 return Error("Invalid SWITCH record");
1329 const Type *OpTy = getTypeByID(Record[0]);
1330 Value *Cond = getFnValueByID(Record[1], OpTy);
1331 BasicBlock *Default = getBasicBlock(Record[2]);
1332 if (OpTy == 0 || Cond == 0 || Default == 0)
1333 return Error("Invalid SWITCH record");
1334 unsigned NumCases = (Record.size()-3)/2;
1335 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1336 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1337 ConstantInt *CaseVal =
1338 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1339 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1340 if (CaseVal == 0 || DestBB == 0) {
1341 delete SI;
1342 return Error("Invalid SWITCH record!");
1343 }
1344 SI->addCase(CaseVal, DestBB);
1345 }
1346 I = SI;
1347 break;
1348 }
1349
Chris Lattner76520192007-05-03 22:34:03 +00001350 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001351 if (Record.size() < 4) return Error("Invalid INVOKE record");
1352 unsigned CCInfo = Record[1];
1353 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1354 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001355
Chris Lattnera9bb7132007-05-08 05:38:01 +00001356 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001357 Value *Callee;
1358 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001359 return Error("Invalid INVOKE record");
1360
Chris Lattner7337ab92007-05-06 00:00:00 +00001361 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1362 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001363 dyn_cast<FunctionType>(CalleeTy->getElementType());
1364
1365 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001366 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1367 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001368 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001369
Chris Lattnera9bb7132007-05-08 05:38:01 +00001370 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1371
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001372 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001373 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1374 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1375 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001376 }
1377
Chris Lattner7337ab92007-05-06 00:00:00 +00001378 if (!FTy->isVarArg()) {
1379 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001380 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001381 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001382 // Read type/value pairs for varargs params.
1383 while (OpNum != Record.size()) {
1384 Value *Op;
1385 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1386 return Error("Invalid INVOKE record");
1387 Ops.push_back(Op);
1388 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001389 }
1390
1391 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
Chris Lattner76520192007-05-03 22:34:03 +00001392 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001393 break;
1394 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001395 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1396 I = new UnwindInst();
1397 break;
1398 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1399 I = new UnreachableInst();
1400 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001401 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001402 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001403 return Error("Invalid PHI record");
1404 const Type *Ty = getTypeByID(Record[0]);
1405 if (!Ty) return Error("Invalid PHI record");
1406
1407 PHINode *PN = new PHINode(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001408 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001409
Chris Lattner15e6d172007-05-04 19:11:41 +00001410 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1411 Value *V = getFnValueByID(Record[1+i], Ty);
1412 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001413 if (!V || !BB) return Error("Invalid PHI record");
1414 PN->addIncoming(V, BB);
1415 }
1416 I = PN;
1417 break;
1418 }
1419
1420 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1421 if (Record.size() < 3)
1422 return Error("Invalid MALLOC record");
1423 const PointerType *Ty =
1424 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1425 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1426 unsigned Align = Record[2];
1427 if (!Ty || !Size) return Error("Invalid MALLOC record");
1428 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1429 break;
1430 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001431 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1432 unsigned OpNum = 0;
1433 Value *Op;
1434 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1435 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001436 return Error("Invalid FREE record");
1437 I = new FreeInst(Op);
1438 break;
1439 }
1440 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1441 if (Record.size() < 3)
1442 return Error("Invalid ALLOCA record");
1443 const PointerType *Ty =
1444 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1445 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1446 unsigned Align = Record[2];
1447 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1448 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1449 break;
1450 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001451 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001452 unsigned OpNum = 0;
1453 Value *Op;
1454 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1455 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001456 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001457
1458 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001459 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001460 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001461 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1462 unsigned OpNum = 0;
1463 Value *Val, *Ptr;
1464 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1465 getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1466 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001467 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001468
1469 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001470 break;
1471 }
Chris Lattner76520192007-05-03 22:34:03 +00001472 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001473 if (Record.size() < 2)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001474 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001475
Chris Lattnera9bb7132007-05-08 05:38:01 +00001476 unsigned CCInfo = Record[1];
1477
1478 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001479 Value *Callee;
1480 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1481 return Error("Invalid CALL record");
1482
1483 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001484 const FunctionType *FTy = 0;
1485 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001486 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001487 return Error("Invalid CALL record");
1488
Chris Lattnera9bb7132007-05-08 05:38:01 +00001489 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1490
Chris Lattner0579f7f2007-05-03 22:04:19 +00001491 SmallVector<Value*, 16> Args;
1492 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001493 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1494 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001495 if (Args.back() == 0) return Error("Invalid CALL record");
1496 }
1497
Chris Lattner0579f7f2007-05-03 22:04:19 +00001498 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001499 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001500 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001501 return Error("Invalid CALL record");
1502 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001503 while (OpNum != Record.size()) {
1504 Value *Op;
1505 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1506 return Error("Invalid CALL record");
1507 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001508 }
1509 }
1510
David Greene52eec542007-08-01 03:43:44 +00001511 I = new CallInst(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001512 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1513 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001514 break;
1515 }
1516 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1517 if (Record.size() < 3)
1518 return Error("Invalid VAARG record");
1519 const Type *OpTy = getTypeByID(Record[0]);
1520 Value *Op = getFnValueByID(Record[1], OpTy);
1521 const Type *ResTy = getTypeByID(Record[2]);
1522 if (!OpTy || !Op || !ResTy)
1523 return Error("Invalid VAARG record");
1524 I = new VAArgInst(Op, ResTy);
1525 break;
1526 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001527 }
1528
1529 // Add instruction to end of current BB. If there is no current BB, reject
1530 // this file.
1531 if (CurBB == 0) {
1532 delete I;
1533 return Error("Invalid instruction with no BB");
1534 }
1535 CurBB->getInstList().push_back(I);
1536
1537 // If this was a terminator instruction, move to the next block.
1538 if (isa<TerminatorInst>(I)) {
1539 ++CurBBNo;
1540 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1541 }
1542
1543 // Non-void values get registered in the value table for future use.
1544 if (I && I->getType() != Type::VoidTy)
1545 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001546 }
1547
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001548 // Check the function list for unresolved values.
1549 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1550 if (A->getParent() == 0) {
1551 // We found at least one unresolved value. Nuke them all to avoid leaks.
1552 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1553 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1554 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1555 delete A;
1556 }
1557 }
Chris Lattner35a04702007-05-04 03:50:29 +00001558 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001559 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001560 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001561
1562 // Trim the value list down to the size it was before we parsed this function.
1563 ValueList.shrinkTo(ModuleValueListSize);
1564 std::vector<BasicBlock*>().swap(FunctionBBs);
1565
Chris Lattner48f84872007-05-01 04:59:48 +00001566 return false;
1567}
1568
Chris Lattnerb348bb82007-05-18 04:02:46 +00001569//===----------------------------------------------------------------------===//
1570// ModuleProvider implementation
1571//===----------------------------------------------------------------------===//
1572
1573
1574bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1575 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001576 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001577
1578 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1579 DeferredFunctionInfo.find(F);
1580 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1581
1582 // Move the bit stream to the saved position of the deferred function body and
1583 // restore the real linkage type for the function.
1584 Stream.JumpToBit(DFII->second.first);
1585 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1586
1587 if (ParseFunctionBody(F)) {
1588 if (ErrInfo) *ErrInfo = ErrorString;
1589 return true;
1590 }
1591
1592 return false;
1593}
1594
1595void BitcodeReader::dematerializeFunction(Function *F) {
1596 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001597 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001598 return;
1599
1600 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1601
1602 // Just forget the function body, we can remat it later.
1603 F->deleteBody();
1604 F->setLinkage(GlobalValue::GhostLinkage);
1605}
1606
1607
1608Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1609 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1610 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1611 ++I) {
1612 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001613 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001614 materializeFunction(F, ErrInfo))
1615 return 0;
1616 }
1617 return TheModule;
1618}
1619
1620
1621/// This method is provided by the parent ModuleProvde class and overriden
1622/// here. It simply releases the module from its provided and frees up our
1623/// state.
1624/// @brief Release our hold on the generated module
1625Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1626 // Since we're losing control of this Module, we must hand it back complete
1627 Module *M = ModuleProvider::releaseModule(ErrInfo);
1628 FreeState();
1629 return M;
1630}
1631
Chris Lattner48f84872007-05-01 04:59:48 +00001632
Chris Lattnerc453f762007-04-29 07:54:31 +00001633//===----------------------------------------------------------------------===//
1634// External interface
1635//===----------------------------------------------------------------------===//
1636
1637/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1638///
1639ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1640 std::string *ErrMsg) {
1641 BitcodeReader *R = new BitcodeReader(Buffer);
1642 if (R->ParseBitcode()) {
1643 if (ErrMsg)
1644 *ErrMsg = R->getErrorString();
1645
1646 // Don't let the BitcodeReader dtor delete 'Buffer'.
1647 R->releaseMemoryBuffer();
1648 delete R;
1649 return 0;
1650 }
1651 return R;
1652}
1653
1654/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1655/// If an error occurs, return null and fill in *ErrMsg if non-null.
1656Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1657 BitcodeReader *R;
1658 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1659 if (!R) return 0;
1660
Chris Lattnerb348bb82007-05-18 04:02:46 +00001661 // Read in the entire module.
1662 Module *M = R->materializeModule(ErrMsg);
1663
1664 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1665 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001666 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001667
1668 // If there was no error, tell ModuleProvider not to delete it when its dtor
1669 // is run.
1670 if (M)
1671 M = R->releaseModule(ErrMsg);
1672
Chris Lattnerc453f762007-04-29 07:54:31 +00001673 delete R;
1674 return M;
1675}