blob: 8b333bcba280e5cdd3dc7defecc11f14262a1a30 [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"
Gabor Greifefe65362008-05-10 08:32:32 +000026#include "llvm/OperandTraits.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();
Chris Lattner461edd92008-03-12 02:25:52 +000034
Chris Lattner58d74912008-03-12 17:45:29 +000035 std::vector<PAListPtr>().swap(ParamAttrs);
Chris Lattnerb348bb82007-05-18 04:02:46 +000036 std::vector<BasicBlock*>().swap(FunctionBBs);
37 std::vector<Function*>().swap(FunctionsWithBodies);
38 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000039}
40
Chris Lattner48c85b82007-05-04 03:30:17 +000041//===----------------------------------------------------------------------===//
42// Helper functions to implement forward reference resolution, etc.
43//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000044
Chris Lattnercaee0dc2007-04-22 06:23:29 +000045/// ConvertToString - Convert a string from a record into an std::string, return
46/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000047template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000048static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000049 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000050 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000051 return true;
52
Chris Lattner15e6d172007-05-04 19:11:41 +000053 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
54 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000055 return false;
56}
57
58static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
59 switch (Val) {
60 default: // Map unknown/new linkages to external
61 case 0: return GlobalValue::ExternalLinkage;
62 case 1: return GlobalValue::WeakLinkage;
63 case 2: return GlobalValue::AppendingLinkage;
64 case 3: return GlobalValue::InternalLinkage;
65 case 4: return GlobalValue::LinkOnceLinkage;
66 case 5: return GlobalValue::DLLImportLinkage;
67 case 6: return GlobalValue::DLLExportLinkage;
68 case 7: return GlobalValue::ExternalWeakLinkage;
69 }
70}
71
72static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
73 switch (Val) {
74 default: // Map unknown visibilities to default.
75 case 0: return GlobalValue::DefaultVisibility;
76 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000077 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000078 }
79}
80
Chris Lattnerf581c3b2007-04-24 07:07:11 +000081static int GetDecodedCastOpcode(unsigned Val) {
82 switch (Val) {
83 default: return -1;
84 case bitc::CAST_TRUNC : return Instruction::Trunc;
85 case bitc::CAST_ZEXT : return Instruction::ZExt;
86 case bitc::CAST_SEXT : return Instruction::SExt;
87 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
88 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
89 case bitc::CAST_UITOFP : return Instruction::UIToFP;
90 case bitc::CAST_SITOFP : return Instruction::SIToFP;
91 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
92 case bitc::CAST_FPEXT : return Instruction::FPExt;
93 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
94 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
95 case bitc::CAST_BITCAST : return Instruction::BitCast;
96 }
97}
98static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
99 switch (Val) {
100 default: return -1;
101 case bitc::BINOP_ADD: return Instruction::Add;
102 case bitc::BINOP_SUB: return Instruction::Sub;
103 case bitc::BINOP_MUL: return Instruction::Mul;
104 case bitc::BINOP_UDIV: return Instruction::UDiv;
105 case bitc::BINOP_SDIV:
106 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
107 case bitc::BINOP_UREM: return Instruction::URem;
108 case bitc::BINOP_SREM:
109 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
110 case bitc::BINOP_SHL: return Instruction::Shl;
111 case bitc::BINOP_LSHR: return Instruction::LShr;
112 case bitc::BINOP_ASHR: return Instruction::AShr;
113 case bitc::BINOP_AND: return Instruction::And;
114 case bitc::BINOP_OR: return Instruction::Or;
115 case bitc::BINOP_XOR: return Instruction::Xor;
116 }
117}
118
Gabor Greifefe65362008-05-10 08:32:32 +0000119namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000120namespace {
121 /// @brief A class for maintaining the slot number definition
122 /// as a placeholder for the actual definition for forward constants defs.
123 class ConstantPlaceHolder : public ConstantExpr {
124 ConstantPlaceHolder(); // DO NOT IMPLEMENT
125 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
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)
Gabor Greifefe65362008-05-10 08:32:32 +0000132 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
133 Op<0>() = UndefValue::get(Type::Int32Ty);
Chris Lattner522b7b12007-04-24 05:48:56 +0000134 }
Gabor Greifefe65362008-05-10 08:32:32 +0000135 /// Provide fast operand accessors
136 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000137 };
138}
139
Gabor Greifefe65362008-05-10 08:32:32 +0000140
141 // FIXME: can we inherit this from ConstantExpr?
142template <>
143struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
144};
145
146DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
147}
148
149void BitcodeReaderValueList::resize(unsigned Desired) {
150 if (Desired > Capacity) {
151 // Since we expect many values to come from the bitcode file we better
152 // allocate the double amount, so that the array size grows exponentially
153 // at each reallocation. Also, add a small amount of 100 extra elements
154 // each time, to reallocate less frequently when the array is still small.
155 //
156 Capacity = Desired * 2 + 100;
157 Use *New = allocHungoffUses(Capacity);
158 Use *Old = OperandList;
159 unsigned Ops = getNumOperands();
160 for (int i(Ops - 1); i >= 0; --i)
161 New[i] = Old[i].get();
162 OperandList = New;
163 if (Old) Use::zap(Old, Old + Ops, true);
164 }
165}
166
Chris Lattner522b7b12007-04-24 05:48:56 +0000167Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
168 const Type *Ty) {
169 if (Idx >= size()) {
170 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000171 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000172 NumOperands = Idx+1;
173 }
174
Gabor Greifefe65362008-05-10 08:32:32 +0000175 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000176 assert(Ty == V->getType() && "Type mismatch in constant table!");
177 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000178 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000179
180 // Create and return a placeholder, which will later be RAUW'd.
181 Constant *C = new ConstantPlaceHolder(Ty);
Gabor Greifefe65362008-05-10 08:32:32 +0000182 OperandList[Idx].init(C, this);
Chris Lattner522b7b12007-04-24 05:48:56 +0000183 return C;
184}
185
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000186Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
187 if (Idx >= size()) {
188 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000189 resize(Idx + 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000190 NumOperands = Idx+1;
191 }
192
Gabor Greifefe65362008-05-10 08:32:32 +0000193 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000194 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
195 return V;
196 }
197
Chris Lattner01ff65f2007-05-02 05:16:49 +0000198 // No type specified, must be invalid reference.
199 if (Ty == 0) return 0;
200
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000201 // Create and return a placeholder, which will later be RAUW'd.
202 Value *V = new Argument(Ty);
Gabor Greifefe65362008-05-10 08:32:32 +0000203 OperandList[Idx].init(V, this);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000204 return V;
205}
206
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000207
208const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
209 // If the TypeID is in range, return it.
210 if (ID < TypeList.size())
211 return TypeList[ID].get();
212 if (!isTypeTable) return 0;
213
214 // The type table allows forward references. Push as many Opaque types as
215 // needed to get up to ID.
216 while (TypeList.size() <= ID)
217 TypeList.push_back(OpaqueType::get());
218 return TypeList.back().get();
219}
220
Chris Lattner48c85b82007-05-04 03:30:17 +0000221//===----------------------------------------------------------------------===//
222// Functions for parsing blocks from the bitcode file
223//===----------------------------------------------------------------------===//
224
225bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000226 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000227 return Error("Malformed block record");
228
229 if (!ParamAttrs.empty())
230 return Error("Multiple PARAMATTR blocks found!");
231
232 SmallVector<uint64_t, 64> Record;
233
Chris Lattner58d74912008-03-12 17:45:29 +0000234 SmallVector<ParamAttrsWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000235
236 // Read all the records.
237 while (1) {
238 unsigned Code = Stream.ReadCode();
239 if (Code == bitc::END_BLOCK) {
240 if (Stream.ReadBlockEnd())
241 return Error("Error at end of PARAMATTR block");
242 return false;
243 }
244
245 if (Code == bitc::ENTER_SUBBLOCK) {
246 // No known subblocks, always skip them.
247 Stream.ReadSubBlockID();
248 if (Stream.SkipBlock())
249 return Error("Malformed block record");
250 continue;
251 }
252
253 if (Code == bitc::DEFINE_ABBREV) {
254 Stream.ReadAbbrevRecord();
255 continue;
256 }
257
258 // Read a record.
259 Record.clear();
260 switch (Stream.ReadRecord(Code, Record)) {
261 default: // Default behavior: ignore.
262 break;
263 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
264 if (Record.size() & 1)
265 return Error("Invalid ENTRY record");
266
Chris Lattner48c85b82007-05-04 03:30:17 +0000267 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Duncan Sands5e41f652007-11-20 14:09:29 +0000268 if (Record[i+1] != ParamAttr::None)
269 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
Chris Lattner48c85b82007-05-04 03:30:17 +0000270 }
Chris Lattner461edd92008-03-12 02:25:52 +0000271
Chris Lattner58d74912008-03-12 17:45:29 +0000272 ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000273 Attrs.clear();
274 break;
275 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000276 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000277 }
278}
279
280
Chris Lattner86697142007-05-01 05:01:34 +0000281bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000282 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000283 return Error("Malformed block record");
284
285 if (!TypeList.empty())
286 return Error("Multiple TYPE_BLOCKs found!");
287
288 SmallVector<uint64_t, 64> Record;
289 unsigned NumRecords = 0;
290
291 // Read all the records for this type table.
292 while (1) {
293 unsigned Code = Stream.ReadCode();
294 if (Code == bitc::END_BLOCK) {
295 if (NumRecords != TypeList.size())
296 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000297 if (Stream.ReadBlockEnd())
298 return Error("Error at end of type table block");
299 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000300 }
301
302 if (Code == bitc::ENTER_SUBBLOCK) {
303 // No known subblocks, always skip them.
304 Stream.ReadSubBlockID();
305 if (Stream.SkipBlock())
306 return Error("Malformed block record");
307 continue;
308 }
309
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000310 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000311 Stream.ReadAbbrevRecord();
312 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000313 }
314
315 // Read a record.
316 Record.clear();
317 const Type *ResultTy = 0;
318 switch (Stream.ReadRecord(Code, Record)) {
319 default: // Default behavior: unknown type.
320 ResultTy = 0;
321 break;
322 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
323 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
324 // type list. This allows us to reserve space.
325 if (Record.size() < 1)
326 return Error("Invalid TYPE_CODE_NUMENTRY record");
327 TypeList.reserve(Record[0]);
328 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000329 case bitc::TYPE_CODE_VOID: // VOID
330 ResultTy = Type::VoidTy;
331 break;
332 case bitc::TYPE_CODE_FLOAT: // FLOAT
333 ResultTy = Type::FloatTy;
334 break;
335 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
336 ResultTy = Type::DoubleTy;
337 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000338 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
339 ResultTy = Type::X86_FP80Ty;
340 break;
341 case bitc::TYPE_CODE_FP128: // FP128
342 ResultTy = Type::FP128Ty;
343 break;
344 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
345 ResultTy = Type::PPC_FP128Ty;
346 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000347 case bitc::TYPE_CODE_LABEL: // LABEL
348 ResultTy = Type::LabelTy;
349 break;
350 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
351 ResultTy = 0;
352 break;
353 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
354 if (Record.size() < 1)
355 return Error("Invalid Integer type record");
356
357 ResultTy = IntegerType::get(Record[0]);
358 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000359 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
360 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000361 if (Record.size() < 1)
362 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000363 unsigned AddressSpace = 0;
364 if (Record.size() == 2)
365 AddressSpace = Record[1];
366 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000367 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000368 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000369 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000370 // FIXME: attrid is dead, remove it in LLVM 3.0
371 // FUNCTION: [vararg, attrid, retty, paramty x N]
372 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000373 return Error("Invalid FUNCTION type record");
374 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000375 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000376 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000377
Chris Lattnera1afde72007-11-27 17:48:06 +0000378 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000379 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000380 break;
381 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000382 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000383 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000384 return Error("Invalid STRUCT type record");
385 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000386 for (unsigned i = 1, e = Record.size(); i != e; ++i)
387 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000388 ResultTy = StructType::get(EltTys, Record[0]);
389 break;
390 }
391 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
392 if (Record.size() < 2)
393 return Error("Invalid ARRAY type record");
394 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
395 break;
396 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
397 if (Record.size() < 2)
398 return Error("Invalid VECTOR type record");
399 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
400 break;
401 }
402
403 if (NumRecords == TypeList.size()) {
404 // If this is a new type slot, just append it.
405 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
406 ++NumRecords;
407 } else if (ResultTy == 0) {
408 // Otherwise, this was forward referenced, so an opaque type was created,
409 // but the result type is actually just an opaque. Leave the one we
410 // created previously.
411 ++NumRecords;
412 } else {
413 // Otherwise, this was forward referenced, so an opaque type was created.
414 // Resolve the opaque type to the real type now.
415 assert(NumRecords < TypeList.size() && "Typelist imbalance");
416 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
417
418 // Don't directly push the new type on the Tab. Instead we want to replace
419 // the opaque type we previously inserted with the new concrete value. The
420 // refinement from the abstract (opaque) type to the new type causes all
421 // uses of the abstract type to use the concrete type (NewTy). This will
422 // also cause the opaque type to be deleted.
423 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
424
425 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000426 // value table... or with a preexisting type that was already in the
427 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000428 assert(TypeList[NumRecords-1].get() != OldTy &&
429 "refineAbstractType didn't work!");
430 }
431 }
432}
433
434
Chris Lattner86697142007-05-01 05:01:34 +0000435bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000436 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000437 return Error("Malformed block record");
438
439 SmallVector<uint64_t, 64> Record;
440
441 // Read all the records for this type table.
442 std::string TypeName;
443 while (1) {
444 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000445 if (Code == bitc::END_BLOCK) {
446 if (Stream.ReadBlockEnd())
447 return Error("Error at end of type symbol table block");
448 return false;
449 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000450
451 if (Code == bitc::ENTER_SUBBLOCK) {
452 // No known subblocks, always skip them.
453 Stream.ReadSubBlockID();
454 if (Stream.SkipBlock())
455 return Error("Malformed block record");
456 continue;
457 }
458
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000459 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000460 Stream.ReadAbbrevRecord();
461 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000462 }
463
464 // Read a record.
465 Record.clear();
466 switch (Stream.ReadRecord(Code, Record)) {
467 default: // Default behavior: unknown type.
468 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000469 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000470 if (ConvertToString(Record, 1, TypeName))
471 return Error("Invalid TST_ENTRY record");
472 unsigned TypeID = Record[0];
473 if (TypeID >= TypeList.size())
474 return Error("Invalid Type ID in TST_ENTRY record");
475
476 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
477 TypeName.clear();
478 break;
479 }
480 }
481}
482
Chris Lattner86697142007-05-01 05:01:34 +0000483bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000484 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000485 return Error("Malformed block record");
486
487 SmallVector<uint64_t, 64> Record;
488
489 // Read all the records for this value table.
490 SmallString<128> ValueName;
491 while (1) {
492 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000493 if (Code == bitc::END_BLOCK) {
494 if (Stream.ReadBlockEnd())
495 return Error("Error at end of value symbol table block");
496 return false;
497 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000498 if (Code == bitc::ENTER_SUBBLOCK) {
499 // No known subblocks, always skip them.
500 Stream.ReadSubBlockID();
501 if (Stream.SkipBlock())
502 return Error("Malformed block record");
503 continue;
504 }
505
506 if (Code == bitc::DEFINE_ABBREV) {
507 Stream.ReadAbbrevRecord();
508 continue;
509 }
510
511 // Read a record.
512 Record.clear();
513 switch (Stream.ReadRecord(Code, Record)) {
514 default: // Default behavior: unknown type.
515 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000516 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000517 if (ConvertToString(Record, 1, ValueName))
518 return Error("Invalid TST_ENTRY record");
519 unsigned ValueID = Record[0];
520 if (ValueID >= ValueList.size())
521 return Error("Invalid Value ID in VST_ENTRY record");
522 Value *V = ValueList[ValueID];
523
524 V->setName(&ValueName[0], ValueName.size());
525 ValueName.clear();
526 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000527 }
528 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000529 if (ConvertToString(Record, 1, ValueName))
530 return Error("Invalid VST_BBENTRY record");
531 BasicBlock *BB = getBasicBlock(Record[0]);
532 if (BB == 0)
533 return Error("Invalid BB ID in VST_BBENTRY record");
534
535 BB->setName(&ValueName[0], ValueName.size());
536 ValueName.clear();
537 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000538 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000539 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000540 }
541}
542
Chris Lattner0eef0802007-04-24 04:04:35 +0000543/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
544/// the LSB for dense VBR encoding.
545static uint64_t DecodeSignRotatedValue(uint64_t V) {
546 if ((V & 1) == 0)
547 return V >> 1;
548 if (V != 1)
549 return -(V >> 1);
550 // There is no such thing as -0 with integers. "-0" really means MININT.
551 return 1ULL << 63;
552}
553
Chris Lattner07d98b42007-04-26 02:46:40 +0000554/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
555/// values and aliases that we can.
556bool BitcodeReader::ResolveGlobalAndAliasInits() {
557 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
558 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
559
560 GlobalInitWorklist.swap(GlobalInits);
561 AliasInitWorklist.swap(AliasInits);
562
563 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000564 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000565 if (ValID >= ValueList.size()) {
566 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000567 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000568 } else {
569 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
570 GlobalInitWorklist.back().first->setInitializer(C);
571 else
572 return Error("Global variable initializer is not a constant!");
573 }
574 GlobalInitWorklist.pop_back();
575 }
576
577 while (!AliasInitWorklist.empty()) {
578 unsigned ValID = AliasInitWorklist.back().second;
579 if (ValID >= ValueList.size()) {
580 AliasInits.push_back(AliasInitWorklist.back());
581 } else {
582 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000583 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000584 else
585 return Error("Alias initializer is not a constant!");
586 }
587 AliasInitWorklist.pop_back();
588 }
589 return false;
590}
591
592
Chris Lattner86697142007-05-01 05:01:34 +0000593bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000594 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000595 return Error("Malformed block record");
596
597 SmallVector<uint64_t, 64> Record;
598
599 // Read all the records for this value table.
600 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000601 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000602 while (1) {
603 unsigned Code = Stream.ReadCode();
604 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000605 if (NextCstNo != ValueList.size())
606 return Error("Invalid constant reference!");
607
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000608 if (Stream.ReadBlockEnd())
609 return Error("Error at end of constants block");
610 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000611 }
612
613 if (Code == bitc::ENTER_SUBBLOCK) {
614 // No known subblocks, always skip them.
615 Stream.ReadSubBlockID();
616 if (Stream.SkipBlock())
617 return Error("Malformed block record");
618 continue;
619 }
620
621 if (Code == bitc::DEFINE_ABBREV) {
622 Stream.ReadAbbrevRecord();
623 continue;
624 }
625
626 // Read a record.
627 Record.clear();
628 Value *V = 0;
629 switch (Stream.ReadRecord(Code, Record)) {
630 default: // Default behavior: unknown constant
631 case bitc::CST_CODE_UNDEF: // UNDEF
632 V = UndefValue::get(CurTy);
633 break;
634 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
635 if (Record.empty())
636 return Error("Malformed CST_SETTYPE record");
637 if (Record[0] >= TypeList.size())
638 return Error("Invalid Type ID in CST_SETTYPE record");
639 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000640 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000641 case bitc::CST_CODE_NULL: // NULL
642 V = Constant::getNullValue(CurTy);
643 break;
644 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000645 if (!isa<IntegerType>(CurTy) || Record.empty())
646 return Error("Invalid CST_INTEGER record");
647 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
648 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000649 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
650 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000651 return Error("Invalid WIDE_INTEGER record");
652
Chris Lattner15e6d172007-05-04 19:11:41 +0000653 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000654 SmallVector<uint64_t, 8> Words;
655 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000656 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000657 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000658 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000659 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000660 break;
661 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000662 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000663 if (Record.empty())
664 return Error("Invalid FLOAT record");
665 if (CurTy == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000666 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000667 else if (CurTy == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000668 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000669 else if (CurTy == Type::X86_FP80Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000670 V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000671 else if (CurTy == Type::FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000672 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000673 else if (CurTy == Type::PPC_FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000674 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000675 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000676 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000677 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000678 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000679
Chris Lattner15e6d172007-05-04 19:11:41 +0000680 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
681 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000682 return Error("Invalid CST_AGGREGATE record");
683
Chris Lattner15e6d172007-05-04 19:11:41 +0000684 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000685 std::vector<Constant*> Elts;
686
687 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
688 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000689 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000690 STy->getElementType(i)));
691 V = ConstantStruct::get(STy, Elts);
692 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
693 const Type *EltTy = ATy->getElementType();
694 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000695 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000696 V = ConstantArray::get(ATy, Elts);
697 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
698 const Type *EltTy = VTy->getElementType();
699 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000700 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000701 V = ConstantVector::get(Elts);
702 } else {
703 V = UndefValue::get(CurTy);
704 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000705 break;
706 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000707 case bitc::CST_CODE_STRING: { // STRING: [values]
708 if (Record.empty())
709 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000710
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000711 const ArrayType *ATy = cast<ArrayType>(CurTy);
712 const Type *EltTy = ATy->getElementType();
713
714 unsigned Size = Record.size();
715 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000716 for (unsigned i = 0; i != Size; ++i)
717 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
718 V = ConstantArray::get(ATy, Elts);
719 break;
720 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000721 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
722 if (Record.empty())
723 return Error("Invalid CST_AGGREGATE record");
724
725 const ArrayType *ATy = cast<ArrayType>(CurTy);
726 const Type *EltTy = ATy->getElementType();
727
728 unsigned Size = Record.size();
729 std::vector<Constant*> Elts;
730 for (unsigned i = 0; i != Size; ++i)
731 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
732 Elts.push_back(Constant::getNullValue(EltTy));
733 V = ConstantArray::get(ATy, Elts);
734 break;
735 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000736 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
737 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
738 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000739 if (Opc < 0) {
740 V = UndefValue::get(CurTy); // Unknown binop.
741 } else {
742 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
743 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
744 V = ConstantExpr::get(Opc, LHS, RHS);
745 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000746 break;
747 }
748 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
749 if (Record.size() < 3) return Error("Invalid CE_CAST record");
750 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000751 if (Opc < 0) {
752 V = UndefValue::get(CurTy); // Unknown cast.
753 } else {
754 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000755 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000756 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
757 V = ConstantExpr::getCast(Opc, Op, CurTy);
758 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000759 break;
760 }
761 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000762 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000763 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000764 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000765 const Type *ElTy = getTypeByID(Record[i]);
766 if (!ElTy) return Error("Invalid CE_GEP record");
767 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
768 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000769 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
770 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000771 }
772 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
773 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
774 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
775 Type::Int1Ty),
776 ValueList.getConstantFwdRef(Record[1],CurTy),
777 ValueList.getConstantFwdRef(Record[2],CurTy));
778 break;
779 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
780 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
781 const VectorType *OpTy =
782 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
783 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
784 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
785 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
786 OpTy->getElementType());
787 V = ConstantExpr::getExtractElement(Op0, Op1);
788 break;
789 }
790 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
791 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
792 if (Record.size() < 3 || OpTy == 0)
793 return Error("Invalid CE_INSERTELT record");
794 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
795 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
796 OpTy->getElementType());
797 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
798 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
799 break;
800 }
801 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
802 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
803 if (Record.size() < 3 || OpTy == 0)
804 return Error("Invalid CE_INSERTELT record");
805 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
806 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
807 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
808 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
809 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
810 break;
811 }
812 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
813 if (Record.size() < 4) return Error("Invalid CE_CMP record");
814 const Type *OpTy = getTypeByID(Record[0]);
815 if (OpTy == 0) return Error("Invalid CE_CMP record");
816 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
817 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
818
819 if (OpTy->isFloatingPoint())
820 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begeman51d2ed12008-05-12 20:16:55 +0000821 else if (OpTy->isInteger() || isa<PointerType>(OpTy))
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000822 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +0000823 else if (OpTy->isFPOrFPVector())
824 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
825 else
826 V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000827 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000828 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000829 case bitc::CST_CODE_INLINEASM: {
830 if (Record.size() < 2) return Error("Invalid INLINEASM record");
831 std::string AsmStr, ConstrStr;
832 bool HasSideEffects = Record[0];
833 unsigned AsmStrSize = Record[1];
834 if (2+AsmStrSize >= Record.size())
835 return Error("Invalid INLINEASM record");
836 unsigned ConstStrSize = Record[2+AsmStrSize];
837 if (3+AsmStrSize+ConstStrSize > Record.size())
838 return Error("Invalid INLINEASM record");
839
840 for (unsigned i = 0; i != AsmStrSize; ++i)
841 AsmStr += (char)Record[2+i];
842 for (unsigned i = 0; i != ConstStrSize; ++i)
843 ConstrStr += (char)Record[3+AsmStrSize+i];
844 const PointerType *PTy = cast<PointerType>(CurTy);
845 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
846 AsmStr, ConstrStr, HasSideEffects);
847 break;
848 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000849 }
850
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000851 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000852 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000853 }
854}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000855
Chris Lattner980e5aa2007-05-01 05:52:21 +0000856/// RememberAndSkipFunctionBody - When we see the block for a function body,
857/// remember where it is and then skip it. This lets us lazily deserialize the
858/// functions.
859bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000860 // Get the function we are talking about.
861 if (FunctionsWithBodies.empty())
862 return Error("Insufficient function protos");
863
864 Function *Fn = FunctionsWithBodies.back();
865 FunctionsWithBodies.pop_back();
866
867 // Save the current stream state.
868 uint64_t CurBit = Stream.GetCurrentBitNo();
869 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
870
871 // Set the functions linkage to GhostLinkage so we know it is lazily
872 // deserialized.
873 Fn->setLinkage(GlobalValue::GhostLinkage);
874
875 // Skip over the function block for now.
876 if (Stream.SkipBlock())
877 return Error("Malformed block record");
878 return false;
879}
880
Chris Lattner86697142007-05-01 05:01:34 +0000881bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000882 // Reject multiple MODULE_BLOCK's in a single bitstream.
883 if (TheModule)
884 return Error("Multiple MODULE_BLOCKs in same stream");
885
Chris Lattnere17b6582007-05-05 00:17:00 +0000886 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000887 return Error("Malformed block record");
888
889 // Otherwise, create the module.
890 TheModule = new Module(ModuleID);
891
892 SmallVector<uint64_t, 64> Record;
893 std::vector<std::string> SectionTable;
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000894 std::vector<std::string> CollectorTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000895
896 // Read all the records for this module.
897 while (!Stream.AtEndOfStream()) {
898 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000899 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000900 if (Stream.ReadBlockEnd())
901 return Error("Error at end of module block");
902
903 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000904 ResolveGlobalAndAliasInits();
905 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000906 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000907 if (!FunctionsWithBodies.empty())
908 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000909
Chandler Carruth69940402007-08-04 01:51:18 +0000910 // Look for intrinsic functions which need to be upgraded at some point
911 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
912 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +0000913 Function* NewFn;
914 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +0000915 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
916 }
917
Chris Lattner980e5aa2007-05-01 05:52:21 +0000918 // Force deallocation of memory for these vectors to favor the client that
919 // want lazy deserialization.
920 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
921 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
922 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000923 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000924 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000925
926 if (Code == bitc::ENTER_SUBBLOCK) {
927 switch (Stream.ReadSubBlockID()) {
928 default: // Skip unknown content.
929 if (Stream.SkipBlock())
930 return Error("Malformed block record");
931 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000932 case bitc::BLOCKINFO_BLOCK_ID:
933 if (Stream.ReadBlockInfoBlock())
934 return Error("Malformed BlockInfoBlock");
935 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000936 case bitc::PARAMATTR_BLOCK_ID:
937 if (ParseParamAttrBlock())
938 return true;
939 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000940 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000941 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000942 return true;
943 break;
944 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000945 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000946 return true;
947 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000948 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000949 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000950 return true;
951 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000952 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000953 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000954 return true;
955 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000956 case bitc::FUNCTION_BLOCK_ID:
957 // If this is the first function body we've seen, reverse the
958 // FunctionsWithBodies list.
959 if (!HasReversedFunctionsWithBodies) {
960 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
961 HasReversedFunctionsWithBodies = true;
962 }
963
Chris Lattner980e5aa2007-05-01 05:52:21 +0000964 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000965 return true;
966 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000967 }
968 continue;
969 }
970
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000971 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000972 Stream.ReadAbbrevRecord();
973 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000974 }
975
976 // Read a record.
977 switch (Stream.ReadRecord(Code, Record)) {
978 default: break; // Default behavior, ignore unknown content.
979 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
980 if (Record.size() < 1)
981 return Error("Malformed MODULE_CODE_VERSION");
982 // Only version #0 is supported so far.
983 if (Record[0] != 0)
984 return Error("Unknown bitstream version!");
985 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000986 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000987 std::string S;
988 if (ConvertToString(Record, 0, S))
989 return Error("Invalid MODULE_CODE_TRIPLE record");
990 TheModule->setTargetTriple(S);
991 break;
992 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000993 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000994 std::string S;
995 if (ConvertToString(Record, 0, S))
996 return Error("Invalid MODULE_CODE_DATALAYOUT record");
997 TheModule->setDataLayout(S);
998 break;
999 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001000 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001001 std::string S;
1002 if (ConvertToString(Record, 0, S))
1003 return Error("Invalid MODULE_CODE_ASM record");
1004 TheModule->setModuleInlineAsm(S);
1005 break;
1006 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001007 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001008 std::string S;
1009 if (ConvertToString(Record, 0, S))
1010 return Error("Invalid MODULE_CODE_DEPLIB record");
1011 TheModule->addLibrary(S);
1012 break;
1013 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001014 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001015 std::string S;
1016 if (ConvertToString(Record, 0, S))
1017 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1018 SectionTable.push_back(S);
1019 break;
1020 }
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001021 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
1022 std::string S;
1023 if (ConvertToString(Record, 0, S))
1024 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
1025 CollectorTable.push_back(S);
1026 break;
1027 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001028 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001029 // linkage, alignment, section, visibility, threadlocal]
1030 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001031 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001032 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1033 const Type *Ty = getTypeByID(Record[0]);
1034 if (!isa<PointerType>(Ty))
1035 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001036 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001037 Ty = cast<PointerType>(Ty)->getElementType();
1038
1039 bool isConstant = Record[1];
1040 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1041 unsigned Alignment = (1 << Record[4]) >> 1;
1042 std::string Section;
1043 if (Record[5]) {
1044 if (Record[5]-1 >= SectionTable.size())
1045 return Error("Invalid section ID");
1046 Section = SectionTable[Record[5]-1];
1047 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001048 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001049 if (Record.size() > 6)
1050 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001051 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001052 if (Record.size() > 7)
1053 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001054
1055 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001056 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1057 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001058 NewGV->setAlignment(Alignment);
1059 if (!Section.empty())
1060 NewGV->setSection(Section);
1061 NewGV->setVisibility(Visibility);
1062 NewGV->setThreadLocal(isThreadLocal);
1063
Chris Lattner0b2482a2007-04-23 21:26:05 +00001064 ValueList.push_back(NewGV);
1065
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001066 // Remember which value to use for the global initializer.
1067 if (unsigned InitID = Record[2])
1068 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001069 break;
1070 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001071 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001072 // alignment, section, visibility, collector]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001073 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001074 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001075 return Error("Invalid MODULE_CODE_FUNCTION record");
1076 const Type *Ty = getTypeByID(Record[0]);
1077 if (!isa<PointerType>(Ty))
1078 return Error("Function not a pointer type!");
1079 const FunctionType *FTy =
1080 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1081 if (!FTy)
1082 return Error("Function not a pointer to function type!");
1083
Gabor Greif051a9502008-04-06 20:25:17 +00001084 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1085 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001086
1087 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001088 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001089 Func->setLinkage(GetDecodedLinkage(Record[3]));
Chris Lattner58d74912008-03-12 17:45:29 +00001090 Func->setParamAttrs(getParamAttrs(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001091
1092 Func->setAlignment((1 << Record[5]) >> 1);
1093 if (Record[6]) {
1094 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001095 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001096 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001097 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001098 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001099 if (Record.size() > 8 && Record[8]) {
1100 if (Record[8]-1 > CollectorTable.size())
1101 return Error("Invalid collector ID");
1102 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1103 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001104
Chris Lattner0b2482a2007-04-23 21:26:05 +00001105 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001106
1107 // If this is a function with a body, remember the prototype we are
1108 // creating now, so that we can match up the body with them later.
1109 if (!isProto)
1110 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001111 break;
1112 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001113 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001114 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001115 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001116 if (Record.size() < 3)
1117 return Error("Invalid MODULE_ALIAS record");
1118 const Type *Ty = getTypeByID(Record[0]);
1119 if (!isa<PointerType>(Ty))
1120 return Error("Function not a pointer type!");
1121
1122 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1123 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001124 // Old bitcode files didn't have visibility field.
1125 if (Record.size() > 3)
1126 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001127 ValueList.push_back(NewGA);
1128 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1129 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001130 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001131 /// MODULE_CODE_PURGEVALS: [numvals]
1132 case bitc::MODULE_CODE_PURGEVALS:
1133 // Trim down the value list to the specified size.
1134 if (Record.size() < 1 || Record[0] > ValueList.size())
1135 return Error("Invalid MODULE_PURGEVALS record");
1136 ValueList.shrinkTo(Record[0]);
1137 break;
1138 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001139 Record.clear();
1140 }
1141
1142 return Error("Premature end of bitstream");
1143}
1144
1145
Chris Lattnerc453f762007-04-29 07:54:31 +00001146bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001147 TheModule = 0;
1148
Chris Lattnerc453f762007-04-29 07:54:31 +00001149 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001150 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1151
Chris Lattnerc453f762007-04-29 07:54:31 +00001152 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001153 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001154
1155 // Sniff for the signature.
1156 if (Stream.Read(8) != 'B' ||
1157 Stream.Read(8) != 'C' ||
1158 Stream.Read(4) != 0x0 ||
1159 Stream.Read(4) != 0xC ||
1160 Stream.Read(4) != 0xE ||
1161 Stream.Read(4) != 0xD)
1162 return Error("Invalid bitcode signature");
1163
1164 // We expect a number of well-defined blocks, though we don't necessarily
1165 // need to understand them all.
1166 while (!Stream.AtEndOfStream()) {
1167 unsigned Code = Stream.ReadCode();
1168
1169 if (Code != bitc::ENTER_SUBBLOCK)
1170 return Error("Invalid record at top-level");
1171
1172 unsigned BlockID = Stream.ReadSubBlockID();
1173
1174 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001175 switch (BlockID) {
1176 case bitc::BLOCKINFO_BLOCK_ID:
1177 if (Stream.ReadBlockInfoBlock())
1178 return Error("Malformed BlockInfoBlock");
1179 break;
1180 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001181 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001182 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001183 break;
1184 default:
1185 if (Stream.SkipBlock())
1186 return Error("Malformed block record");
1187 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001188 }
1189 }
1190
1191 return false;
1192}
Chris Lattnerc453f762007-04-29 07:54:31 +00001193
Chris Lattner48f84872007-05-01 04:59:48 +00001194
Chris Lattner980e5aa2007-05-01 05:52:21 +00001195/// ParseFunctionBody - Lazily parse the specified function body block.
1196bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001197 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001198 return Error("Malformed block record");
1199
1200 unsigned ModuleValueListSize = ValueList.size();
1201
1202 // Add all the function arguments to the value table.
1203 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1204 ValueList.push_back(I);
1205
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001206 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001207 BasicBlock *CurBB = 0;
1208 unsigned CurBBNo = 0;
1209
Chris Lattner980e5aa2007-05-01 05:52:21 +00001210 // Read all the records.
1211 SmallVector<uint64_t, 64> Record;
1212 while (1) {
1213 unsigned Code = Stream.ReadCode();
1214 if (Code == bitc::END_BLOCK) {
1215 if (Stream.ReadBlockEnd())
1216 return Error("Error at end of function block");
1217 break;
1218 }
1219
1220 if (Code == bitc::ENTER_SUBBLOCK) {
1221 switch (Stream.ReadSubBlockID()) {
1222 default: // Skip unknown content.
1223 if (Stream.SkipBlock())
1224 return Error("Malformed block record");
1225 break;
1226 case bitc::CONSTANTS_BLOCK_ID:
1227 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001228 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001229 break;
1230 case bitc::VALUE_SYMTAB_BLOCK_ID:
1231 if (ParseValueSymbolTable()) return true;
1232 break;
1233 }
1234 continue;
1235 }
1236
1237 if (Code == bitc::DEFINE_ABBREV) {
1238 Stream.ReadAbbrevRecord();
1239 continue;
1240 }
1241
1242 // Read a record.
1243 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001244 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001245 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001246 default: // Default behavior: reject
1247 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001248 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001249 if (Record.size() < 1 || Record[0] == 0)
1250 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001251 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001252 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001253 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001254 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001255 CurBB = FunctionBBs[0];
1256 continue;
1257
Chris Lattnerabfbf852007-05-06 00:21:25 +00001258 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1259 unsigned OpNum = 0;
1260 Value *LHS, *RHS;
1261 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1262 getValue(Record, OpNum, LHS->getType(), RHS) ||
1263 OpNum+1 != Record.size())
1264 return Error("Invalid BINOP record");
1265
1266 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1267 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001268 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001269 break;
1270 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001271 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1272 unsigned OpNum = 0;
1273 Value *Op;
1274 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1275 OpNum+2 != Record.size())
1276 return Error("Invalid CAST record");
1277
1278 const Type *ResTy = getTypeByID(Record[OpNum]);
1279 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1280 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001281 return Error("Invalid CAST record");
1282 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1283 break;
1284 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001285 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001286 unsigned OpNum = 0;
1287 Value *BasePtr;
1288 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001289 return Error("Invalid GEP record");
1290
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001291 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001292 while (OpNum != Record.size()) {
1293 Value *Op;
1294 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001295 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001296 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001297 }
1298
Gabor Greif051a9502008-04-06 20:25:17 +00001299 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001300 break;
1301 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001302
Chris Lattnerabfbf852007-05-06 00:21:25 +00001303 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1304 unsigned OpNum = 0;
1305 Value *TrueVal, *FalseVal, *Cond;
1306 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1307 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1308 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001309 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001310
Gabor Greif051a9502008-04-06 20:25:17 +00001311 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001312 break;
1313 }
1314
1315 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001316 unsigned OpNum = 0;
1317 Value *Vec, *Idx;
1318 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1319 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001320 return Error("Invalid EXTRACTELT record");
1321 I = new ExtractElementInst(Vec, Idx);
1322 break;
1323 }
1324
1325 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001326 unsigned OpNum = 0;
1327 Value *Vec, *Elt, *Idx;
1328 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1329 getValue(Record, OpNum,
1330 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1331 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001332 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001333 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001334 break;
1335 }
1336
Chris Lattnerabfbf852007-05-06 00:21:25 +00001337 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1338 unsigned OpNum = 0;
1339 Value *Vec1, *Vec2, *Mask;
1340 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1341 getValue(Record, OpNum, Vec1->getType(), Vec2))
1342 return Error("Invalid SHUFFLEVEC record");
1343
1344 const Type *MaskTy =
1345 VectorType::get(Type::Int32Ty,
1346 cast<VectorType>(Vec1->getType())->getNumElements());
1347
1348 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001349 return Error("Invalid SHUFFLEVEC record");
1350 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1351 break;
1352 }
1353
1354 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001355 unsigned OpNum = 0;
1356 Value *LHS, *RHS;
1357 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1358 getValue(Record, OpNum, LHS->getType(), RHS) ||
1359 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001360 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001361
Nate Begemanc83ad0d2008-05-12 20:11:05 +00001362 if (LHS->getType()->isInteger() || isa<PointerType>(LHS->getType()))
Chris Lattner7337ab92007-05-06 00:00:00 +00001363 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanac80ade2008-05-12 19:01:56 +00001364 else if (LHS->getType()->isFloatingPoint())
1365 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1366 else if (LHS->getType()->isFPOrFPVector())
1367 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1368 else
1369 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001370 break;
1371 }
Devang Patel197be3d2008-02-22 02:49:49 +00001372 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1373 if (Record.size() != 2)
1374 return Error("Invalid GETRESULT record");
1375 unsigned OpNum = 0;
1376 Value *Op;
1377 getValueTypePair(Record, OpNum, NextValueNo, Op);
1378 unsigned Index = Record[1];
1379 I = new GetResultInst(Op, Index);
1380 break;
1381 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001382
Chris Lattner231cbcb2007-05-02 04:27:25 +00001383 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001384 {
1385 unsigned Size = Record.size();
1386 if (Size == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00001387 I = ReturnInst::Create();
Devang Pateld9d99ff2008-02-26 01:29:32 +00001388 break;
1389 } else {
1390 unsigned OpNum = 0;
Devang Patelf4511cd2008-02-26 19:38:17 +00001391 SmallVector<Value *,4> Vs;
Devang Pateld9d99ff2008-02-26 01:29:32 +00001392 do {
1393 Value *Op = NULL;
1394 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1395 return Error("Invalid RET record");
1396 Vs.push_back(Op);
1397 } while(OpNum != Record.size());
1398
Devang Patelf4511cd2008-02-26 19:38:17 +00001399 // SmallVector Vs has at least one element.
Gabor Greif051a9502008-04-06 20:25:17 +00001400 I = ReturnInst::Create(&Vs[0], Vs.size());
Devang Pateld9d99ff2008-02-26 01:29:32 +00001401 break;
1402 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001403 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001404 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001405 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001406 return Error("Invalid BR record");
1407 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1408 if (TrueDest == 0)
1409 return Error("Invalid BR record");
1410
1411 if (Record.size() == 1)
Gabor Greif051a9502008-04-06 20:25:17 +00001412 I = BranchInst::Create(TrueDest);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001413 else {
1414 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1415 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1416 if (FalseDest == 0 || Cond == 0)
1417 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001418 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001419 }
1420 break;
1421 }
1422 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1423 if (Record.size() < 3 || (Record.size() & 1) == 0)
1424 return Error("Invalid SWITCH record");
1425 const Type *OpTy = getTypeByID(Record[0]);
1426 Value *Cond = getFnValueByID(Record[1], OpTy);
1427 BasicBlock *Default = getBasicBlock(Record[2]);
1428 if (OpTy == 0 || Cond == 0 || Default == 0)
1429 return Error("Invalid SWITCH record");
1430 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001431 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001432 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1433 ConstantInt *CaseVal =
1434 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1435 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1436 if (CaseVal == 0 || DestBB == 0) {
1437 delete SI;
1438 return Error("Invalid SWITCH record!");
1439 }
1440 SI->addCase(CaseVal, DestBB);
1441 }
1442 I = SI;
1443 break;
1444 }
1445
Duncan Sandsdc024672007-11-27 13:23:08 +00001446 case bitc::FUNC_CODE_INST_INVOKE: {
1447 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001448 if (Record.size() < 4) return Error("Invalid INVOKE record");
Chris Lattner58d74912008-03-12 17:45:29 +00001449 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001450 unsigned CCInfo = Record[1];
1451 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1452 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001453
Chris Lattnera9bb7132007-05-08 05:38:01 +00001454 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001455 Value *Callee;
1456 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001457 return Error("Invalid INVOKE record");
1458
Chris Lattner7337ab92007-05-06 00:00:00 +00001459 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1460 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001461 dyn_cast<FunctionType>(CalleeTy->getElementType());
1462
1463 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001464 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1465 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001466 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001467
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001468 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001469 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1470 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1471 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001472 }
1473
Chris Lattner7337ab92007-05-06 00:00:00 +00001474 if (!FTy->isVarArg()) {
1475 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001476 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001477 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001478 // Read type/value pairs for varargs params.
1479 while (OpNum != Record.size()) {
1480 Value *Op;
1481 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1482 return Error("Invalid INVOKE record");
1483 Ops.push_back(Op);
1484 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001485 }
1486
Gabor Greif051a9502008-04-06 20:25:17 +00001487 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001488 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Duncan Sandsdc024672007-11-27 13:23:08 +00001489 cast<InvokeInst>(I)->setParamAttrs(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001490 break;
1491 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001492 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1493 I = new UnwindInst();
1494 break;
1495 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1496 I = new UnreachableInst();
1497 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001498 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001499 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001500 return Error("Invalid PHI record");
1501 const Type *Ty = getTypeByID(Record[0]);
1502 if (!Ty) return Error("Invalid PHI record");
1503
Gabor Greif051a9502008-04-06 20:25:17 +00001504 PHINode *PN = PHINode::Create(Ty);
Chris Lattner86941612008-04-13 00:14:42 +00001505 PN->reserveOperandSpace((Record.size()-1)/2);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001506
Chris Lattner15e6d172007-05-04 19:11:41 +00001507 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1508 Value *V = getFnValueByID(Record[1+i], Ty);
1509 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001510 if (!V || !BB) return Error("Invalid PHI record");
1511 PN->addIncoming(V, BB);
1512 }
1513 I = PN;
1514 break;
1515 }
1516
1517 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1518 if (Record.size() < 3)
1519 return Error("Invalid MALLOC record");
1520 const PointerType *Ty =
1521 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1522 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1523 unsigned Align = Record[2];
1524 if (!Ty || !Size) return Error("Invalid MALLOC record");
1525 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1526 break;
1527 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001528 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1529 unsigned OpNum = 0;
1530 Value *Op;
1531 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1532 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001533 return Error("Invalid FREE record");
1534 I = new FreeInst(Op);
1535 break;
1536 }
1537 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1538 if (Record.size() < 3)
1539 return Error("Invalid ALLOCA record");
1540 const PointerType *Ty =
1541 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1542 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1543 unsigned Align = Record[2];
1544 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1545 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1546 break;
1547 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001548 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001549 unsigned OpNum = 0;
1550 Value *Op;
1551 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1552 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001553 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001554
1555 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001556 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001557 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001558 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1559 unsigned OpNum = 0;
1560 Value *Val, *Ptr;
1561 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1562 getValue(Record, OpNum,
1563 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1564 OpNum+2 != Record.size())
1565 return Error("Invalid STORE record");
1566
1567 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1568 break;
1569 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001570 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001571 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001572 unsigned OpNum = 0;
1573 Value *Val, *Ptr;
1574 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001575 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001576 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001577 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001578
1579 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001580 break;
1581 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001582 case bitc::FUNC_CODE_INST_CALL: {
1583 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1584 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001585 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001586
Chris Lattner58d74912008-03-12 17:45:29 +00001587 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001588 unsigned CCInfo = Record[1];
1589
1590 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001591 Value *Callee;
1592 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1593 return Error("Invalid CALL record");
1594
1595 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001596 const FunctionType *FTy = 0;
1597 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001598 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001599 return Error("Invalid CALL record");
1600
1601 SmallVector<Value*, 16> Args;
1602 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001603 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001604 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1605 Args.push_back(getBasicBlock(Record[OpNum]));
1606 else
1607 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001608 if (Args.back() == 0) return Error("Invalid CALL record");
1609 }
1610
Chris Lattner0579f7f2007-05-03 22:04:19 +00001611 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001612 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001613 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001614 return Error("Invalid CALL record");
1615 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001616 while (OpNum != Record.size()) {
1617 Value *Op;
1618 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1619 return Error("Invalid CALL record");
1620 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001621 }
1622 }
1623
Gabor Greif051a9502008-04-06 20:25:17 +00001624 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001625 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1626 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Duncan Sandsdc024672007-11-27 13:23:08 +00001627 cast<CallInst>(I)->setParamAttrs(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001628 break;
1629 }
1630 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1631 if (Record.size() < 3)
1632 return Error("Invalid VAARG record");
1633 const Type *OpTy = getTypeByID(Record[0]);
1634 Value *Op = getFnValueByID(Record[1], OpTy);
1635 const Type *ResTy = getTypeByID(Record[2]);
1636 if (!OpTy || !Op || !ResTy)
1637 return Error("Invalid VAARG record");
1638 I = new VAArgInst(Op, ResTy);
1639 break;
1640 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001641 }
1642
1643 // Add instruction to end of current BB. If there is no current BB, reject
1644 // this file.
1645 if (CurBB == 0) {
1646 delete I;
1647 return Error("Invalid instruction with no BB");
1648 }
1649 CurBB->getInstList().push_back(I);
1650
1651 // If this was a terminator instruction, move to the next block.
1652 if (isa<TerminatorInst>(I)) {
1653 ++CurBBNo;
1654 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1655 }
1656
1657 // Non-void values get registered in the value table for future use.
1658 if (I && I->getType() != Type::VoidTy)
1659 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001660 }
1661
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001662 // Check the function list for unresolved values.
1663 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1664 if (A->getParent() == 0) {
1665 // We found at least one unresolved value. Nuke them all to avoid leaks.
1666 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1667 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1668 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1669 delete A;
1670 }
1671 }
Chris Lattner35a04702007-05-04 03:50:29 +00001672 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001673 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001674 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001675
1676 // Trim the value list down to the size it was before we parsed this function.
1677 ValueList.shrinkTo(ModuleValueListSize);
1678 std::vector<BasicBlock*>().swap(FunctionBBs);
1679
Chris Lattner48f84872007-05-01 04:59:48 +00001680 return false;
1681}
1682
Chris Lattnerb348bb82007-05-18 04:02:46 +00001683//===----------------------------------------------------------------------===//
1684// ModuleProvider implementation
1685//===----------------------------------------------------------------------===//
1686
1687
1688bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1689 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001690 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001691
1692 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1693 DeferredFunctionInfo.find(F);
1694 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1695
1696 // Move the bit stream to the saved position of the deferred function body and
1697 // restore the real linkage type for the function.
1698 Stream.JumpToBit(DFII->second.first);
1699 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1700
1701 if (ParseFunctionBody(F)) {
1702 if (ErrInfo) *ErrInfo = ErrorString;
1703 return true;
1704 }
Chandler Carruth69940402007-08-04 01:51:18 +00001705
1706 // Upgrade any old intrinsic calls in the function.
1707 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1708 E = UpgradedIntrinsics.end(); I != E; ++I) {
1709 if (I->first != I->second) {
1710 for (Value::use_iterator UI = I->first->use_begin(),
1711 UE = I->first->use_end(); UI != UE; ) {
1712 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1713 UpgradeIntrinsicCall(CI, I->second);
1714 }
1715 }
1716 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001717
1718 return false;
1719}
1720
1721void BitcodeReader::dematerializeFunction(Function *F) {
1722 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001723 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001724 return;
1725
1726 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1727
1728 // Just forget the function body, we can remat it later.
1729 F->deleteBody();
1730 F->setLinkage(GlobalValue::GhostLinkage);
1731}
1732
1733
1734Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1735 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1736 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1737 ++I) {
1738 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001739 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001740 materializeFunction(F, ErrInfo))
1741 return 0;
1742 }
Chandler Carruth69940402007-08-04 01:51:18 +00001743
1744 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1745 // delete the old functions to clean up. We can't do this unless the entire
1746 // module is materialized because there could always be another function body
1747 // with calls to the old function.
1748 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1749 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1750 if (I->first != I->second) {
1751 for (Value::use_iterator UI = I->first->use_begin(),
1752 UE = I->first->use_end(); UI != UE; ) {
1753 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1754 UpgradeIntrinsicCall(CI, I->second);
1755 }
1756 ValueList.replaceUsesOfWith(I->first, I->second);
1757 I->first->eraseFromParent();
1758 }
1759 }
1760 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1761
Chris Lattnerb348bb82007-05-18 04:02:46 +00001762 return TheModule;
1763}
1764
1765
1766/// This method is provided by the parent ModuleProvde class and overriden
1767/// here. It simply releases the module from its provided and frees up our
1768/// state.
1769/// @brief Release our hold on the generated module
1770Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1771 // Since we're losing control of this Module, we must hand it back complete
1772 Module *M = ModuleProvider::releaseModule(ErrInfo);
1773 FreeState();
1774 return M;
1775}
1776
Chris Lattner48f84872007-05-01 04:59:48 +00001777
Chris Lattnerc453f762007-04-29 07:54:31 +00001778//===----------------------------------------------------------------------===//
1779// External interface
1780//===----------------------------------------------------------------------===//
1781
1782/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1783///
1784ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1785 std::string *ErrMsg) {
1786 BitcodeReader *R = new BitcodeReader(Buffer);
1787 if (R->ParseBitcode()) {
1788 if (ErrMsg)
1789 *ErrMsg = R->getErrorString();
1790
1791 // Don't let the BitcodeReader dtor delete 'Buffer'.
1792 R->releaseMemoryBuffer();
1793 delete R;
1794 return 0;
1795 }
1796 return R;
1797}
1798
1799/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1800/// If an error occurs, return null and fill in *ErrMsg if non-null.
1801Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1802 BitcodeReader *R;
1803 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1804 if (!R) return 0;
1805
Chris Lattnerb348bb82007-05-18 04:02:46 +00001806 // Read in the entire module.
1807 Module *M = R->materializeModule(ErrMsg);
1808
1809 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1810 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001811 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001812
1813 // If there was no error, tell ModuleProvider not to delete it when its dtor
1814 // is run.
1815 if (M)
1816 M = R->releaseModule(ErrMsg);
1817
Chris Lattnerc453f762007-04-29 07:54:31 +00001818 delete R;
1819 return M;
1820}