blob: 1d8def907cd06ee9565fb0fd367581e47fa51578 [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"
Chandler Carruth69940402007-08-04 01:51:18 +000021#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000022#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000023#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000025#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000026using namespace llvm;
27
Chris Lattnerb348bb82007-05-18 04:02:46 +000028void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000029 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000030 Buffer = 0;
31 std::vector<PATypeHolder>().swap(TypeList);
32 ValueList.clear();
Chris Lattner461edd92008-03-12 02:25:52 +000033
Chris Lattner58d74912008-03-12 17:45:29 +000034 std::vector<PAListPtr>().swap(ParamAttrs);
Chris Lattnerb348bb82007-05-18 04:02:46 +000035 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 Use Op;
Gabor Greif051a9502008-04-06 20:25:17 +0000126 public:
127 // allocate space for exactly one operand
128 void *operator new(size_t s) {
129 return User::operator new(s, 1);
130 }
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000131 explicit ConstantPlaceHolder(const Type *Ty)
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000132 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
133 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000134 }
135 };
136}
137
138Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
139 const Type *Ty) {
140 if (Idx >= size()) {
141 // Insert a bunch of null values.
142 Uses.resize(Idx+1);
143 OperandList = &Uses[0];
144 NumOperands = Idx+1;
145 }
146
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000147 if (Value *V = Uses[Idx]) {
148 assert(Ty == V->getType() && "Type mismatch in constant table!");
149 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000150 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000151
152 // Create and return a placeholder, which will later be RAUW'd.
153 Constant *C = new ConstantPlaceHolder(Ty);
154 Uses[Idx].init(C, this);
155 return C;
156}
157
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000158Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
159 if (Idx >= size()) {
160 // Insert a bunch of null values.
161 Uses.resize(Idx+1);
162 OperandList = &Uses[0];
163 NumOperands = Idx+1;
164 }
165
166 if (Value *V = Uses[Idx]) {
167 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
168 return V;
169 }
170
Chris Lattner01ff65f2007-05-02 05:16:49 +0000171 // No type specified, must be invalid reference.
172 if (Ty == 0) return 0;
173
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000174 // Create and return a placeholder, which will later be RAUW'd.
175 Value *V = new Argument(Ty);
176 Uses[Idx].init(V, this);
177 return V;
178}
179
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000180
181const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
182 // If the TypeID is in range, return it.
183 if (ID < TypeList.size())
184 return TypeList[ID].get();
185 if (!isTypeTable) return 0;
186
187 // The type table allows forward references. Push as many Opaque types as
188 // needed to get up to ID.
189 while (TypeList.size() <= ID)
190 TypeList.push_back(OpaqueType::get());
191 return TypeList.back().get();
192}
193
Chris Lattner48c85b82007-05-04 03:30:17 +0000194//===----------------------------------------------------------------------===//
195// Functions for parsing blocks from the bitcode file
196//===----------------------------------------------------------------------===//
197
198bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000199 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000200 return Error("Malformed block record");
201
202 if (!ParamAttrs.empty())
203 return Error("Multiple PARAMATTR blocks found!");
204
205 SmallVector<uint64_t, 64> Record;
206
Chris Lattner58d74912008-03-12 17:45:29 +0000207 SmallVector<ParamAttrsWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000208
209 // Read all the records.
210 while (1) {
211 unsigned Code = Stream.ReadCode();
212 if (Code == bitc::END_BLOCK) {
213 if (Stream.ReadBlockEnd())
214 return Error("Error at end of PARAMATTR block");
215 return false;
216 }
217
218 if (Code == bitc::ENTER_SUBBLOCK) {
219 // No known subblocks, always skip them.
220 Stream.ReadSubBlockID();
221 if (Stream.SkipBlock())
222 return Error("Malformed block record");
223 continue;
224 }
225
226 if (Code == bitc::DEFINE_ABBREV) {
227 Stream.ReadAbbrevRecord();
228 continue;
229 }
230
231 // Read a record.
232 Record.clear();
233 switch (Stream.ReadRecord(Code, Record)) {
234 default: // Default behavior: ignore.
235 break;
236 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
237 if (Record.size() & 1)
238 return Error("Invalid ENTRY record");
239
Chris Lattner48c85b82007-05-04 03:30:17 +0000240 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Duncan Sands5e41f652007-11-20 14:09:29 +0000241 if (Record[i+1] != ParamAttr::None)
242 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
Chris Lattner48c85b82007-05-04 03:30:17 +0000243 }
Chris Lattner461edd92008-03-12 02:25:52 +0000244
Chris Lattner58d74912008-03-12 17:45:29 +0000245 ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000246 Attrs.clear();
247 break;
248 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000249 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000250 }
251}
252
253
Chris Lattner86697142007-05-01 05:01:34 +0000254bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000255 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000256 return Error("Malformed block record");
257
258 if (!TypeList.empty())
259 return Error("Multiple TYPE_BLOCKs found!");
260
261 SmallVector<uint64_t, 64> Record;
262 unsigned NumRecords = 0;
263
264 // Read all the records for this type table.
265 while (1) {
266 unsigned Code = Stream.ReadCode();
267 if (Code == bitc::END_BLOCK) {
268 if (NumRecords != TypeList.size())
269 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000270 if (Stream.ReadBlockEnd())
271 return Error("Error at end of type table block");
272 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000273 }
274
275 if (Code == bitc::ENTER_SUBBLOCK) {
276 // No known subblocks, always skip them.
277 Stream.ReadSubBlockID();
278 if (Stream.SkipBlock())
279 return Error("Malformed block record");
280 continue;
281 }
282
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000283 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000284 Stream.ReadAbbrevRecord();
285 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000286 }
287
288 // Read a record.
289 Record.clear();
290 const Type *ResultTy = 0;
291 switch (Stream.ReadRecord(Code, Record)) {
292 default: // Default behavior: unknown type.
293 ResultTy = 0;
294 break;
295 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
296 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
297 // type list. This allows us to reserve space.
298 if (Record.size() < 1)
299 return Error("Invalid TYPE_CODE_NUMENTRY record");
300 TypeList.reserve(Record[0]);
301 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000302 case bitc::TYPE_CODE_VOID: // VOID
303 ResultTy = Type::VoidTy;
304 break;
305 case bitc::TYPE_CODE_FLOAT: // FLOAT
306 ResultTy = Type::FloatTy;
307 break;
308 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
309 ResultTy = Type::DoubleTy;
310 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000311 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
312 ResultTy = Type::X86_FP80Ty;
313 break;
314 case bitc::TYPE_CODE_FP128: // FP128
315 ResultTy = Type::FP128Ty;
316 break;
317 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
318 ResultTy = Type::PPC_FP128Ty;
319 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000320 case bitc::TYPE_CODE_LABEL: // LABEL
321 ResultTy = Type::LabelTy;
322 break;
323 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
324 ResultTy = 0;
325 break;
326 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
327 if (Record.size() < 1)
328 return Error("Invalid Integer type record");
329
330 ResultTy = IntegerType::get(Record[0]);
331 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000332 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
333 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000334 if (Record.size() < 1)
335 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000336 unsigned AddressSpace = 0;
337 if (Record.size() == 2)
338 AddressSpace = Record[1];
339 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000340 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000341 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000342 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000343 // FIXME: attrid is dead, remove it in LLVM 3.0
344 // FUNCTION: [vararg, attrid, retty, paramty x N]
345 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000346 return Error("Invalid FUNCTION type record");
347 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000348 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000349 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000350
Chris Lattnera1afde72007-11-27 17:48:06 +0000351 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000352 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000353 break;
354 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000355 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000356 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000357 return Error("Invalid STRUCT type record");
358 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000359 for (unsigned i = 1, e = Record.size(); i != e; ++i)
360 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000361 ResultTy = StructType::get(EltTys, Record[0]);
362 break;
363 }
364 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
365 if (Record.size() < 2)
366 return Error("Invalid ARRAY type record");
367 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
368 break;
369 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
370 if (Record.size() < 2)
371 return Error("Invalid VECTOR type record");
372 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
373 break;
374 }
375
376 if (NumRecords == TypeList.size()) {
377 // If this is a new type slot, just append it.
378 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
379 ++NumRecords;
380 } else if (ResultTy == 0) {
381 // Otherwise, this was forward referenced, so an opaque type was created,
382 // but the result type is actually just an opaque. Leave the one we
383 // created previously.
384 ++NumRecords;
385 } else {
386 // Otherwise, this was forward referenced, so an opaque type was created.
387 // Resolve the opaque type to the real type now.
388 assert(NumRecords < TypeList.size() && "Typelist imbalance");
389 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
390
391 // Don't directly push the new type on the Tab. Instead we want to replace
392 // the opaque type we previously inserted with the new concrete value. The
393 // refinement from the abstract (opaque) type to the new type causes all
394 // uses of the abstract type to use the concrete type (NewTy). This will
395 // also cause the opaque type to be deleted.
396 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
397
398 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000399 // value table... or with a preexisting type that was already in the
400 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000401 assert(TypeList[NumRecords-1].get() != OldTy &&
402 "refineAbstractType didn't work!");
403 }
404 }
405}
406
407
Chris Lattner86697142007-05-01 05:01:34 +0000408bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000409 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000410 return Error("Malformed block record");
411
412 SmallVector<uint64_t, 64> Record;
413
414 // Read all the records for this type table.
415 std::string TypeName;
416 while (1) {
417 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000418 if (Code == bitc::END_BLOCK) {
419 if (Stream.ReadBlockEnd())
420 return Error("Error at end of type symbol table block");
421 return false;
422 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000423
424 if (Code == bitc::ENTER_SUBBLOCK) {
425 // No known subblocks, always skip them.
426 Stream.ReadSubBlockID();
427 if (Stream.SkipBlock())
428 return Error("Malformed block record");
429 continue;
430 }
431
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000432 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000433 Stream.ReadAbbrevRecord();
434 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000435 }
436
437 // Read a record.
438 Record.clear();
439 switch (Stream.ReadRecord(Code, Record)) {
440 default: // Default behavior: unknown type.
441 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000442 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000443 if (ConvertToString(Record, 1, TypeName))
444 return Error("Invalid TST_ENTRY record");
445 unsigned TypeID = Record[0];
446 if (TypeID >= TypeList.size())
447 return Error("Invalid Type ID in TST_ENTRY record");
448
449 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
450 TypeName.clear();
451 break;
452 }
453 }
454}
455
Chris Lattner86697142007-05-01 05:01:34 +0000456bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000457 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000458 return Error("Malformed block record");
459
460 SmallVector<uint64_t, 64> Record;
461
462 // Read all the records for this value table.
463 SmallString<128> ValueName;
464 while (1) {
465 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000466 if (Code == bitc::END_BLOCK) {
467 if (Stream.ReadBlockEnd())
468 return Error("Error at end of value symbol table block");
469 return false;
470 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000471 if (Code == bitc::ENTER_SUBBLOCK) {
472 // No known subblocks, always skip them.
473 Stream.ReadSubBlockID();
474 if (Stream.SkipBlock())
475 return Error("Malformed block record");
476 continue;
477 }
478
479 if (Code == bitc::DEFINE_ABBREV) {
480 Stream.ReadAbbrevRecord();
481 continue;
482 }
483
484 // Read a record.
485 Record.clear();
486 switch (Stream.ReadRecord(Code, Record)) {
487 default: // Default behavior: unknown type.
488 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000489 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000490 if (ConvertToString(Record, 1, ValueName))
491 return Error("Invalid TST_ENTRY record");
492 unsigned ValueID = Record[0];
493 if (ValueID >= ValueList.size())
494 return Error("Invalid Value ID in VST_ENTRY record");
495 Value *V = ValueList[ValueID];
496
497 V->setName(&ValueName[0], ValueName.size());
498 ValueName.clear();
499 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000500 }
501 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000502 if (ConvertToString(Record, 1, ValueName))
503 return Error("Invalid VST_BBENTRY record");
504 BasicBlock *BB = getBasicBlock(Record[0]);
505 if (BB == 0)
506 return Error("Invalid BB ID in VST_BBENTRY record");
507
508 BB->setName(&ValueName[0], ValueName.size());
509 ValueName.clear();
510 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000511 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000512 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000513 }
514}
515
Chris Lattner0eef0802007-04-24 04:04:35 +0000516/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
517/// the LSB for dense VBR encoding.
518static uint64_t DecodeSignRotatedValue(uint64_t V) {
519 if ((V & 1) == 0)
520 return V >> 1;
521 if (V != 1)
522 return -(V >> 1);
523 // There is no such thing as -0 with integers. "-0" really means MININT.
524 return 1ULL << 63;
525}
526
Chris Lattner07d98b42007-04-26 02:46:40 +0000527/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
528/// values and aliases that we can.
529bool BitcodeReader::ResolveGlobalAndAliasInits() {
530 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
531 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
532
533 GlobalInitWorklist.swap(GlobalInits);
534 AliasInitWorklist.swap(AliasInits);
535
536 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000537 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000538 if (ValID >= ValueList.size()) {
539 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000540 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000541 } else {
542 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
543 GlobalInitWorklist.back().first->setInitializer(C);
544 else
545 return Error("Global variable initializer is not a constant!");
546 }
547 GlobalInitWorklist.pop_back();
548 }
549
550 while (!AliasInitWorklist.empty()) {
551 unsigned ValID = AliasInitWorklist.back().second;
552 if (ValID >= ValueList.size()) {
553 AliasInits.push_back(AliasInitWorklist.back());
554 } else {
555 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000556 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000557 else
558 return Error("Alias initializer is not a constant!");
559 }
560 AliasInitWorklist.pop_back();
561 }
562 return false;
563}
564
565
Chris Lattner86697142007-05-01 05:01:34 +0000566bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000567 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000568 return Error("Malformed block record");
569
570 SmallVector<uint64_t, 64> Record;
571
572 // Read all the records for this value table.
573 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000574 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000575 while (1) {
576 unsigned Code = Stream.ReadCode();
577 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000578 if (NextCstNo != ValueList.size())
579 return Error("Invalid constant reference!");
580
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000581 if (Stream.ReadBlockEnd())
582 return Error("Error at end of constants block");
583 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000584 }
585
586 if (Code == bitc::ENTER_SUBBLOCK) {
587 // No known subblocks, always skip them.
588 Stream.ReadSubBlockID();
589 if (Stream.SkipBlock())
590 return Error("Malformed block record");
591 continue;
592 }
593
594 if (Code == bitc::DEFINE_ABBREV) {
595 Stream.ReadAbbrevRecord();
596 continue;
597 }
598
599 // Read a record.
600 Record.clear();
601 Value *V = 0;
602 switch (Stream.ReadRecord(Code, Record)) {
603 default: // Default behavior: unknown constant
604 case bitc::CST_CODE_UNDEF: // UNDEF
605 V = UndefValue::get(CurTy);
606 break;
607 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
608 if (Record.empty())
609 return Error("Malformed CST_SETTYPE record");
610 if (Record[0] >= TypeList.size())
611 return Error("Invalid Type ID in CST_SETTYPE record");
612 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000613 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000614 case bitc::CST_CODE_NULL: // NULL
615 V = Constant::getNullValue(CurTy);
616 break;
617 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000618 if (!isa<IntegerType>(CurTy) || Record.empty())
619 return Error("Invalid CST_INTEGER record");
620 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
621 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000622 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
623 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000624 return Error("Invalid WIDE_INTEGER record");
625
Chris Lattner15e6d172007-05-04 19:11:41 +0000626 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000627 SmallVector<uint64_t, 8> Words;
628 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000629 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000630 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000631 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000632 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000633 break;
634 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000635 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000636 if (Record.empty())
637 return Error("Invalid FLOAT record");
638 if (CurTy == Type::FloatTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000639 V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000640 else if (CurTy == Type::DoubleTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000641 V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000642 else if (CurTy == Type::X86_FP80Ty)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000643 V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000644 else if (CurTy == Type::FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000645 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000646 else if (CurTy == Type::PPC_FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000647 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000648 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000649 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000650 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000651 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000652
Chris Lattner15e6d172007-05-04 19:11:41 +0000653 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
654 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000655 return Error("Invalid CST_AGGREGATE record");
656
Chris Lattner15e6d172007-05-04 19:11:41 +0000657 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000658 std::vector<Constant*> Elts;
659
660 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
661 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000662 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000663 STy->getElementType(i)));
664 V = ConstantStruct::get(STy, Elts);
665 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
666 const Type *EltTy = ATy->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 = ConstantArray::get(ATy, Elts);
670 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
671 const Type *EltTy = VTy->getElementType();
672 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000673 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000674 V = ConstantVector::get(Elts);
675 } else {
676 V = UndefValue::get(CurTy);
677 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000678 break;
679 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000680 case bitc::CST_CODE_STRING: { // STRING: [values]
681 if (Record.empty())
682 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000683
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000684 const ArrayType *ATy = cast<ArrayType>(CurTy);
685 const Type *EltTy = ATy->getElementType();
686
687 unsigned Size = Record.size();
688 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000689 for (unsigned i = 0; i != Size; ++i)
690 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
691 V = ConstantArray::get(ATy, Elts);
692 break;
693 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000694 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
695 if (Record.empty())
696 return Error("Invalid CST_AGGREGATE record");
697
698 const ArrayType *ATy = cast<ArrayType>(CurTy);
699 const Type *EltTy = ATy->getElementType();
700
701 unsigned Size = Record.size();
702 std::vector<Constant*> Elts;
703 for (unsigned i = 0; i != Size; ++i)
704 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
705 Elts.push_back(Constant::getNullValue(EltTy));
706 V = ConstantArray::get(ATy, Elts);
707 break;
708 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000709 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
710 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
711 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000712 if (Opc < 0) {
713 V = UndefValue::get(CurTy); // Unknown binop.
714 } else {
715 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
716 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
717 V = ConstantExpr::get(Opc, LHS, RHS);
718 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000719 break;
720 }
721 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
722 if (Record.size() < 3) return Error("Invalid CE_CAST record");
723 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000724 if (Opc < 0) {
725 V = UndefValue::get(CurTy); // Unknown cast.
726 } else {
727 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000728 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000729 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
730 V = ConstantExpr::getCast(Opc, Op, CurTy);
731 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000732 break;
733 }
734 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000735 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000736 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000737 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000738 const Type *ElTy = getTypeByID(Record[i]);
739 if (!ElTy) return Error("Invalid CE_GEP record");
740 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
741 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000742 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
743 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000744 }
745 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
746 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
747 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
748 Type::Int1Ty),
749 ValueList.getConstantFwdRef(Record[1],CurTy),
750 ValueList.getConstantFwdRef(Record[2],CurTy));
751 break;
752 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
753 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
754 const VectorType *OpTy =
755 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
756 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
757 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
758 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
759 OpTy->getElementType());
760 V = ConstantExpr::getExtractElement(Op0, Op1);
761 break;
762 }
763 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
764 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
765 if (Record.size() < 3 || OpTy == 0)
766 return Error("Invalid CE_INSERTELT record");
767 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
768 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
769 OpTy->getElementType());
770 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
771 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
772 break;
773 }
774 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
775 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
776 if (Record.size() < 3 || OpTy == 0)
777 return Error("Invalid CE_INSERTELT record");
778 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
779 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
780 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
781 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
782 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
783 break;
784 }
785 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
786 if (Record.size() < 4) return Error("Invalid CE_CMP record");
787 const Type *OpTy = getTypeByID(Record[0]);
788 if (OpTy == 0) return Error("Invalid CE_CMP record");
789 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
790 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
791
792 if (OpTy->isFloatingPoint())
793 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
794 else
795 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
796 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000797 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000798 case bitc::CST_CODE_INLINEASM: {
799 if (Record.size() < 2) return Error("Invalid INLINEASM record");
800 std::string AsmStr, ConstrStr;
801 bool HasSideEffects = Record[0];
802 unsigned AsmStrSize = Record[1];
803 if (2+AsmStrSize >= Record.size())
804 return Error("Invalid INLINEASM record");
805 unsigned ConstStrSize = Record[2+AsmStrSize];
806 if (3+AsmStrSize+ConstStrSize > Record.size())
807 return Error("Invalid INLINEASM record");
808
809 for (unsigned i = 0; i != AsmStrSize; ++i)
810 AsmStr += (char)Record[2+i];
811 for (unsigned i = 0; i != ConstStrSize; ++i)
812 ConstrStr += (char)Record[3+AsmStrSize+i];
813 const PointerType *PTy = cast<PointerType>(CurTy);
814 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
815 AsmStr, ConstrStr, HasSideEffects);
816 break;
817 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000818 }
819
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000820 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000821 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000822 }
823}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000824
Chris Lattner980e5aa2007-05-01 05:52:21 +0000825/// RememberAndSkipFunctionBody - When we see the block for a function body,
826/// remember where it is and then skip it. This lets us lazily deserialize the
827/// functions.
828bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000829 // Get the function we are talking about.
830 if (FunctionsWithBodies.empty())
831 return Error("Insufficient function protos");
832
833 Function *Fn = FunctionsWithBodies.back();
834 FunctionsWithBodies.pop_back();
835
836 // Save the current stream state.
837 uint64_t CurBit = Stream.GetCurrentBitNo();
838 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
839
840 // Set the functions linkage to GhostLinkage so we know it is lazily
841 // deserialized.
842 Fn->setLinkage(GlobalValue::GhostLinkage);
843
844 // Skip over the function block for now.
845 if (Stream.SkipBlock())
846 return Error("Malformed block record");
847 return false;
848}
849
Chris Lattner86697142007-05-01 05:01:34 +0000850bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000851 // Reject multiple MODULE_BLOCK's in a single bitstream.
852 if (TheModule)
853 return Error("Multiple MODULE_BLOCKs in same stream");
854
Chris Lattnere17b6582007-05-05 00:17:00 +0000855 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000856 return Error("Malformed block record");
857
858 // Otherwise, create the module.
859 TheModule = new Module(ModuleID);
860
861 SmallVector<uint64_t, 64> Record;
862 std::vector<std::string> SectionTable;
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000863 std::vector<std::string> CollectorTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000864
865 // Read all the records for this module.
866 while (!Stream.AtEndOfStream()) {
867 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000868 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000869 if (Stream.ReadBlockEnd())
870 return Error("Error at end of module block");
871
872 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000873 ResolveGlobalAndAliasInits();
874 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000875 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000876 if (!FunctionsWithBodies.empty())
877 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000878
Chandler Carruth69940402007-08-04 01:51:18 +0000879 // Look for intrinsic functions which need to be upgraded at some point
880 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
881 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +0000882 Function* NewFn;
883 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +0000884 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
885 }
886
Chris Lattner980e5aa2007-05-01 05:52:21 +0000887 // Force deallocation of memory for these vectors to favor the client that
888 // want lazy deserialization.
889 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
890 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
891 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000892 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000893 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000894
895 if (Code == bitc::ENTER_SUBBLOCK) {
896 switch (Stream.ReadSubBlockID()) {
897 default: // Skip unknown content.
898 if (Stream.SkipBlock())
899 return Error("Malformed block record");
900 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000901 case bitc::BLOCKINFO_BLOCK_ID:
902 if (Stream.ReadBlockInfoBlock())
903 return Error("Malformed BlockInfoBlock");
904 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000905 case bitc::PARAMATTR_BLOCK_ID:
906 if (ParseParamAttrBlock())
907 return true;
908 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000909 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000910 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000911 return true;
912 break;
913 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000914 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000915 return true;
916 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000917 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000918 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000919 return true;
920 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000921 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000922 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000923 return true;
924 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000925 case bitc::FUNCTION_BLOCK_ID:
926 // If this is the first function body we've seen, reverse the
927 // FunctionsWithBodies list.
928 if (!HasReversedFunctionsWithBodies) {
929 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
930 HasReversedFunctionsWithBodies = true;
931 }
932
Chris Lattner980e5aa2007-05-01 05:52:21 +0000933 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000934 return true;
935 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000936 }
937 continue;
938 }
939
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000940 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000941 Stream.ReadAbbrevRecord();
942 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000943 }
944
945 // Read a record.
946 switch (Stream.ReadRecord(Code, Record)) {
947 default: break; // Default behavior, ignore unknown content.
948 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
949 if (Record.size() < 1)
950 return Error("Malformed MODULE_CODE_VERSION");
951 // Only version #0 is supported so far.
952 if (Record[0] != 0)
953 return Error("Unknown bitstream version!");
954 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000955 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000956 std::string S;
957 if (ConvertToString(Record, 0, S))
958 return Error("Invalid MODULE_CODE_TRIPLE record");
959 TheModule->setTargetTriple(S);
960 break;
961 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000962 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000963 std::string S;
964 if (ConvertToString(Record, 0, S))
965 return Error("Invalid MODULE_CODE_DATALAYOUT record");
966 TheModule->setDataLayout(S);
967 break;
968 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000969 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000970 std::string S;
971 if (ConvertToString(Record, 0, S))
972 return Error("Invalid MODULE_CODE_ASM record");
973 TheModule->setModuleInlineAsm(S);
974 break;
975 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000976 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000977 std::string S;
978 if (ConvertToString(Record, 0, S))
979 return Error("Invalid MODULE_CODE_DEPLIB record");
980 TheModule->addLibrary(S);
981 break;
982 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000983 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000984 std::string S;
985 if (ConvertToString(Record, 0, S))
986 return Error("Invalid MODULE_CODE_SECTIONNAME record");
987 SectionTable.push_back(S);
988 break;
989 }
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000990 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
991 std::string S;
992 if (ConvertToString(Record, 0, S))
993 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
994 CollectorTable.push_back(S);
995 break;
996 }
Christopher Lambfe63fb92007-12-11 08:59:05 +0000997 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000998 // linkage, alignment, section, visibility, threadlocal]
999 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001000 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001001 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1002 const Type *Ty = getTypeByID(Record[0]);
1003 if (!isa<PointerType>(Ty))
1004 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001005 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001006 Ty = cast<PointerType>(Ty)->getElementType();
1007
1008 bool isConstant = Record[1];
1009 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1010 unsigned Alignment = (1 << Record[4]) >> 1;
1011 std::string Section;
1012 if (Record[5]) {
1013 if (Record[5]-1 >= SectionTable.size())
1014 return Error("Invalid section ID");
1015 Section = SectionTable[Record[5]-1];
1016 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001017 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001018 if (Record.size() > 6)
1019 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001020 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001021 if (Record.size() > 7)
1022 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001023
1024 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001025 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1026 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001027 NewGV->setAlignment(Alignment);
1028 if (!Section.empty())
1029 NewGV->setSection(Section);
1030 NewGV->setVisibility(Visibility);
1031 NewGV->setThreadLocal(isThreadLocal);
1032
Chris Lattner0b2482a2007-04-23 21:26:05 +00001033 ValueList.push_back(NewGV);
1034
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001035 // Remember which value to use for the global initializer.
1036 if (unsigned InitID = Record[2])
1037 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001038 break;
1039 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001040 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001041 // alignment, section, visibility, collector]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001042 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001043 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001044 return Error("Invalid MODULE_CODE_FUNCTION record");
1045 const Type *Ty = getTypeByID(Record[0]);
1046 if (!isa<PointerType>(Ty))
1047 return Error("Function not a pointer type!");
1048 const FunctionType *FTy =
1049 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1050 if (!FTy)
1051 return Error("Function not a pointer to function type!");
1052
Gabor Greif051a9502008-04-06 20:25:17 +00001053 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1054 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001055
1056 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001057 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001058 Func->setLinkage(GetDecodedLinkage(Record[3]));
Chris Lattner58d74912008-03-12 17:45:29 +00001059 Func->setParamAttrs(getParamAttrs(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001060
1061 Func->setAlignment((1 << Record[5]) >> 1);
1062 if (Record[6]) {
1063 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001064 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001065 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001066 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001067 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001068 if (Record.size() > 8 && Record[8]) {
1069 if (Record[8]-1 > CollectorTable.size())
1070 return Error("Invalid collector ID");
1071 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1072 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001073
Chris Lattner0b2482a2007-04-23 21:26:05 +00001074 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001075
1076 // If this is a function with a body, remember the prototype we are
1077 // creating now, so that we can match up the body with them later.
1078 if (!isProto)
1079 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001080 break;
1081 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001082 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001083 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001084 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001085 if (Record.size() < 3)
1086 return Error("Invalid MODULE_ALIAS record");
1087 const Type *Ty = getTypeByID(Record[0]);
1088 if (!isa<PointerType>(Ty))
1089 return Error("Function not a pointer type!");
1090
1091 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1092 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001093 // Old bitcode files didn't have visibility field.
1094 if (Record.size() > 3)
1095 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001096 ValueList.push_back(NewGA);
1097 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1098 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001099 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001100 /// MODULE_CODE_PURGEVALS: [numvals]
1101 case bitc::MODULE_CODE_PURGEVALS:
1102 // Trim down the value list to the specified size.
1103 if (Record.size() < 1 || Record[0] > ValueList.size())
1104 return Error("Invalid MODULE_PURGEVALS record");
1105 ValueList.shrinkTo(Record[0]);
1106 break;
1107 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001108 Record.clear();
1109 }
1110
1111 return Error("Premature end of bitstream");
1112}
1113
1114
Chris Lattnerc453f762007-04-29 07:54:31 +00001115bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001116 TheModule = 0;
1117
Chris Lattnerc453f762007-04-29 07:54:31 +00001118 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001119 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1120
Chris Lattnerc453f762007-04-29 07:54:31 +00001121 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001122 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001123
1124 // Sniff for the signature.
1125 if (Stream.Read(8) != 'B' ||
1126 Stream.Read(8) != 'C' ||
1127 Stream.Read(4) != 0x0 ||
1128 Stream.Read(4) != 0xC ||
1129 Stream.Read(4) != 0xE ||
1130 Stream.Read(4) != 0xD)
1131 return Error("Invalid bitcode signature");
1132
1133 // We expect a number of well-defined blocks, though we don't necessarily
1134 // need to understand them all.
1135 while (!Stream.AtEndOfStream()) {
1136 unsigned Code = Stream.ReadCode();
1137
1138 if (Code != bitc::ENTER_SUBBLOCK)
1139 return Error("Invalid record at top-level");
1140
1141 unsigned BlockID = Stream.ReadSubBlockID();
1142
1143 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001144 switch (BlockID) {
1145 case bitc::BLOCKINFO_BLOCK_ID:
1146 if (Stream.ReadBlockInfoBlock())
1147 return Error("Malformed BlockInfoBlock");
1148 break;
1149 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001150 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001151 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001152 break;
1153 default:
1154 if (Stream.SkipBlock())
1155 return Error("Malformed block record");
1156 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001157 }
1158 }
1159
1160 return false;
1161}
Chris Lattnerc453f762007-04-29 07:54:31 +00001162
Chris Lattner48f84872007-05-01 04:59:48 +00001163
Chris Lattner980e5aa2007-05-01 05:52:21 +00001164/// ParseFunctionBody - Lazily parse the specified function body block.
1165bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001166 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001167 return Error("Malformed block record");
1168
1169 unsigned ModuleValueListSize = ValueList.size();
1170
1171 // Add all the function arguments to the value table.
1172 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1173 ValueList.push_back(I);
1174
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001175 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001176 BasicBlock *CurBB = 0;
1177 unsigned CurBBNo = 0;
1178
Chris Lattner980e5aa2007-05-01 05:52:21 +00001179 // Read all the records.
1180 SmallVector<uint64_t, 64> Record;
1181 while (1) {
1182 unsigned Code = Stream.ReadCode();
1183 if (Code == bitc::END_BLOCK) {
1184 if (Stream.ReadBlockEnd())
1185 return Error("Error at end of function block");
1186 break;
1187 }
1188
1189 if (Code == bitc::ENTER_SUBBLOCK) {
1190 switch (Stream.ReadSubBlockID()) {
1191 default: // Skip unknown content.
1192 if (Stream.SkipBlock())
1193 return Error("Malformed block record");
1194 break;
1195 case bitc::CONSTANTS_BLOCK_ID:
1196 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001197 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001198 break;
1199 case bitc::VALUE_SYMTAB_BLOCK_ID:
1200 if (ParseValueSymbolTable()) return true;
1201 break;
1202 }
1203 continue;
1204 }
1205
1206 if (Code == bitc::DEFINE_ABBREV) {
1207 Stream.ReadAbbrevRecord();
1208 continue;
1209 }
1210
1211 // Read a record.
1212 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001213 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001214 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001215 default: // Default behavior: reject
1216 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001217 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001218 if (Record.size() < 1 || Record[0] == 0)
1219 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001220 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001221 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001222 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001223 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001224 CurBB = FunctionBBs[0];
1225 continue;
1226
Nick Lewyckyfc82fab2008-03-02 02:48:09 +00001227 case bitc::FUNC_CODE_INST_BB_UNWINDDEST: // BB_UNWINDDEST: [bb#]
1228 if (CurBB->getUnwindDest())
1229 return Error("Only permit one BB_UNWINDDEST per BB");
1230 if (Record.size() != 1)
1231 return Error("Invalid BB_UNWINDDEST record");
1232
1233 CurBB->setUnwindDest(getBasicBlock(Record[0]));
1234 continue;
1235
Chris Lattnerabfbf852007-05-06 00:21:25 +00001236 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1237 unsigned OpNum = 0;
1238 Value *LHS, *RHS;
1239 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1240 getValue(Record, OpNum, LHS->getType(), RHS) ||
1241 OpNum+1 != Record.size())
1242 return Error("Invalid BINOP record");
1243
1244 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1245 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001246 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001247 break;
1248 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001249 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1250 unsigned OpNum = 0;
1251 Value *Op;
1252 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1253 OpNum+2 != Record.size())
1254 return Error("Invalid CAST record");
1255
1256 const Type *ResTy = getTypeByID(Record[OpNum]);
1257 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1258 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001259 return Error("Invalid CAST record");
1260 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1261 break;
1262 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001263 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001264 unsigned OpNum = 0;
1265 Value *BasePtr;
1266 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001267 return Error("Invalid GEP record");
1268
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001269 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001270 while (OpNum != Record.size()) {
1271 Value *Op;
1272 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001273 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001274 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001275 }
1276
Gabor Greif051a9502008-04-06 20:25:17 +00001277 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001278 break;
1279 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001280
Chris Lattnerabfbf852007-05-06 00:21:25 +00001281 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1282 unsigned OpNum = 0;
1283 Value *TrueVal, *FalseVal, *Cond;
1284 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1285 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1286 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001287 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001288
Gabor Greif051a9502008-04-06 20:25:17 +00001289 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001290 break;
1291 }
1292
1293 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001294 unsigned OpNum = 0;
1295 Value *Vec, *Idx;
1296 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1297 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001298 return Error("Invalid EXTRACTELT record");
1299 I = new ExtractElementInst(Vec, Idx);
1300 break;
1301 }
1302
1303 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001304 unsigned OpNum = 0;
1305 Value *Vec, *Elt, *Idx;
1306 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1307 getValue(Record, OpNum,
1308 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1309 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001310 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001311 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001312 break;
1313 }
1314
Chris Lattnerabfbf852007-05-06 00:21:25 +00001315 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1316 unsigned OpNum = 0;
1317 Value *Vec1, *Vec2, *Mask;
1318 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1319 getValue(Record, OpNum, Vec1->getType(), Vec2))
1320 return Error("Invalid SHUFFLEVEC record");
1321
1322 const Type *MaskTy =
1323 VectorType::get(Type::Int32Ty,
1324 cast<VectorType>(Vec1->getType())->getNumElements());
1325
1326 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001327 return Error("Invalid SHUFFLEVEC record");
1328 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1329 break;
1330 }
1331
1332 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001333 unsigned OpNum = 0;
1334 Value *LHS, *RHS;
1335 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1336 getValue(Record, OpNum, LHS->getType(), RHS) ||
1337 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001338 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001339
1340 if (LHS->getType()->isFPOrFPVector())
1341 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001342 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001343 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001344 break;
1345 }
Devang Patel197be3d2008-02-22 02:49:49 +00001346 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1347 if (Record.size() != 2)
1348 return Error("Invalid GETRESULT record");
1349 unsigned OpNum = 0;
1350 Value *Op;
1351 getValueTypePair(Record, OpNum, NextValueNo, Op);
1352 unsigned Index = Record[1];
1353 I = new GetResultInst(Op, Index);
1354 break;
1355 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001356
Chris Lattner231cbcb2007-05-02 04:27:25 +00001357 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001358 {
1359 unsigned Size = Record.size();
1360 if (Size == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00001361 I = ReturnInst::Create();
Devang Pateld9d99ff2008-02-26 01:29:32 +00001362 break;
1363 } else {
1364 unsigned OpNum = 0;
Devang Patelf4511cd2008-02-26 19:38:17 +00001365 SmallVector<Value *,4> Vs;
Devang Pateld9d99ff2008-02-26 01:29:32 +00001366 do {
1367 Value *Op = NULL;
1368 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1369 return Error("Invalid RET record");
1370 Vs.push_back(Op);
1371 } while(OpNum != Record.size());
1372
Devang Patelf4511cd2008-02-26 19:38:17 +00001373 // SmallVector Vs has at least one element.
Gabor Greif051a9502008-04-06 20:25:17 +00001374 I = ReturnInst::Create(&Vs[0], Vs.size());
Devang Pateld9d99ff2008-02-26 01:29:32 +00001375 break;
1376 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001377 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001378 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001379 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001380 return Error("Invalid BR record");
1381 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1382 if (TrueDest == 0)
1383 return Error("Invalid BR record");
1384
1385 if (Record.size() == 1)
Gabor Greif051a9502008-04-06 20:25:17 +00001386 I = BranchInst::Create(TrueDest);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001387 else {
1388 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1389 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1390 if (FalseDest == 0 || Cond == 0)
1391 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001392 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001393 }
1394 break;
1395 }
1396 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1397 if (Record.size() < 3 || (Record.size() & 1) == 0)
1398 return Error("Invalid SWITCH record");
1399 const Type *OpTy = getTypeByID(Record[0]);
1400 Value *Cond = getFnValueByID(Record[1], OpTy);
1401 BasicBlock *Default = getBasicBlock(Record[2]);
1402 if (OpTy == 0 || Cond == 0 || Default == 0)
1403 return Error("Invalid SWITCH record");
1404 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001405 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001406 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1407 ConstantInt *CaseVal =
1408 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1409 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1410 if (CaseVal == 0 || DestBB == 0) {
1411 delete SI;
1412 return Error("Invalid SWITCH record!");
1413 }
1414 SI->addCase(CaseVal, DestBB);
1415 }
1416 I = SI;
1417 break;
1418 }
1419
Duncan Sandsdc024672007-11-27 13:23:08 +00001420 case bitc::FUNC_CODE_INST_INVOKE: {
1421 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001422 if (Record.size() < 4) return Error("Invalid INVOKE record");
Chris Lattner58d74912008-03-12 17:45:29 +00001423 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001424 unsigned CCInfo = Record[1];
1425 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1426 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001427
Chris Lattnera9bb7132007-05-08 05:38:01 +00001428 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001429 Value *Callee;
1430 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001431 return Error("Invalid INVOKE record");
1432
Chris Lattner7337ab92007-05-06 00:00:00 +00001433 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1434 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001435 dyn_cast<FunctionType>(CalleeTy->getElementType());
1436
1437 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001438 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1439 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001440 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001441
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001442 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001443 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1444 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1445 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001446 }
1447
Chris Lattner7337ab92007-05-06 00:00:00 +00001448 if (!FTy->isVarArg()) {
1449 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001450 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001451 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001452 // Read type/value pairs for varargs params.
1453 while (OpNum != Record.size()) {
1454 Value *Op;
1455 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1456 return Error("Invalid INVOKE record");
1457 Ops.push_back(Op);
1458 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001459 }
1460
Gabor Greif051a9502008-04-06 20:25:17 +00001461 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001462 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Duncan Sandsdc024672007-11-27 13:23:08 +00001463 cast<InvokeInst>(I)->setParamAttrs(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001464 break;
1465 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001466 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1467 I = new UnwindInst();
1468 break;
1469 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1470 I = new UnreachableInst();
1471 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001472 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001473 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001474 return Error("Invalid PHI record");
1475 const Type *Ty = getTypeByID(Record[0]);
1476 if (!Ty) return Error("Invalid PHI record");
1477
Gabor Greif051a9502008-04-06 20:25:17 +00001478 PHINode *PN = PHINode::Create(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001479 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001480
Chris Lattner15e6d172007-05-04 19:11:41 +00001481 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1482 Value *V = getFnValueByID(Record[1+i], Ty);
1483 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001484 if (!V || !BB) return Error("Invalid PHI record");
1485 PN->addIncoming(V, BB);
1486 }
1487 I = PN;
1488 break;
1489 }
1490
1491 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1492 if (Record.size() < 3)
1493 return Error("Invalid MALLOC record");
1494 const PointerType *Ty =
1495 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1496 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1497 unsigned Align = Record[2];
1498 if (!Ty || !Size) return Error("Invalid MALLOC record");
1499 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1500 break;
1501 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001502 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1503 unsigned OpNum = 0;
1504 Value *Op;
1505 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1506 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001507 return Error("Invalid FREE record");
1508 I = new FreeInst(Op);
1509 break;
1510 }
1511 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1512 if (Record.size() < 3)
1513 return Error("Invalid ALLOCA record");
1514 const PointerType *Ty =
1515 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1516 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1517 unsigned Align = Record[2];
1518 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1519 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1520 break;
1521 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001522 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001523 unsigned OpNum = 0;
1524 Value *Op;
1525 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1526 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001527 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001528
1529 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001530 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001531 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001532 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1533 unsigned OpNum = 0;
1534 Value *Val, *Ptr;
1535 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1536 getValue(Record, OpNum,
1537 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1538 OpNum+2 != Record.size())
1539 return Error("Invalid STORE record");
1540
1541 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1542 break;
1543 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001544 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001545 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001546 unsigned OpNum = 0;
1547 Value *Val, *Ptr;
1548 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001549 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001550 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001551 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001552
1553 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001554 break;
1555 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001556 case bitc::FUNC_CODE_INST_CALL: {
1557 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1558 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001559 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001560
Chris Lattner58d74912008-03-12 17:45:29 +00001561 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001562 unsigned CCInfo = Record[1];
1563
1564 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001565 Value *Callee;
1566 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1567 return Error("Invalid CALL record");
1568
1569 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001570 const FunctionType *FTy = 0;
1571 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001572 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001573 return Error("Invalid CALL record");
1574
1575 SmallVector<Value*, 16> Args;
1576 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001577 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001578 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1579 Args.push_back(getBasicBlock(Record[OpNum]));
1580 else
1581 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001582 if (Args.back() == 0) return Error("Invalid CALL record");
1583 }
1584
Chris Lattner0579f7f2007-05-03 22:04:19 +00001585 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001586 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001587 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001588 return Error("Invalid CALL record");
1589 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001590 while (OpNum != Record.size()) {
1591 Value *Op;
1592 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1593 return Error("Invalid CALL record");
1594 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001595 }
1596 }
1597
Gabor Greif051a9502008-04-06 20:25:17 +00001598 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001599 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1600 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Duncan Sandsdc024672007-11-27 13:23:08 +00001601 cast<CallInst>(I)->setParamAttrs(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001602 break;
1603 }
1604 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1605 if (Record.size() < 3)
1606 return Error("Invalid VAARG record");
1607 const Type *OpTy = getTypeByID(Record[0]);
1608 Value *Op = getFnValueByID(Record[1], OpTy);
1609 const Type *ResTy = getTypeByID(Record[2]);
1610 if (!OpTy || !Op || !ResTy)
1611 return Error("Invalid VAARG record");
1612 I = new VAArgInst(Op, ResTy);
1613 break;
1614 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001615 }
1616
1617 // Add instruction to end of current BB. If there is no current BB, reject
1618 // this file.
1619 if (CurBB == 0) {
1620 delete I;
1621 return Error("Invalid instruction with no BB");
1622 }
1623 CurBB->getInstList().push_back(I);
1624
1625 // If this was a terminator instruction, move to the next block.
1626 if (isa<TerminatorInst>(I)) {
1627 ++CurBBNo;
1628 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1629 }
1630
1631 // Non-void values get registered in the value table for future use.
1632 if (I && I->getType() != Type::VoidTy)
1633 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001634 }
1635
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001636 // Check the function list for unresolved values.
1637 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1638 if (A->getParent() == 0) {
1639 // We found at least one unresolved value. Nuke them all to avoid leaks.
1640 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1641 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1642 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1643 delete A;
1644 }
1645 }
Chris Lattner35a04702007-05-04 03:50:29 +00001646 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001647 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001648 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001649
1650 // Trim the value list down to the size it was before we parsed this function.
1651 ValueList.shrinkTo(ModuleValueListSize);
1652 std::vector<BasicBlock*>().swap(FunctionBBs);
1653
Chris Lattner48f84872007-05-01 04:59:48 +00001654 return false;
1655}
1656
Chris Lattnerb348bb82007-05-18 04:02:46 +00001657//===----------------------------------------------------------------------===//
1658// ModuleProvider implementation
1659//===----------------------------------------------------------------------===//
1660
1661
1662bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1663 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001664 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001665
1666 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1667 DeferredFunctionInfo.find(F);
1668 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1669
1670 // Move the bit stream to the saved position of the deferred function body and
1671 // restore the real linkage type for the function.
1672 Stream.JumpToBit(DFII->second.first);
1673 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1674
1675 if (ParseFunctionBody(F)) {
1676 if (ErrInfo) *ErrInfo = ErrorString;
1677 return true;
1678 }
Chandler Carruth69940402007-08-04 01:51:18 +00001679
1680 // Upgrade any old intrinsic calls in the function.
1681 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1682 E = UpgradedIntrinsics.end(); I != E; ++I) {
1683 if (I->first != I->second) {
1684 for (Value::use_iterator UI = I->first->use_begin(),
1685 UE = I->first->use_end(); UI != UE; ) {
1686 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1687 UpgradeIntrinsicCall(CI, I->second);
1688 }
1689 }
1690 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001691
1692 return false;
1693}
1694
1695void BitcodeReader::dematerializeFunction(Function *F) {
1696 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001697 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001698 return;
1699
1700 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1701
1702 // Just forget the function body, we can remat it later.
1703 F->deleteBody();
1704 F->setLinkage(GlobalValue::GhostLinkage);
1705}
1706
1707
1708Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1709 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1710 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1711 ++I) {
1712 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001713 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001714 materializeFunction(F, ErrInfo))
1715 return 0;
1716 }
Chandler Carruth69940402007-08-04 01:51:18 +00001717
1718 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1719 // delete the old functions to clean up. We can't do this unless the entire
1720 // module is materialized because there could always be another function body
1721 // with calls to the old function.
1722 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1723 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1724 if (I->first != I->second) {
1725 for (Value::use_iterator UI = I->first->use_begin(),
1726 UE = I->first->use_end(); UI != UE; ) {
1727 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1728 UpgradeIntrinsicCall(CI, I->second);
1729 }
1730 ValueList.replaceUsesOfWith(I->first, I->second);
1731 I->first->eraseFromParent();
1732 }
1733 }
1734 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1735
Chris Lattnerb348bb82007-05-18 04:02:46 +00001736 return TheModule;
1737}
1738
1739
1740/// This method is provided by the parent ModuleProvde class and overriden
1741/// here. It simply releases the module from its provided and frees up our
1742/// state.
1743/// @brief Release our hold on the generated module
1744Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1745 // Since we're losing control of this Module, we must hand it back complete
1746 Module *M = ModuleProvider::releaseModule(ErrInfo);
1747 FreeState();
1748 return M;
1749}
1750
Chris Lattner48f84872007-05-01 04:59:48 +00001751
Chris Lattnerc453f762007-04-29 07:54:31 +00001752//===----------------------------------------------------------------------===//
1753// External interface
1754//===----------------------------------------------------------------------===//
1755
1756/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1757///
1758ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1759 std::string *ErrMsg) {
1760 BitcodeReader *R = new BitcodeReader(Buffer);
1761 if (R->ParseBitcode()) {
1762 if (ErrMsg)
1763 *ErrMsg = R->getErrorString();
1764
1765 // Don't let the BitcodeReader dtor delete 'Buffer'.
1766 R->releaseMemoryBuffer();
1767 delete R;
1768 return 0;
1769 }
1770 return R;
1771}
1772
1773/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1774/// If an error occurs, return null and fill in *ErrMsg if non-null.
1775Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1776 BitcodeReader *R;
1777 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1778 if (!R) return 0;
1779
Chris Lattnerb348bb82007-05-18 04:02:46 +00001780 // Read in the entire module.
1781 Module *M = R->materializeModule(ErrMsg);
1782
1783 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1784 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001785 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001786
1787 // If there was no error, tell ModuleProvider not to delete it when its dtor
1788 // is run.
1789 if (M)
1790 M = R->releaseModule(ErrMsg);
1791
Chris Lattnerc453f762007-04-29 07:54:31 +00001792 delete R;
1793 return M;
1794}