blob: 61e0ab9898909bcd0b4448ff6993a7b4cb16eb79 [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnercaee0dc2007-04-22 06:23:29 +00007//
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"
Dale Johannesen22c39792008-02-22 22:17:59 +000021#include "llvm/ParamAttrsList.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000024#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000025#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000026#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000027using namespace llvm;
28
Chris Lattnerb348bb82007-05-18 04:02:46 +000029void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000030 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000031 Buffer = 0;
32 std::vector<PATypeHolder>().swap(TypeList);
33 ValueList.clear();
34 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
35 std::vector<BasicBlock*>().swap(FunctionBBs);
36 std::vector<Function*>().swap(FunctionsWithBodies);
37 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000038}
39
Chris Lattner48c85b82007-05-04 03:30:17 +000040//===----------------------------------------------------------------------===//
41// Helper functions to implement forward reference resolution, etc.
42//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000043
Chris Lattnercaee0dc2007-04-22 06:23:29 +000044/// ConvertToString - Convert a string from a record into an std::string, return
45/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000046template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000047static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000048 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000049 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000050 return true;
51
Chris Lattner15e6d172007-05-04 19:11:41 +000052 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
53 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000054 return false;
55}
56
57static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
58 switch (Val) {
59 default: // Map unknown/new linkages to external
60 case 0: return GlobalValue::ExternalLinkage;
61 case 1: return GlobalValue::WeakLinkage;
62 case 2: return GlobalValue::AppendingLinkage;
63 case 3: return GlobalValue::InternalLinkage;
64 case 4: return GlobalValue::LinkOnceLinkage;
65 case 5: return GlobalValue::DLLImportLinkage;
66 case 6: return GlobalValue::DLLExportLinkage;
67 case 7: return GlobalValue::ExternalWeakLinkage;
68 }
69}
70
71static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
72 switch (Val) {
73 default: // Map unknown visibilities to default.
74 case 0: return GlobalValue::DefaultVisibility;
75 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000076 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000077 }
78}
79
Chris Lattnerf581c3b2007-04-24 07:07:11 +000080static int GetDecodedCastOpcode(unsigned Val) {
81 switch (Val) {
82 default: return -1;
83 case bitc::CAST_TRUNC : return Instruction::Trunc;
84 case bitc::CAST_ZEXT : return Instruction::ZExt;
85 case bitc::CAST_SEXT : return Instruction::SExt;
86 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
87 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
88 case bitc::CAST_UITOFP : return Instruction::UIToFP;
89 case bitc::CAST_SITOFP : return Instruction::SIToFP;
90 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
91 case bitc::CAST_FPEXT : return Instruction::FPExt;
92 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
93 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
94 case bitc::CAST_BITCAST : return Instruction::BitCast;
95 }
96}
97static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
98 switch (Val) {
99 default: return -1;
100 case bitc::BINOP_ADD: return Instruction::Add;
101 case bitc::BINOP_SUB: return Instruction::Sub;
102 case bitc::BINOP_MUL: return Instruction::Mul;
103 case bitc::BINOP_UDIV: return Instruction::UDiv;
104 case bitc::BINOP_SDIV:
105 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
106 case bitc::BINOP_UREM: return Instruction::URem;
107 case bitc::BINOP_SREM:
108 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
109 case bitc::BINOP_SHL: return Instruction::Shl;
110 case bitc::BINOP_LSHR: return Instruction::LShr;
111 case bitc::BINOP_ASHR: return Instruction::AShr;
112 case bitc::BINOP_AND: return Instruction::And;
113 case bitc::BINOP_OR: return Instruction::Or;
114 case bitc::BINOP_XOR: return Instruction::Xor;
115 }
116}
117
118
Chris Lattner522b7b12007-04-24 05:48:56 +0000119namespace {
120 /// @brief A class for maintaining the slot number definition
121 /// as a placeholder for the actual definition for forward constants defs.
122 class ConstantPlaceHolder : public ConstantExpr {
123 ConstantPlaceHolder(); // DO NOT IMPLEMENT
124 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000125 public:
126 Use Op;
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000127 explicit ConstantPlaceHolder(const Type *Ty)
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000128 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
129 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000130 }
131 };
132}
133
134Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
135 const Type *Ty) {
136 if (Idx >= size()) {
137 // Insert a bunch of null values.
138 Uses.resize(Idx+1);
139 OperandList = &Uses[0];
140 NumOperands = Idx+1;
141 }
142
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000143 if (Value *V = Uses[Idx]) {
144 assert(Ty == V->getType() && "Type mismatch in constant table!");
145 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000146 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000147
148 // Create and return a placeholder, which will later be RAUW'd.
149 Constant *C = new ConstantPlaceHolder(Ty);
150 Uses[Idx].init(C, this);
151 return C;
152}
153
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000154Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
155 if (Idx >= size()) {
156 // Insert a bunch of null values.
157 Uses.resize(Idx+1);
158 OperandList = &Uses[0];
159 NumOperands = Idx+1;
160 }
161
162 if (Value *V = Uses[Idx]) {
163 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
164 return V;
165 }
166
Chris Lattner01ff65f2007-05-02 05:16:49 +0000167 // No type specified, must be invalid reference.
168 if (Ty == 0) return 0;
169
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000170 // Create and return a placeholder, which will later be RAUW'd.
171 Value *V = new Argument(Ty);
172 Uses[Idx].init(V, this);
173 return V;
174}
175
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000176
177const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
178 // If the TypeID is in range, return it.
179 if (ID < TypeList.size())
180 return TypeList[ID].get();
181 if (!isTypeTable) return 0;
182
183 // The type table allows forward references. Push as many Opaque types as
184 // needed to get up to ID.
185 while (TypeList.size() <= ID)
186 TypeList.push_back(OpaqueType::get());
187 return TypeList.back().get();
188}
189
Chris Lattner48c85b82007-05-04 03:30:17 +0000190//===----------------------------------------------------------------------===//
191// Functions for parsing blocks from the bitcode file
192//===----------------------------------------------------------------------===//
193
194bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000195 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000196 return Error("Malformed block record");
197
198 if (!ParamAttrs.empty())
199 return Error("Multiple PARAMATTR blocks found!");
200
201 SmallVector<uint64_t, 64> Record;
202
203 ParamAttrsVector Attrs;
204
205 // Read all the records.
206 while (1) {
207 unsigned Code = Stream.ReadCode();
208 if (Code == bitc::END_BLOCK) {
209 if (Stream.ReadBlockEnd())
210 return Error("Error at end of PARAMATTR block");
211 return false;
212 }
213
214 if (Code == bitc::ENTER_SUBBLOCK) {
215 // No known subblocks, always skip them.
216 Stream.ReadSubBlockID();
217 if (Stream.SkipBlock())
218 return Error("Malformed block record");
219 continue;
220 }
221
222 if (Code == bitc::DEFINE_ABBREV) {
223 Stream.ReadAbbrevRecord();
224 continue;
225 }
226
227 // Read a record.
228 Record.clear();
229 switch (Stream.ReadRecord(Code, Record)) {
230 default: // Default behavior: ignore.
231 break;
232 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
233 if (Record.size() & 1)
234 return Error("Invalid ENTRY record");
235
Chris Lattner48c85b82007-05-04 03:30:17 +0000236 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Duncan Sands5e41f652007-11-20 14:09:29 +0000237 if (Record[i+1] != ParamAttr::None)
238 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
Chris Lattner48c85b82007-05-04 03:30:17 +0000239 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000240 ParamAttrs.push_back(Attrs.empty() ? NULL : ParamAttrsList::get(Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000241 Attrs.clear();
242 break;
243 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000244 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000245 }
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;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000327 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
328 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000329 if (Record.size() < 1)
330 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000331 unsigned AddressSpace = 0;
332 if (Record.size() == 2)
333 AddressSpace = Record[1];
334 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000335 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000336 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000337 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000338 // FIXME: attrid is dead, remove it in LLVM 3.0
339 // FUNCTION: [vararg, attrid, retty, paramty x N]
340 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000341 return Error("Invalid FUNCTION type record");
342 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000343 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000344 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000345
Chris Lattnera1afde72007-11-27 17:48:06 +0000346 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000347 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000348 break;
349 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000350 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000351 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000352 return Error("Invalid STRUCT type record");
353 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000354 for (unsigned i = 1, e = Record.size(); i != e; ++i)
355 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000356 ResultTy = StructType::get(EltTys, Record[0]);
357 break;
358 }
359 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
360 if (Record.size() < 2)
361 return Error("Invalid ARRAY type record");
362 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
363 break;
364 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
365 if (Record.size() < 2)
366 return Error("Invalid VECTOR type record");
367 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
368 break;
369 }
370
371 if (NumRecords == TypeList.size()) {
372 // If this is a new type slot, just append it.
373 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
374 ++NumRecords;
375 } else if (ResultTy == 0) {
376 // Otherwise, this was forward referenced, so an opaque type was created,
377 // but the result type is actually just an opaque. Leave the one we
378 // created previously.
379 ++NumRecords;
380 } else {
381 // Otherwise, this was forward referenced, so an opaque type was created.
382 // Resolve the opaque type to the real type now.
383 assert(NumRecords < TypeList.size() && "Typelist imbalance");
384 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
385
386 // Don't directly push the new type on the Tab. Instead we want to replace
387 // the opaque type we previously inserted with the new concrete value. The
388 // refinement from the abstract (opaque) type to the new type causes all
389 // uses of the abstract type to use the concrete type (NewTy). This will
390 // also cause the opaque type to be deleted.
391 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
392
393 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000394 // value table... or with a preexisting type that was already in the
395 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000396 assert(TypeList[NumRecords-1].get() != OldTy &&
397 "refineAbstractType didn't work!");
398 }
399 }
400}
401
402
Chris Lattner86697142007-05-01 05:01:34 +0000403bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000404 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000405 return Error("Malformed block record");
406
407 SmallVector<uint64_t, 64> Record;
408
409 // Read all the records for this type table.
410 std::string TypeName;
411 while (1) {
412 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000413 if (Code == bitc::END_BLOCK) {
414 if (Stream.ReadBlockEnd())
415 return Error("Error at end of type symbol table block");
416 return false;
417 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000418
419 if (Code == bitc::ENTER_SUBBLOCK) {
420 // No known subblocks, always skip them.
421 Stream.ReadSubBlockID();
422 if (Stream.SkipBlock())
423 return Error("Malformed block record");
424 continue;
425 }
426
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000427 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000428 Stream.ReadAbbrevRecord();
429 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000430 }
431
432 // Read a record.
433 Record.clear();
434 switch (Stream.ReadRecord(Code, Record)) {
435 default: // Default behavior: unknown type.
436 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000437 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000438 if (ConvertToString(Record, 1, TypeName))
439 return Error("Invalid TST_ENTRY record");
440 unsigned TypeID = Record[0];
441 if (TypeID >= TypeList.size())
442 return Error("Invalid Type ID in TST_ENTRY record");
443
444 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
445 TypeName.clear();
446 break;
447 }
448 }
449}
450
Chris Lattner86697142007-05-01 05:01:34 +0000451bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000452 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000453 return Error("Malformed block record");
454
455 SmallVector<uint64_t, 64> Record;
456
457 // Read all the records for this value table.
458 SmallString<128> ValueName;
459 while (1) {
460 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000461 if (Code == bitc::END_BLOCK) {
462 if (Stream.ReadBlockEnd())
463 return Error("Error at end of value symbol table block");
464 return false;
465 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000466 if (Code == bitc::ENTER_SUBBLOCK) {
467 // No known subblocks, always skip them.
468 Stream.ReadSubBlockID();
469 if (Stream.SkipBlock())
470 return Error("Malformed block record");
471 continue;
472 }
473
474 if (Code == bitc::DEFINE_ABBREV) {
475 Stream.ReadAbbrevRecord();
476 continue;
477 }
478
479 // Read a record.
480 Record.clear();
481 switch (Stream.ReadRecord(Code, Record)) {
482 default: // Default behavior: unknown type.
483 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000484 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000485 if (ConvertToString(Record, 1, ValueName))
486 return Error("Invalid TST_ENTRY record");
487 unsigned ValueID = Record[0];
488 if (ValueID >= ValueList.size())
489 return Error("Invalid Value ID in VST_ENTRY record");
490 Value *V = ValueList[ValueID];
491
492 V->setName(&ValueName[0], ValueName.size());
493 ValueName.clear();
494 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000495 }
496 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000497 if (ConvertToString(Record, 1, ValueName))
498 return Error("Invalid VST_BBENTRY record");
499 BasicBlock *BB = getBasicBlock(Record[0]);
500 if (BB == 0)
501 return Error("Invalid BB ID in VST_BBENTRY record");
502
503 BB->setName(&ValueName[0], ValueName.size());
504 ValueName.clear();
505 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000506 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000507 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000508 }
509}
510
Chris Lattner0eef0802007-04-24 04:04:35 +0000511/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
512/// the LSB for dense VBR encoding.
513static uint64_t DecodeSignRotatedValue(uint64_t V) {
514 if ((V & 1) == 0)
515 return V >> 1;
516 if (V != 1)
517 return -(V >> 1);
518 // There is no such thing as -0 with integers. "-0" really means MININT.
519 return 1ULL << 63;
520}
521
Chris Lattner07d98b42007-04-26 02:46:40 +0000522/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
523/// values and aliases that we can.
524bool BitcodeReader::ResolveGlobalAndAliasInits() {
525 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
526 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
527
528 GlobalInitWorklist.swap(GlobalInits);
529 AliasInitWorklist.swap(AliasInits);
530
531 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000532 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000533 if (ValID >= ValueList.size()) {
534 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000535 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000536 } else {
537 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
538 GlobalInitWorklist.back().first->setInitializer(C);
539 else
540 return Error("Global variable initializer is not a constant!");
541 }
542 GlobalInitWorklist.pop_back();
543 }
544
545 while (!AliasInitWorklist.empty()) {
546 unsigned ValID = AliasInitWorklist.back().second;
547 if (ValID >= ValueList.size()) {
548 AliasInits.push_back(AliasInitWorklist.back());
549 } else {
550 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000551 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000552 else
553 return Error("Alias initializer is not a constant!");
554 }
555 AliasInitWorklist.pop_back();
556 }
557 return false;
558}
559
560
Chris Lattner86697142007-05-01 05:01:34 +0000561bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000562 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000563 return Error("Malformed block record");
564
565 SmallVector<uint64_t, 64> Record;
566
567 // Read all the records for this value table.
568 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000569 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000570 while (1) {
571 unsigned Code = Stream.ReadCode();
572 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000573 if (NextCstNo != ValueList.size())
574 return Error("Invalid constant reference!");
575
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000576 if (Stream.ReadBlockEnd())
577 return Error("Error at end of constants block");
578 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000579 }
580
581 if (Code == bitc::ENTER_SUBBLOCK) {
582 // No known subblocks, always skip them.
583 Stream.ReadSubBlockID();
584 if (Stream.SkipBlock())
585 return Error("Malformed block record");
586 continue;
587 }
588
589 if (Code == bitc::DEFINE_ABBREV) {
590 Stream.ReadAbbrevRecord();
591 continue;
592 }
593
594 // Read a record.
595 Record.clear();
596 Value *V = 0;
597 switch (Stream.ReadRecord(Code, Record)) {
598 default: // Default behavior: unknown constant
599 case bitc::CST_CODE_UNDEF: // UNDEF
600 V = UndefValue::get(CurTy);
601 break;
602 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
603 if (Record.empty())
604 return Error("Malformed CST_SETTYPE record");
605 if (Record[0] >= TypeList.size())
606 return Error("Invalid Type ID in CST_SETTYPE record");
607 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000608 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000609 case bitc::CST_CODE_NULL: // NULL
610 V = Constant::getNullValue(CurTy);
611 break;
612 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000613 if (!isa<IntegerType>(CurTy) || Record.empty())
614 return Error("Invalid CST_INTEGER record");
615 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
616 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000617 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
618 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000619 return Error("Invalid WIDE_INTEGER record");
620
Chris Lattner15e6d172007-05-04 19:11:41 +0000621 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000622 SmallVector<uint64_t, 8> Words;
623 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000624 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000625 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000626 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000627 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000628 break;
629 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000630 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000631 if (Record.empty())
632 return Error("Invalid FLOAT record");
633 if (CurTy == Type::FloatTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000634 V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000635 else if (CurTy == Type::DoubleTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000636 V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000637 else if (CurTy == Type::X86_FP80Ty)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000638 V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000639 else if (CurTy == Type::FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000640 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000641 else if (CurTy == Type::PPC_FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000642 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000643 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000644 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000645 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000646 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000647
Chris Lattner15e6d172007-05-04 19:11:41 +0000648 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
649 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000650 return Error("Invalid CST_AGGREGATE record");
651
Chris Lattner15e6d172007-05-04 19:11:41 +0000652 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000653 std::vector<Constant*> Elts;
654
655 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
656 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000657 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000658 STy->getElementType(i)));
659 V = ConstantStruct::get(STy, Elts);
660 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
661 const Type *EltTy = ATy->getElementType();
662 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000663 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000664 V = ConstantArray::get(ATy, Elts);
665 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
666 const Type *EltTy = VTy->getElementType();
667 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000668 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000669 V = ConstantVector::get(Elts);
670 } else {
671 V = UndefValue::get(CurTy);
672 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000673 break;
674 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000675 case bitc::CST_CODE_STRING: { // STRING: [values]
676 if (Record.empty())
677 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000678
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000679 const ArrayType *ATy = cast<ArrayType>(CurTy);
680 const Type *EltTy = ATy->getElementType();
681
682 unsigned Size = Record.size();
683 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000684 for (unsigned i = 0; i != Size; ++i)
685 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
686 V = ConstantArray::get(ATy, Elts);
687 break;
688 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000689 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
690 if (Record.empty())
691 return Error("Invalid CST_AGGREGATE record");
692
693 const ArrayType *ATy = cast<ArrayType>(CurTy);
694 const Type *EltTy = ATy->getElementType();
695
696 unsigned Size = Record.size();
697 std::vector<Constant*> Elts;
698 for (unsigned i = 0; i != Size; ++i)
699 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
700 Elts.push_back(Constant::getNullValue(EltTy));
701 V = ConstantArray::get(ATy, Elts);
702 break;
703 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000704 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
705 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
706 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000707 if (Opc < 0) {
708 V = UndefValue::get(CurTy); // Unknown binop.
709 } else {
710 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
711 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
712 V = ConstantExpr::get(Opc, LHS, RHS);
713 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000714 break;
715 }
716 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
717 if (Record.size() < 3) return Error("Invalid CE_CAST record");
718 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000719 if (Opc < 0) {
720 V = UndefValue::get(CurTy); // Unknown cast.
721 } else {
722 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000723 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000724 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
725 V = ConstantExpr::getCast(Opc, Op, CurTy);
726 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000727 break;
728 }
729 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000730 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000731 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000732 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000733 const Type *ElTy = getTypeByID(Record[i]);
734 if (!ElTy) return Error("Invalid CE_GEP record");
735 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
736 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000737 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
738 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000739 }
740 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
741 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
742 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
743 Type::Int1Ty),
744 ValueList.getConstantFwdRef(Record[1],CurTy),
745 ValueList.getConstantFwdRef(Record[2],CurTy));
746 break;
747 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
748 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
749 const VectorType *OpTy =
750 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
751 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
752 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
753 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
754 OpTy->getElementType());
755 V = ConstantExpr::getExtractElement(Op0, Op1);
756 break;
757 }
758 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
759 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
760 if (Record.size() < 3 || OpTy == 0)
761 return Error("Invalid CE_INSERTELT record");
762 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
763 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
764 OpTy->getElementType());
765 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
766 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
767 break;
768 }
769 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
770 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
771 if (Record.size() < 3 || OpTy == 0)
772 return Error("Invalid CE_INSERTELT record");
773 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
774 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
775 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
776 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
777 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
778 break;
779 }
780 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
781 if (Record.size() < 4) return Error("Invalid CE_CMP record");
782 const Type *OpTy = getTypeByID(Record[0]);
783 if (OpTy == 0) return Error("Invalid CE_CMP record");
784 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
785 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
786
787 if (OpTy->isFloatingPoint())
788 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
789 else
790 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
791 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000792 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000793 case bitc::CST_CODE_INLINEASM: {
794 if (Record.size() < 2) return Error("Invalid INLINEASM record");
795 std::string AsmStr, ConstrStr;
796 bool HasSideEffects = Record[0];
797 unsigned AsmStrSize = Record[1];
798 if (2+AsmStrSize >= Record.size())
799 return Error("Invalid INLINEASM record");
800 unsigned ConstStrSize = Record[2+AsmStrSize];
801 if (3+AsmStrSize+ConstStrSize > Record.size())
802 return Error("Invalid INLINEASM record");
803
804 for (unsigned i = 0; i != AsmStrSize; ++i)
805 AsmStr += (char)Record[2+i];
806 for (unsigned i = 0; i != ConstStrSize; ++i)
807 ConstrStr += (char)Record[3+AsmStrSize+i];
808 const PointerType *PTy = cast<PointerType>(CurTy);
809 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
810 AsmStr, ConstrStr, HasSideEffects);
811 break;
812 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000813 }
814
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000815 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000816 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000817 }
818}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000819
Chris Lattner980e5aa2007-05-01 05:52:21 +0000820/// RememberAndSkipFunctionBody - When we see the block for a function body,
821/// remember where it is and then skip it. This lets us lazily deserialize the
822/// functions.
823bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000824 // Get the function we are talking about.
825 if (FunctionsWithBodies.empty())
826 return Error("Insufficient function protos");
827
828 Function *Fn = FunctionsWithBodies.back();
829 FunctionsWithBodies.pop_back();
830
831 // Save the current stream state.
832 uint64_t CurBit = Stream.GetCurrentBitNo();
833 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
834
835 // Set the functions linkage to GhostLinkage so we know it is lazily
836 // deserialized.
837 Fn->setLinkage(GlobalValue::GhostLinkage);
838
839 // Skip over the function block for now.
840 if (Stream.SkipBlock())
841 return Error("Malformed block record");
842 return false;
843}
844
Chris Lattner86697142007-05-01 05:01:34 +0000845bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000846 // Reject multiple MODULE_BLOCK's in a single bitstream.
847 if (TheModule)
848 return Error("Multiple MODULE_BLOCKs in same stream");
849
Chris Lattnere17b6582007-05-05 00:17:00 +0000850 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000851 return Error("Malformed block record");
852
853 // Otherwise, create the module.
854 TheModule = new Module(ModuleID);
855
856 SmallVector<uint64_t, 64> Record;
857 std::vector<std::string> SectionTable;
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000858 std::vector<std::string> CollectorTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000859
860 // Read all the records for this module.
861 while (!Stream.AtEndOfStream()) {
862 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000863 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000864 if (Stream.ReadBlockEnd())
865 return Error("Error at end of module block");
866
867 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000868 ResolveGlobalAndAliasInits();
869 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000870 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000871 if (!FunctionsWithBodies.empty())
872 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000873
Chandler Carruth69940402007-08-04 01:51:18 +0000874 // Look for intrinsic functions which need to be upgraded at some point
875 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
876 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +0000877 Function* NewFn;
878 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +0000879 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
880 }
881
Chris Lattner980e5aa2007-05-01 05:52:21 +0000882 // Force deallocation of memory for these vectors to favor the client that
883 // want lazy deserialization.
884 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
885 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
886 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000887 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000888 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000889
890 if (Code == bitc::ENTER_SUBBLOCK) {
891 switch (Stream.ReadSubBlockID()) {
892 default: // Skip unknown content.
893 if (Stream.SkipBlock())
894 return Error("Malformed block record");
895 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000896 case bitc::BLOCKINFO_BLOCK_ID:
897 if (Stream.ReadBlockInfoBlock())
898 return Error("Malformed BlockInfoBlock");
899 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000900 case bitc::PARAMATTR_BLOCK_ID:
901 if (ParseParamAttrBlock())
902 return true;
903 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000904 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000905 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000906 return true;
907 break;
908 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000909 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000910 return true;
911 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000912 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000913 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000914 return true;
915 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000916 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000917 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000918 return true;
919 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000920 case bitc::FUNCTION_BLOCK_ID:
921 // If this is the first function body we've seen, reverse the
922 // FunctionsWithBodies list.
923 if (!HasReversedFunctionsWithBodies) {
924 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
925 HasReversedFunctionsWithBodies = true;
926 }
927
Chris Lattner980e5aa2007-05-01 05:52:21 +0000928 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000929 return true;
930 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000931 }
932 continue;
933 }
934
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000935 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000936 Stream.ReadAbbrevRecord();
937 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000938 }
939
940 // Read a record.
941 switch (Stream.ReadRecord(Code, Record)) {
942 default: break; // Default behavior, ignore unknown content.
943 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
944 if (Record.size() < 1)
945 return Error("Malformed MODULE_CODE_VERSION");
946 // Only version #0 is supported so far.
947 if (Record[0] != 0)
948 return Error("Unknown bitstream version!");
949 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000950 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000951 std::string S;
952 if (ConvertToString(Record, 0, S))
953 return Error("Invalid MODULE_CODE_TRIPLE record");
954 TheModule->setTargetTriple(S);
955 break;
956 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000957 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000958 std::string S;
959 if (ConvertToString(Record, 0, S))
960 return Error("Invalid MODULE_CODE_DATALAYOUT record");
961 TheModule->setDataLayout(S);
962 break;
963 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000964 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000965 std::string S;
966 if (ConvertToString(Record, 0, S))
967 return Error("Invalid MODULE_CODE_ASM record");
968 TheModule->setModuleInlineAsm(S);
969 break;
970 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000971 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000972 std::string S;
973 if (ConvertToString(Record, 0, S))
974 return Error("Invalid MODULE_CODE_DEPLIB record");
975 TheModule->addLibrary(S);
976 break;
977 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000978 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000979 std::string S;
980 if (ConvertToString(Record, 0, S))
981 return Error("Invalid MODULE_CODE_SECTIONNAME record");
982 SectionTable.push_back(S);
983 break;
984 }
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000985 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
986 std::string S;
987 if (ConvertToString(Record, 0, S))
988 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
989 CollectorTable.push_back(S);
990 break;
991 }
Christopher Lambfe63fb92007-12-11 08:59:05 +0000992 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000993 // linkage, alignment, section, visibility, threadlocal]
994 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000995 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000996 return Error("Invalid MODULE_CODE_GLOBALVAR record");
997 const Type *Ty = getTypeByID(Record[0]);
998 if (!isa<PointerType>(Ty))
999 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001000 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001001 Ty = cast<PointerType>(Ty)->getElementType();
1002
1003 bool isConstant = Record[1];
1004 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1005 unsigned Alignment = (1 << Record[4]) >> 1;
1006 std::string Section;
1007 if (Record[5]) {
1008 if (Record[5]-1 >= SectionTable.size())
1009 return Error("Invalid section ID");
1010 Section = SectionTable[Record[5]-1];
1011 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001012 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001013 if (Record.size() > 6)
1014 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001015 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001016 if (Record.size() > 7)
1017 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001018
1019 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001020 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1021 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001022 NewGV->setAlignment(Alignment);
1023 if (!Section.empty())
1024 NewGV->setSection(Section);
1025 NewGV->setVisibility(Visibility);
1026 NewGV->setThreadLocal(isThreadLocal);
1027
Chris Lattner0b2482a2007-04-23 21:26:05 +00001028 ValueList.push_back(NewGV);
1029
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001030 // Remember which value to use for the global initializer.
1031 if (unsigned InitID = Record[2])
1032 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001033 break;
1034 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001035 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001036 // alignment, section, visibility, collector]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001037 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001038 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001039 return Error("Invalid MODULE_CODE_FUNCTION record");
1040 const Type *Ty = getTypeByID(Record[0]);
1041 if (!isa<PointerType>(Ty))
1042 return Error("Function not a pointer type!");
1043 const FunctionType *FTy =
1044 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1045 if (!FTy)
1046 return Error("Function not a pointer to function type!");
1047
1048 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1049 "", TheModule);
1050
1051 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001052 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001053 Func->setLinkage(GetDecodedLinkage(Record[3]));
Duncan Sandsdc024672007-11-27 13:23:08 +00001054 const ParamAttrsList *PAL = getParamAttrs(Record[4]);
1055 Func->setParamAttrs(PAL);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001056
1057 Func->setAlignment((1 << Record[5]) >> 1);
1058 if (Record[6]) {
1059 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001060 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001061 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001062 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001063 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001064 if (Record.size() > 8 && Record[8]) {
1065 if (Record[8]-1 > CollectorTable.size())
1066 return Error("Invalid collector ID");
1067 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1068 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001069
Chris Lattner0b2482a2007-04-23 21:26:05 +00001070 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001071
1072 // If this is a function with a body, remember the prototype we are
1073 // creating now, so that we can match up the body with them later.
1074 if (!isProto)
1075 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001076 break;
1077 }
Chris Lattner07d98b42007-04-26 02:46:40 +00001078 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +00001079 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001080 if (Record.size() < 3)
1081 return Error("Invalid MODULE_ALIAS record");
1082 const Type *Ty = getTypeByID(Record[0]);
1083 if (!isa<PointerType>(Ty))
1084 return Error("Function not a pointer type!");
1085
1086 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1087 "", 0, TheModule);
1088 ValueList.push_back(NewGA);
1089 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1090 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001091 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001092 /// MODULE_CODE_PURGEVALS: [numvals]
1093 case bitc::MODULE_CODE_PURGEVALS:
1094 // Trim down the value list to the specified size.
1095 if (Record.size() < 1 || Record[0] > ValueList.size())
1096 return Error("Invalid MODULE_PURGEVALS record");
1097 ValueList.shrinkTo(Record[0]);
1098 break;
1099 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001100 Record.clear();
1101 }
1102
1103 return Error("Premature end of bitstream");
1104}
1105
1106
Chris Lattnerc453f762007-04-29 07:54:31 +00001107bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001108 TheModule = 0;
1109
Chris Lattnerc453f762007-04-29 07:54:31 +00001110 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001111 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1112
Chris Lattnerc453f762007-04-29 07:54:31 +00001113 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001114 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001115
1116 // Sniff for the signature.
1117 if (Stream.Read(8) != 'B' ||
1118 Stream.Read(8) != 'C' ||
1119 Stream.Read(4) != 0x0 ||
1120 Stream.Read(4) != 0xC ||
1121 Stream.Read(4) != 0xE ||
1122 Stream.Read(4) != 0xD)
1123 return Error("Invalid bitcode signature");
1124
1125 // We expect a number of well-defined blocks, though we don't necessarily
1126 // need to understand them all.
1127 while (!Stream.AtEndOfStream()) {
1128 unsigned Code = Stream.ReadCode();
1129
1130 if (Code != bitc::ENTER_SUBBLOCK)
1131 return Error("Invalid record at top-level");
1132
1133 unsigned BlockID = Stream.ReadSubBlockID();
1134
1135 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001136 switch (BlockID) {
1137 case bitc::BLOCKINFO_BLOCK_ID:
1138 if (Stream.ReadBlockInfoBlock())
1139 return Error("Malformed BlockInfoBlock");
1140 break;
1141 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001142 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001143 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001144 break;
1145 default:
1146 if (Stream.SkipBlock())
1147 return Error("Malformed block record");
1148 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001149 }
1150 }
1151
1152 return false;
1153}
Chris Lattnerc453f762007-04-29 07:54:31 +00001154
Chris Lattner48f84872007-05-01 04:59:48 +00001155
Chris Lattner980e5aa2007-05-01 05:52:21 +00001156/// ParseFunctionBody - Lazily parse the specified function body block.
1157bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001158 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001159 return Error("Malformed block record");
1160
1161 unsigned ModuleValueListSize = ValueList.size();
1162
1163 // Add all the function arguments to the value table.
1164 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1165 ValueList.push_back(I);
1166
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001167 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001168 BasicBlock *CurBB = 0;
1169 unsigned CurBBNo = 0;
1170
Chris Lattner980e5aa2007-05-01 05:52:21 +00001171 // Read all the records.
1172 SmallVector<uint64_t, 64> Record;
1173 while (1) {
1174 unsigned Code = Stream.ReadCode();
1175 if (Code == bitc::END_BLOCK) {
1176 if (Stream.ReadBlockEnd())
1177 return Error("Error at end of function block");
1178 break;
1179 }
1180
1181 if (Code == bitc::ENTER_SUBBLOCK) {
1182 switch (Stream.ReadSubBlockID()) {
1183 default: // Skip unknown content.
1184 if (Stream.SkipBlock())
1185 return Error("Malformed block record");
1186 break;
1187 case bitc::CONSTANTS_BLOCK_ID:
1188 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001189 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001190 break;
1191 case bitc::VALUE_SYMTAB_BLOCK_ID:
1192 if (ParseValueSymbolTable()) return true;
1193 break;
1194 }
1195 continue;
1196 }
1197
1198 if (Code == bitc::DEFINE_ABBREV) {
1199 Stream.ReadAbbrevRecord();
1200 continue;
1201 }
1202
1203 // Read a record.
1204 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001205 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001206 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001207 default: // Default behavior: reject
1208 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001209 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001210 if (Record.size() < 1 || Record[0] == 0)
1211 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001212 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001213 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001214 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1215 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001216 CurBB = FunctionBBs[0];
1217 continue;
1218
Chris Lattnerabfbf852007-05-06 00:21:25 +00001219 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1220 unsigned OpNum = 0;
1221 Value *LHS, *RHS;
1222 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1223 getValue(Record, OpNum, LHS->getType(), RHS) ||
1224 OpNum+1 != Record.size())
1225 return Error("Invalid BINOP record");
1226
1227 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1228 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001229 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001230 break;
1231 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001232 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1233 unsigned OpNum = 0;
1234 Value *Op;
1235 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1236 OpNum+2 != Record.size())
1237 return Error("Invalid CAST record");
1238
1239 const Type *ResTy = getTypeByID(Record[OpNum]);
1240 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1241 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001242 return Error("Invalid CAST record");
1243 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1244 break;
1245 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001246 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001247 unsigned OpNum = 0;
1248 Value *BasePtr;
1249 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001250 return Error("Invalid GEP record");
1251
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001252 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001253 while (OpNum != Record.size()) {
1254 Value *Op;
1255 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001256 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001257 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001258 }
1259
David Greeneb8f74792007-09-04 15:46:09 +00001260 I = new GetElementPtrInst(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001261 break;
1262 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001263
Chris Lattnerabfbf852007-05-06 00:21:25 +00001264 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1265 unsigned OpNum = 0;
1266 Value *TrueVal, *FalseVal, *Cond;
1267 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1268 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1269 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001270 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001271
1272 I = new SelectInst(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001273 break;
1274 }
1275
1276 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001277 unsigned OpNum = 0;
1278 Value *Vec, *Idx;
1279 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1280 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001281 return Error("Invalid EXTRACTELT record");
1282 I = new ExtractElementInst(Vec, Idx);
1283 break;
1284 }
1285
1286 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001287 unsigned OpNum = 0;
1288 Value *Vec, *Elt, *Idx;
1289 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1290 getValue(Record, OpNum,
1291 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1292 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001293 return Error("Invalid INSERTELT record");
1294 I = new InsertElementInst(Vec, Elt, Idx);
1295 break;
1296 }
1297
Chris Lattnerabfbf852007-05-06 00:21:25 +00001298 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1299 unsigned OpNum = 0;
1300 Value *Vec1, *Vec2, *Mask;
1301 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1302 getValue(Record, OpNum, Vec1->getType(), Vec2))
1303 return Error("Invalid SHUFFLEVEC record");
1304
1305 const Type *MaskTy =
1306 VectorType::get(Type::Int32Ty,
1307 cast<VectorType>(Vec1->getType())->getNumElements());
1308
1309 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001310 return Error("Invalid SHUFFLEVEC record");
1311 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1312 break;
1313 }
1314
1315 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001316 unsigned OpNum = 0;
1317 Value *LHS, *RHS;
1318 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1319 getValue(Record, OpNum, LHS->getType(), RHS) ||
1320 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001321 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001322
1323 if (LHS->getType()->isFPOrFPVector())
1324 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001325 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001326 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001327 break;
1328 }
Devang Patel197be3d2008-02-22 02:49:49 +00001329 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1330 if (Record.size() != 2)
1331 return Error("Invalid GETRESULT record");
1332 unsigned OpNum = 0;
1333 Value *Op;
1334 getValueTypePair(Record, OpNum, NextValueNo, Op);
1335 unsigned Index = Record[1];
1336 I = new GetResultInst(Op, Index);
1337 break;
1338 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001339
Chris Lattner231cbcb2007-05-02 04:27:25 +00001340 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001341 {
1342 unsigned Size = Record.size();
1343 if (Size == 0) {
1344 I = new ReturnInst();
1345 break;
1346 } else {
1347 unsigned OpNum = 0;
Devang Patelf4511cd2008-02-26 19:38:17 +00001348 SmallVector<Value *,4> Vs;
Devang Pateld9d99ff2008-02-26 01:29:32 +00001349 do {
1350 Value *Op = NULL;
1351 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1352 return Error("Invalid RET record");
1353 Vs.push_back(Op);
1354 } while(OpNum != Record.size());
1355
Devang Patelf4511cd2008-02-26 19:38:17 +00001356 // SmallVector Vs has at least one element.
1357 I = new ReturnInst(&Vs[0], Vs.size());
Devang Pateld9d99ff2008-02-26 01:29:32 +00001358 break;
1359 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001360 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001361 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001362 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001363 return Error("Invalid BR record");
1364 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1365 if (TrueDest == 0)
1366 return Error("Invalid BR record");
1367
1368 if (Record.size() == 1)
1369 I = new BranchInst(TrueDest);
1370 else {
1371 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1372 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1373 if (FalseDest == 0 || Cond == 0)
1374 return Error("Invalid BR record");
1375 I = new BranchInst(TrueDest, FalseDest, Cond);
1376 }
1377 break;
1378 }
1379 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1380 if (Record.size() < 3 || (Record.size() & 1) == 0)
1381 return Error("Invalid SWITCH record");
1382 const Type *OpTy = getTypeByID(Record[0]);
1383 Value *Cond = getFnValueByID(Record[1], OpTy);
1384 BasicBlock *Default = getBasicBlock(Record[2]);
1385 if (OpTy == 0 || Cond == 0 || Default == 0)
1386 return Error("Invalid SWITCH record");
1387 unsigned NumCases = (Record.size()-3)/2;
1388 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1389 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1390 ConstantInt *CaseVal =
1391 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1392 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1393 if (CaseVal == 0 || DestBB == 0) {
1394 delete SI;
1395 return Error("Invalid SWITCH record!");
1396 }
1397 SI->addCase(CaseVal, DestBB);
1398 }
1399 I = SI;
1400 break;
1401 }
1402
Duncan Sandsdc024672007-11-27 13:23:08 +00001403 case bitc::FUNC_CODE_INST_INVOKE: {
1404 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001405 if (Record.size() < 4) return Error("Invalid INVOKE record");
Duncan Sandsdc024672007-11-27 13:23:08 +00001406 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001407 unsigned CCInfo = Record[1];
1408 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1409 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001410
Chris Lattnera9bb7132007-05-08 05:38:01 +00001411 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001412 Value *Callee;
1413 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001414 return Error("Invalid INVOKE record");
1415
Chris Lattner7337ab92007-05-06 00:00:00 +00001416 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1417 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001418 dyn_cast<FunctionType>(CalleeTy->getElementType());
1419
1420 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001421 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1422 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001423 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001424
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001425 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001426 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1427 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1428 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001429 }
1430
Chris Lattner7337ab92007-05-06 00:00:00 +00001431 if (!FTy->isVarArg()) {
1432 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001433 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001434 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001435 // Read type/value pairs for varargs params.
1436 while (OpNum != Record.size()) {
1437 Value *Op;
1438 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1439 return Error("Invalid INVOKE record");
1440 Ops.push_back(Op);
1441 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001442 }
1443
David Greenef1355a52007-08-27 19:04:21 +00001444 I = new InvokeInst(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001445 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Duncan Sandsdc024672007-11-27 13:23:08 +00001446 cast<InvokeInst>(I)->setParamAttrs(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001447 break;
1448 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001449 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1450 I = new UnwindInst();
1451 break;
1452 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1453 I = new UnreachableInst();
1454 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001455 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001456 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001457 return Error("Invalid PHI record");
1458 const Type *Ty = getTypeByID(Record[0]);
1459 if (!Ty) return Error("Invalid PHI record");
1460
1461 PHINode *PN = new PHINode(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001462 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001463
Chris Lattner15e6d172007-05-04 19:11:41 +00001464 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1465 Value *V = getFnValueByID(Record[1+i], Ty);
1466 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001467 if (!V || !BB) return Error("Invalid PHI record");
1468 PN->addIncoming(V, BB);
1469 }
1470 I = PN;
1471 break;
1472 }
1473
1474 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1475 if (Record.size() < 3)
1476 return Error("Invalid MALLOC record");
1477 const PointerType *Ty =
1478 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1479 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1480 unsigned Align = Record[2];
1481 if (!Ty || !Size) return Error("Invalid MALLOC record");
1482 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1483 break;
1484 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001485 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1486 unsigned OpNum = 0;
1487 Value *Op;
1488 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1489 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001490 return Error("Invalid FREE record");
1491 I = new FreeInst(Op);
1492 break;
1493 }
1494 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1495 if (Record.size() < 3)
1496 return Error("Invalid ALLOCA record");
1497 const PointerType *Ty =
1498 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1499 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1500 unsigned Align = Record[2];
1501 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1502 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1503 break;
1504 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001505 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001506 unsigned OpNum = 0;
1507 Value *Op;
1508 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1509 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001510 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001511
1512 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001513 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001514 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001515 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1516 unsigned OpNum = 0;
1517 Value *Val, *Ptr;
1518 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1519 getValue(Record, OpNum,
1520 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1521 OpNum+2 != Record.size())
1522 return Error("Invalid STORE record");
1523
1524 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1525 break;
1526 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001527 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001528 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001529 unsigned OpNum = 0;
1530 Value *Val, *Ptr;
1531 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001532 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001533 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001534 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001535
1536 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001537 break;
1538 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001539 case bitc::FUNC_CODE_INST_CALL: {
1540 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1541 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001542 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001543
Duncan Sandsdc024672007-11-27 13:23:08 +00001544 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001545 unsigned CCInfo = Record[1];
1546
1547 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001548 Value *Callee;
1549 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1550 return Error("Invalid CALL record");
1551
1552 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001553 const FunctionType *FTy = 0;
1554 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001555 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001556 return Error("Invalid CALL record");
1557
1558 SmallVector<Value*, 16> Args;
1559 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001560 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001561 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1562 Args.push_back(getBasicBlock(Record[OpNum]));
1563 else
1564 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001565 if (Args.back() == 0) return Error("Invalid CALL record");
1566 }
1567
Chris Lattner0579f7f2007-05-03 22:04:19 +00001568 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001569 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001570 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001571 return Error("Invalid CALL record");
1572 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001573 while (OpNum != Record.size()) {
1574 Value *Op;
1575 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1576 return Error("Invalid CALL record");
1577 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001578 }
1579 }
1580
David Greene52eec542007-08-01 03:43:44 +00001581 I = new CallInst(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001582 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1583 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Duncan Sandsdc024672007-11-27 13:23:08 +00001584 cast<CallInst>(I)->setParamAttrs(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001585 break;
1586 }
1587 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1588 if (Record.size() < 3)
1589 return Error("Invalid VAARG record");
1590 const Type *OpTy = getTypeByID(Record[0]);
1591 Value *Op = getFnValueByID(Record[1], OpTy);
1592 const Type *ResTy = getTypeByID(Record[2]);
1593 if (!OpTy || !Op || !ResTy)
1594 return Error("Invalid VAARG record");
1595 I = new VAArgInst(Op, ResTy);
1596 break;
1597 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001598 }
1599
1600 // Add instruction to end of current BB. If there is no current BB, reject
1601 // this file.
1602 if (CurBB == 0) {
1603 delete I;
1604 return Error("Invalid instruction with no BB");
1605 }
1606 CurBB->getInstList().push_back(I);
1607
1608 // If this was a terminator instruction, move to the next block.
1609 if (isa<TerminatorInst>(I)) {
1610 ++CurBBNo;
1611 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1612 }
1613
1614 // Non-void values get registered in the value table for future use.
1615 if (I && I->getType() != Type::VoidTy)
1616 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001617 }
1618
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001619 // Check the function list for unresolved values.
1620 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1621 if (A->getParent() == 0) {
1622 // We found at least one unresolved value. Nuke them all to avoid leaks.
1623 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1624 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1625 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1626 delete A;
1627 }
1628 }
Chris Lattner35a04702007-05-04 03:50:29 +00001629 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001630 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001631 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001632
1633 // Trim the value list down to the size it was before we parsed this function.
1634 ValueList.shrinkTo(ModuleValueListSize);
1635 std::vector<BasicBlock*>().swap(FunctionBBs);
1636
Chris Lattner48f84872007-05-01 04:59:48 +00001637 return false;
1638}
1639
Chris Lattnerb348bb82007-05-18 04:02:46 +00001640//===----------------------------------------------------------------------===//
1641// ModuleProvider implementation
1642//===----------------------------------------------------------------------===//
1643
1644
1645bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1646 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001647 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001648
1649 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1650 DeferredFunctionInfo.find(F);
1651 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1652
1653 // Move the bit stream to the saved position of the deferred function body and
1654 // restore the real linkage type for the function.
1655 Stream.JumpToBit(DFII->second.first);
1656 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1657
1658 if (ParseFunctionBody(F)) {
1659 if (ErrInfo) *ErrInfo = ErrorString;
1660 return true;
1661 }
Chandler Carruth69940402007-08-04 01:51:18 +00001662
1663 // Upgrade any old intrinsic calls in the function.
1664 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1665 E = UpgradedIntrinsics.end(); I != E; ++I) {
1666 if (I->first != I->second) {
1667 for (Value::use_iterator UI = I->first->use_begin(),
1668 UE = I->first->use_end(); UI != UE; ) {
1669 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1670 UpgradeIntrinsicCall(CI, I->second);
1671 }
1672 }
1673 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001674
1675 return false;
1676}
1677
1678void BitcodeReader::dematerializeFunction(Function *F) {
1679 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001680 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001681 return;
1682
1683 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1684
1685 // Just forget the function body, we can remat it later.
1686 F->deleteBody();
1687 F->setLinkage(GlobalValue::GhostLinkage);
1688}
1689
1690
1691Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1692 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1693 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1694 ++I) {
1695 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001696 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001697 materializeFunction(F, ErrInfo))
1698 return 0;
1699 }
Chandler Carruth69940402007-08-04 01:51:18 +00001700
1701 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1702 // delete the old functions to clean up. We can't do this unless the entire
1703 // module is materialized because there could always be another function body
1704 // with calls to the old function.
1705 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1706 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1707 if (I->first != I->second) {
1708 for (Value::use_iterator UI = I->first->use_begin(),
1709 UE = I->first->use_end(); UI != UE; ) {
1710 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1711 UpgradeIntrinsicCall(CI, I->second);
1712 }
1713 ValueList.replaceUsesOfWith(I->first, I->second);
1714 I->first->eraseFromParent();
1715 }
1716 }
1717 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1718
Chris Lattnerb348bb82007-05-18 04:02:46 +00001719 return TheModule;
1720}
1721
1722
1723/// This method is provided by the parent ModuleProvde class and overriden
1724/// here. It simply releases the module from its provided and frees up our
1725/// state.
1726/// @brief Release our hold on the generated module
1727Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1728 // Since we're losing control of this Module, we must hand it back complete
1729 Module *M = ModuleProvider::releaseModule(ErrInfo);
1730 FreeState();
1731 return M;
1732}
1733
Chris Lattner48f84872007-05-01 04:59:48 +00001734
Chris Lattnerc453f762007-04-29 07:54:31 +00001735//===----------------------------------------------------------------------===//
1736// External interface
1737//===----------------------------------------------------------------------===//
1738
1739/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1740///
1741ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1742 std::string *ErrMsg) {
1743 BitcodeReader *R = new BitcodeReader(Buffer);
1744 if (R->ParseBitcode()) {
1745 if (ErrMsg)
1746 *ErrMsg = R->getErrorString();
1747
1748 // Don't let the BitcodeReader dtor delete 'Buffer'.
1749 R->releaseMemoryBuffer();
1750 delete R;
1751 return 0;
1752 }
1753 return R;
1754}
1755
1756/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1757/// If an error occurs, return null and fill in *ErrMsg if non-null.
1758Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1759 BitcodeReader *R;
1760 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1761 if (!R) return 0;
1762
Chris Lattnerb348bb82007-05-18 04:02:46 +00001763 // Read in the entire module.
1764 Module *M = R->materializeModule(ErrMsg);
1765
1766 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1767 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001768 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001769
1770 // If there was no error, tell ModuleProvider not to delete it when its dtor
1771 // is run.
1772 if (M)
1773 M = R->releaseModule(ErrMsg);
1774
Chris Lattnerc453f762007-04-29 07:54:31 +00001775 delete R;
1776 return M;
1777}