blob: a8c62be88fc87bcc1d4d54f7b8f4034d2fca2235 [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;
Dale Johannesenaafce772008-05-14 20:12:51 +000069 case 8: return GlobalValue::CommonLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000070 }
71}
72
73static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
74 switch (Val) {
75 default: // Map unknown visibilities to default.
76 case 0: return GlobalValue::DefaultVisibility;
77 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000078 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000079 }
80}
81
Chris Lattnerf581c3b2007-04-24 07:07:11 +000082static int GetDecodedCastOpcode(unsigned Val) {
83 switch (Val) {
84 default: return -1;
85 case bitc::CAST_TRUNC : return Instruction::Trunc;
86 case bitc::CAST_ZEXT : return Instruction::ZExt;
87 case bitc::CAST_SEXT : return Instruction::SExt;
88 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
89 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
90 case bitc::CAST_UITOFP : return Instruction::UIToFP;
91 case bitc::CAST_SITOFP : return Instruction::SIToFP;
92 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
93 case bitc::CAST_FPEXT : return Instruction::FPExt;
94 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
95 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
96 case bitc::CAST_BITCAST : return Instruction::BitCast;
97 }
98}
99static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
100 switch (Val) {
101 default: return -1;
102 case bitc::BINOP_ADD: return Instruction::Add;
103 case bitc::BINOP_SUB: return Instruction::Sub;
104 case bitc::BINOP_MUL: return Instruction::Mul;
105 case bitc::BINOP_UDIV: return Instruction::UDiv;
106 case bitc::BINOP_SDIV:
107 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
108 case bitc::BINOP_UREM: return Instruction::URem;
109 case bitc::BINOP_SREM:
110 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
111 case bitc::BINOP_SHL: return Instruction::Shl;
112 case bitc::BINOP_LSHR: return Instruction::LShr;
113 case bitc::BINOP_ASHR: return Instruction::AShr;
114 case bitc::BINOP_AND: return Instruction::And;
115 case bitc::BINOP_OR: return Instruction::Or;
116 case bitc::BINOP_XOR: return Instruction::Xor;
117 }
118}
119
Gabor Greifefe65362008-05-10 08:32:32 +0000120namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000121namespace {
122 /// @brief A class for maintaining the slot number definition
123 /// as a placeholder for the actual definition for forward constants defs.
124 class ConstantPlaceHolder : public ConstantExpr {
125 ConstantPlaceHolder(); // DO NOT IMPLEMENT
126 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000127 public:
128 // allocate space for exactly one operand
129 void *operator new(size_t s) {
130 return User::operator new(s, 1);
131 }
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000132 explicit ConstantPlaceHolder(const Type *Ty)
Gabor Greifefe65362008-05-10 08:32:32 +0000133 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
134 Op<0>() = UndefValue::get(Type::Int32Ty);
Chris Lattner522b7b12007-04-24 05:48:56 +0000135 }
Gabor Greifefe65362008-05-10 08:32:32 +0000136 /// Provide fast operand accessors
137 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000138 };
139}
140
Gabor Greifefe65362008-05-10 08:32:32 +0000141
142 // FIXME: can we inherit this from ConstantExpr?
143template <>
144struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
145};
146
147DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
148}
149
150void BitcodeReaderValueList::resize(unsigned Desired) {
151 if (Desired > Capacity) {
152 // Since we expect many values to come from the bitcode file we better
153 // allocate the double amount, so that the array size grows exponentially
154 // at each reallocation. Also, add a small amount of 100 extra elements
155 // each time, to reallocate less frequently when the array is still small.
156 //
157 Capacity = Desired * 2 + 100;
158 Use *New = allocHungoffUses(Capacity);
159 Use *Old = OperandList;
160 unsigned Ops = getNumOperands();
161 for (int i(Ops - 1); i >= 0; --i)
162 New[i] = Old[i].get();
163 OperandList = New;
164 if (Old) Use::zap(Old, Old + Ops, true);
165 }
166}
167
Chris Lattner522b7b12007-04-24 05:48:56 +0000168Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
169 const Type *Ty) {
170 if (Idx >= size()) {
171 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000172 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000173 NumOperands = Idx+1;
174 }
175
Gabor Greifefe65362008-05-10 08:32:32 +0000176 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000177 assert(Ty == V->getType() && "Type mismatch in constant table!");
178 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000179 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000180
181 // Create and return a placeholder, which will later be RAUW'd.
182 Constant *C = new ConstantPlaceHolder(Ty);
Gabor Greif6c80c382008-05-26 21:33:52 +0000183 OperandList[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000184 return C;
185}
186
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000187Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
188 if (Idx >= size()) {
189 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000190 resize(Idx + 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000191 NumOperands = Idx+1;
192 }
193
Gabor Greifefe65362008-05-10 08:32:32 +0000194 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000195 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
196 return V;
197 }
198
Chris Lattner01ff65f2007-05-02 05:16:49 +0000199 // No type specified, must be invalid reference.
200 if (Ty == 0) return 0;
201
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000202 // Create and return a placeholder, which will later be RAUW'd.
203 Value *V = new Argument(Ty);
Gabor Greif6c80c382008-05-26 21:33:52 +0000204 OperandList[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000205 return V;
206}
207
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000208
209const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
210 // If the TypeID is in range, return it.
211 if (ID < TypeList.size())
212 return TypeList[ID].get();
213 if (!isTypeTable) return 0;
214
215 // The type table allows forward references. Push as many Opaque types as
216 // needed to get up to ID.
217 while (TypeList.size() <= ID)
218 TypeList.push_back(OpaqueType::get());
219 return TypeList.back().get();
220}
221
Chris Lattner48c85b82007-05-04 03:30:17 +0000222//===----------------------------------------------------------------------===//
223// Functions for parsing blocks from the bitcode file
224//===----------------------------------------------------------------------===//
225
226bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000227 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000228 return Error("Malformed block record");
229
230 if (!ParamAttrs.empty())
231 return Error("Multiple PARAMATTR blocks found!");
232
233 SmallVector<uint64_t, 64> Record;
234
Chris Lattner58d74912008-03-12 17:45:29 +0000235 SmallVector<ParamAttrsWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000236
237 // Read all the records.
238 while (1) {
239 unsigned Code = Stream.ReadCode();
240 if (Code == bitc::END_BLOCK) {
241 if (Stream.ReadBlockEnd())
242 return Error("Error at end of PARAMATTR block");
243 return false;
244 }
245
246 if (Code == bitc::ENTER_SUBBLOCK) {
247 // No known subblocks, always skip them.
248 Stream.ReadSubBlockID();
249 if (Stream.SkipBlock())
250 return Error("Malformed block record");
251 continue;
252 }
253
254 if (Code == bitc::DEFINE_ABBREV) {
255 Stream.ReadAbbrevRecord();
256 continue;
257 }
258
259 // Read a record.
260 Record.clear();
261 switch (Stream.ReadRecord(Code, Record)) {
262 default: // Default behavior: ignore.
263 break;
264 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
265 if (Record.size() & 1)
266 return Error("Invalid ENTRY record");
267
Chris Lattner48c85b82007-05-04 03:30:17 +0000268 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Duncan Sands5e41f652007-11-20 14:09:29 +0000269 if (Record[i+1] != ParamAttr::None)
270 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
Chris Lattner48c85b82007-05-04 03:30:17 +0000271 }
Chris Lattner461edd92008-03-12 02:25:52 +0000272
Chris Lattner58d74912008-03-12 17:45:29 +0000273 ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000274 Attrs.clear();
275 break;
276 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000277 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000278 }
279}
280
281
Chris Lattner86697142007-05-01 05:01:34 +0000282bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000283 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000284 return Error("Malformed block record");
285
286 if (!TypeList.empty())
287 return Error("Multiple TYPE_BLOCKs found!");
288
289 SmallVector<uint64_t, 64> Record;
290 unsigned NumRecords = 0;
291
292 // Read all the records for this type table.
293 while (1) {
294 unsigned Code = Stream.ReadCode();
295 if (Code == bitc::END_BLOCK) {
296 if (NumRecords != TypeList.size())
297 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000298 if (Stream.ReadBlockEnd())
299 return Error("Error at end of type table block");
300 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000301 }
302
303 if (Code == bitc::ENTER_SUBBLOCK) {
304 // No known subblocks, always skip them.
305 Stream.ReadSubBlockID();
306 if (Stream.SkipBlock())
307 return Error("Malformed block record");
308 continue;
309 }
310
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000311 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000312 Stream.ReadAbbrevRecord();
313 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000314 }
315
316 // Read a record.
317 Record.clear();
318 const Type *ResultTy = 0;
319 switch (Stream.ReadRecord(Code, Record)) {
320 default: // Default behavior: unknown type.
321 ResultTy = 0;
322 break;
323 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
324 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
325 // type list. This allows us to reserve space.
326 if (Record.size() < 1)
327 return Error("Invalid TYPE_CODE_NUMENTRY record");
328 TypeList.reserve(Record[0]);
329 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000330 case bitc::TYPE_CODE_VOID: // VOID
331 ResultTy = Type::VoidTy;
332 break;
333 case bitc::TYPE_CODE_FLOAT: // FLOAT
334 ResultTy = Type::FloatTy;
335 break;
336 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
337 ResultTy = Type::DoubleTy;
338 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000339 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
340 ResultTy = Type::X86_FP80Ty;
341 break;
342 case bitc::TYPE_CODE_FP128: // FP128
343 ResultTy = Type::FP128Ty;
344 break;
345 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
346 ResultTy = Type::PPC_FP128Ty;
347 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000348 case bitc::TYPE_CODE_LABEL: // LABEL
349 ResultTy = Type::LabelTy;
350 break;
351 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
352 ResultTy = 0;
353 break;
354 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
355 if (Record.size() < 1)
356 return Error("Invalid Integer type record");
357
358 ResultTy = IntegerType::get(Record[0]);
359 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000360 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
361 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000362 if (Record.size() < 1)
363 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000364 unsigned AddressSpace = 0;
365 if (Record.size() == 2)
366 AddressSpace = Record[1];
367 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000368 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000369 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000370 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000371 // FIXME: attrid is dead, remove it in LLVM 3.0
372 // FUNCTION: [vararg, attrid, retty, paramty x N]
373 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000374 return Error("Invalid FUNCTION type record");
375 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000376 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000377 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000378
Chris Lattnera1afde72007-11-27 17:48:06 +0000379 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000380 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000381 break;
382 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000383 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000384 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000385 return Error("Invalid STRUCT type record");
386 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000387 for (unsigned i = 1, e = Record.size(); i != e; ++i)
388 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000389 ResultTy = StructType::get(EltTys, Record[0]);
390 break;
391 }
392 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
393 if (Record.size() < 2)
394 return Error("Invalid ARRAY type record");
395 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
396 break;
397 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
398 if (Record.size() < 2)
399 return Error("Invalid VECTOR type record");
400 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
401 break;
402 }
403
404 if (NumRecords == TypeList.size()) {
405 // If this is a new type slot, just append it.
406 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
407 ++NumRecords;
408 } else if (ResultTy == 0) {
409 // Otherwise, this was forward referenced, so an opaque type was created,
410 // but the result type is actually just an opaque. Leave the one we
411 // created previously.
412 ++NumRecords;
413 } else {
414 // Otherwise, this was forward referenced, so an opaque type was created.
415 // Resolve the opaque type to the real type now.
416 assert(NumRecords < TypeList.size() && "Typelist imbalance");
417 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
418
419 // Don't directly push the new type on the Tab. Instead we want to replace
420 // the opaque type we previously inserted with the new concrete value. The
421 // refinement from the abstract (opaque) type to the new type causes all
422 // uses of the abstract type to use the concrete type (NewTy). This will
423 // also cause the opaque type to be deleted.
424 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
425
426 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000427 // value table... or with a preexisting type that was already in the
428 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000429 assert(TypeList[NumRecords-1].get() != OldTy &&
430 "refineAbstractType didn't work!");
431 }
432 }
433}
434
435
Chris Lattner86697142007-05-01 05:01:34 +0000436bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000437 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000438 return Error("Malformed block record");
439
440 SmallVector<uint64_t, 64> Record;
441
442 // Read all the records for this type table.
443 std::string TypeName;
444 while (1) {
445 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000446 if (Code == bitc::END_BLOCK) {
447 if (Stream.ReadBlockEnd())
448 return Error("Error at end of type symbol table block");
449 return false;
450 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000451
452 if (Code == bitc::ENTER_SUBBLOCK) {
453 // No known subblocks, always skip them.
454 Stream.ReadSubBlockID();
455 if (Stream.SkipBlock())
456 return Error("Malformed block record");
457 continue;
458 }
459
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000460 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000461 Stream.ReadAbbrevRecord();
462 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000463 }
464
465 // Read a record.
466 Record.clear();
467 switch (Stream.ReadRecord(Code, Record)) {
468 default: // Default behavior: unknown type.
469 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000470 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000471 if (ConvertToString(Record, 1, TypeName))
472 return Error("Invalid TST_ENTRY record");
473 unsigned TypeID = Record[0];
474 if (TypeID >= TypeList.size())
475 return Error("Invalid Type ID in TST_ENTRY record");
476
477 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
478 TypeName.clear();
479 break;
480 }
481 }
482}
483
Chris Lattner86697142007-05-01 05:01:34 +0000484bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000485 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000486 return Error("Malformed block record");
487
488 SmallVector<uint64_t, 64> Record;
489
490 // Read all the records for this value table.
491 SmallString<128> ValueName;
492 while (1) {
493 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000494 if (Code == bitc::END_BLOCK) {
495 if (Stream.ReadBlockEnd())
496 return Error("Error at end of value symbol table block");
497 return false;
498 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000499 if (Code == bitc::ENTER_SUBBLOCK) {
500 // No known subblocks, always skip them.
501 Stream.ReadSubBlockID();
502 if (Stream.SkipBlock())
503 return Error("Malformed block record");
504 continue;
505 }
506
507 if (Code == bitc::DEFINE_ABBREV) {
508 Stream.ReadAbbrevRecord();
509 continue;
510 }
511
512 // Read a record.
513 Record.clear();
514 switch (Stream.ReadRecord(Code, Record)) {
515 default: // Default behavior: unknown type.
516 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000517 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000518 if (ConvertToString(Record, 1, ValueName))
519 return Error("Invalid TST_ENTRY record");
520 unsigned ValueID = Record[0];
521 if (ValueID >= ValueList.size())
522 return Error("Invalid Value ID in VST_ENTRY record");
523 Value *V = ValueList[ValueID];
524
525 V->setName(&ValueName[0], ValueName.size());
526 ValueName.clear();
527 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000528 }
529 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000530 if (ConvertToString(Record, 1, ValueName))
531 return Error("Invalid VST_BBENTRY record");
532 BasicBlock *BB = getBasicBlock(Record[0]);
533 if (BB == 0)
534 return Error("Invalid BB ID in VST_BBENTRY record");
535
536 BB->setName(&ValueName[0], ValueName.size());
537 ValueName.clear();
538 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000539 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000540 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000541 }
542}
543
Chris Lattner0eef0802007-04-24 04:04:35 +0000544/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
545/// the LSB for dense VBR encoding.
546static uint64_t DecodeSignRotatedValue(uint64_t V) {
547 if ((V & 1) == 0)
548 return V >> 1;
549 if (V != 1)
550 return -(V >> 1);
551 // There is no such thing as -0 with integers. "-0" really means MININT.
552 return 1ULL << 63;
553}
554
Chris Lattner07d98b42007-04-26 02:46:40 +0000555/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
556/// values and aliases that we can.
557bool BitcodeReader::ResolveGlobalAndAliasInits() {
558 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
559 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
560
561 GlobalInitWorklist.swap(GlobalInits);
562 AliasInitWorklist.swap(AliasInits);
563
564 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000565 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000566 if (ValID >= ValueList.size()) {
567 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000568 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000569 } else {
570 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
571 GlobalInitWorklist.back().first->setInitializer(C);
572 else
573 return Error("Global variable initializer is not a constant!");
574 }
575 GlobalInitWorklist.pop_back();
576 }
577
578 while (!AliasInitWorklist.empty()) {
579 unsigned ValID = AliasInitWorklist.back().second;
580 if (ValID >= ValueList.size()) {
581 AliasInits.push_back(AliasInitWorklist.back());
582 } else {
583 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000584 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000585 else
586 return Error("Alias initializer is not a constant!");
587 }
588 AliasInitWorklist.pop_back();
589 }
590 return false;
591}
592
593
Chris Lattner86697142007-05-01 05:01:34 +0000594bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000595 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000596 return Error("Malformed block record");
597
598 SmallVector<uint64_t, 64> Record;
599
600 // Read all the records for this value table.
601 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000602 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000603 while (1) {
604 unsigned Code = Stream.ReadCode();
605 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000606 if (NextCstNo != ValueList.size())
607 return Error("Invalid constant reference!");
608
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000609 if (Stream.ReadBlockEnd())
610 return Error("Error at end of constants block");
611 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000612 }
613
614 if (Code == bitc::ENTER_SUBBLOCK) {
615 // No known subblocks, always skip them.
616 Stream.ReadSubBlockID();
617 if (Stream.SkipBlock())
618 return Error("Malformed block record");
619 continue;
620 }
621
622 if (Code == bitc::DEFINE_ABBREV) {
623 Stream.ReadAbbrevRecord();
624 continue;
625 }
626
627 // Read a record.
628 Record.clear();
629 Value *V = 0;
630 switch (Stream.ReadRecord(Code, Record)) {
631 default: // Default behavior: unknown constant
632 case bitc::CST_CODE_UNDEF: // UNDEF
633 V = UndefValue::get(CurTy);
634 break;
635 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
636 if (Record.empty())
637 return Error("Malformed CST_SETTYPE record");
638 if (Record[0] >= TypeList.size())
639 return Error("Invalid Type ID in CST_SETTYPE record");
640 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000641 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000642 case bitc::CST_CODE_NULL: // NULL
643 V = Constant::getNullValue(CurTy);
644 break;
645 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000646 if (!isa<IntegerType>(CurTy) || Record.empty())
647 return Error("Invalid CST_INTEGER record");
648 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
649 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000650 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
651 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000652 return Error("Invalid WIDE_INTEGER record");
653
Chris Lattner15e6d172007-05-04 19:11:41 +0000654 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000655 SmallVector<uint64_t, 8> Words;
656 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000657 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000658 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000659 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000660 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000661 break;
662 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000663 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000664 if (Record.empty())
665 return Error("Invalid FLOAT record");
666 if (CurTy == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000667 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000668 else if (CurTy == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000669 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000670 else if (CurTy == Type::X86_FP80Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000671 V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000672 else if (CurTy == Type::FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000673 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000674 else if (CurTy == Type::PPC_FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000675 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000676 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000677 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000678 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000679 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000680
Chris Lattner15e6d172007-05-04 19:11:41 +0000681 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
682 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000683 return Error("Invalid CST_AGGREGATE record");
684
Chris Lattner15e6d172007-05-04 19:11:41 +0000685 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000686 std::vector<Constant*> Elts;
687
688 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
689 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000690 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000691 STy->getElementType(i)));
692 V = ConstantStruct::get(STy, Elts);
693 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
694 const Type *EltTy = ATy->getElementType();
695 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000696 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000697 V = ConstantArray::get(ATy, Elts);
698 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
699 const Type *EltTy = VTy->getElementType();
700 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000701 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000702 V = ConstantVector::get(Elts);
703 } else {
704 V = UndefValue::get(CurTy);
705 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000706 break;
707 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000708 case bitc::CST_CODE_STRING: { // STRING: [values]
709 if (Record.empty())
710 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000711
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000712 const ArrayType *ATy = cast<ArrayType>(CurTy);
713 const Type *EltTy = ATy->getElementType();
714
715 unsigned Size = Record.size();
716 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000717 for (unsigned i = 0; i != Size; ++i)
718 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
719 V = ConstantArray::get(ATy, Elts);
720 break;
721 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000722 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
723 if (Record.empty())
724 return Error("Invalid CST_AGGREGATE record");
725
726 const ArrayType *ATy = cast<ArrayType>(CurTy);
727 const Type *EltTy = ATy->getElementType();
728
729 unsigned Size = Record.size();
730 std::vector<Constant*> Elts;
731 for (unsigned i = 0; i != Size; ++i)
732 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
733 Elts.push_back(Constant::getNullValue(EltTy));
734 V = ConstantArray::get(ATy, Elts);
735 break;
736 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000737 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
738 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
739 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000740 if (Opc < 0) {
741 V = UndefValue::get(CurTy); // Unknown binop.
742 } else {
743 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
744 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
745 V = ConstantExpr::get(Opc, LHS, RHS);
746 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000747 break;
748 }
749 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
750 if (Record.size() < 3) return Error("Invalid CE_CAST record");
751 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000752 if (Opc < 0) {
753 V = UndefValue::get(CurTy); // Unknown cast.
754 } else {
755 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000756 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000757 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
758 V = ConstantExpr::getCast(Opc, Op, CurTy);
759 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000760 break;
761 }
762 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000763 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000764 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000765 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000766 const Type *ElTy = getTypeByID(Record[i]);
767 if (!ElTy) return Error("Invalid CE_GEP record");
768 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
769 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000770 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
771 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000772 }
Dan Gohman81a0c0b2008-05-31 00:58:22 +0000773 case bitc::CST_CODE_CE_EXTRACTVAL: {
774 // CE_EXTRACTVAL: [opty, opval, n x indices]
775 const Type *AggTy = getTypeByID(Record[0]);
776 if (!AggTy || !AggTy->isAggregateType())
Dan Gohman0aab28b2008-05-31 19:11:15 +0000777 return Error("Invalid CE_EXTRACTVAL record");
Dan Gohman81a0c0b2008-05-31 00:58:22 +0000778 Constant *Agg = ValueList.getConstantFwdRef(Record[1], AggTy);
779 SmallVector<unsigned, 4> Indices;
780 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
781 uint64_t Index = Record[i];
782 if ((unsigned)Index != Index)
783 return Error("Invalid CE_EXTRACTVAL record");
784 Indices.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +0000785 }
Dan Gohman81a0c0b2008-05-31 00:58:22 +0000786 if (!ExtractValueInst::getIndexedType(AggTy,
787 Indices.begin(), Indices.end()))
788 return Error("Invalid CE_EXTRACTVAL record");
789 V = ConstantExpr::getExtractValue(Agg, &Indices[0], Indices.size());
Dan Gohmane4977cf2008-05-23 01:55:30 +0000790 break;
791 }
Dan Gohman81a0c0b2008-05-31 00:58:22 +0000792 case bitc::CST_CODE_CE_INSERTVAL: {
793 // CE_INSERTVAL: [opty, opval, opty, opval, n x indices]
794 const Type *AggTy = getTypeByID(Record[0]);
795 if (!AggTy || !AggTy->isAggregateType())
796 return Error("Invalid CE_INSERTVAL record");
797 Constant *Agg = ValueList.getConstantFwdRef(Record[1], AggTy);
798 const Type *ValTy = getTypeByID(Record[2]);
Dan Gohman0aab28b2008-05-31 19:11:15 +0000799 Constant *Val = ValueList.getConstantFwdRef(Record[3], ValTy);
Dan Gohman81a0c0b2008-05-31 00:58:22 +0000800 SmallVector<unsigned, 4> Indices;
801 for (unsigned i = 4, e = Record.size(); i != e; ++i) {
802 uint64_t Index = Record[i];
803 if ((unsigned)Index != Index)
804 return Error("Invalid CE_INSERTVAL record");
805 Indices.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +0000806 }
Dan Gohman81a0c0b2008-05-31 00:58:22 +0000807 if (ExtractValueInst::getIndexedType(AggTy,
808 Indices.begin(),
809 Indices.end()) != ValTy)
810 return Error("Invalid CE_INSERTVAL record");
811 V = ConstantExpr::getInsertValue(Agg, Val, &Indices[0], Indices.size());
Dan Gohmane4977cf2008-05-23 01:55:30 +0000812 break;
813 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000814 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
815 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
816 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
817 Type::Int1Ty),
818 ValueList.getConstantFwdRef(Record[1],CurTy),
819 ValueList.getConstantFwdRef(Record[2],CurTy));
820 break;
821 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
822 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
823 const VectorType *OpTy =
824 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
825 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
826 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
827 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
828 OpTy->getElementType());
829 V = ConstantExpr::getExtractElement(Op0, Op1);
830 break;
831 }
832 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
833 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
834 if (Record.size() < 3 || OpTy == 0)
835 return Error("Invalid CE_INSERTELT record");
836 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
837 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
838 OpTy->getElementType());
839 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
840 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
841 break;
842 }
843 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
844 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
845 if (Record.size() < 3 || OpTy == 0)
846 return Error("Invalid CE_INSERTELT record");
847 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
848 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
849 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
850 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
851 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
852 break;
853 }
854 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
855 if (Record.size() < 4) return Error("Invalid CE_CMP record");
856 const Type *OpTy = getTypeByID(Record[0]);
857 if (OpTy == 0) return Error("Invalid CE_CMP record");
858 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
859 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
860
861 if (OpTy->isFloatingPoint())
862 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanbaa64eb2008-05-12 20:33:52 +0000863 else if (!isa<VectorType>(OpTy))
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000864 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +0000865 else if (OpTy->isFPOrFPVector())
866 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
867 else
868 V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000869 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000870 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000871 case bitc::CST_CODE_INLINEASM: {
872 if (Record.size() < 2) return Error("Invalid INLINEASM record");
873 std::string AsmStr, ConstrStr;
874 bool HasSideEffects = Record[0];
875 unsigned AsmStrSize = Record[1];
876 if (2+AsmStrSize >= Record.size())
877 return Error("Invalid INLINEASM record");
878 unsigned ConstStrSize = Record[2+AsmStrSize];
879 if (3+AsmStrSize+ConstStrSize > Record.size())
880 return Error("Invalid INLINEASM record");
881
882 for (unsigned i = 0; i != AsmStrSize; ++i)
883 AsmStr += (char)Record[2+i];
884 for (unsigned i = 0; i != ConstStrSize; ++i)
885 ConstrStr += (char)Record[3+AsmStrSize+i];
886 const PointerType *PTy = cast<PointerType>(CurTy);
887 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
888 AsmStr, ConstrStr, HasSideEffects);
889 break;
890 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000891 }
892
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000893 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000894 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000895 }
896}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000897
Chris Lattner980e5aa2007-05-01 05:52:21 +0000898/// RememberAndSkipFunctionBody - When we see the block for a function body,
899/// remember where it is and then skip it. This lets us lazily deserialize the
900/// functions.
901bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000902 // Get the function we are talking about.
903 if (FunctionsWithBodies.empty())
904 return Error("Insufficient function protos");
905
906 Function *Fn = FunctionsWithBodies.back();
907 FunctionsWithBodies.pop_back();
908
909 // Save the current stream state.
910 uint64_t CurBit = Stream.GetCurrentBitNo();
911 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
912
913 // Set the functions linkage to GhostLinkage so we know it is lazily
914 // deserialized.
915 Fn->setLinkage(GlobalValue::GhostLinkage);
916
917 // Skip over the function block for now.
918 if (Stream.SkipBlock())
919 return Error("Malformed block record");
920 return false;
921}
922
Chris Lattner86697142007-05-01 05:01:34 +0000923bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000924 // Reject multiple MODULE_BLOCK's in a single bitstream.
925 if (TheModule)
926 return Error("Multiple MODULE_BLOCKs in same stream");
927
Chris Lattnere17b6582007-05-05 00:17:00 +0000928 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000929 return Error("Malformed block record");
930
931 // Otherwise, create the module.
932 TheModule = new Module(ModuleID);
933
934 SmallVector<uint64_t, 64> Record;
935 std::vector<std::string> SectionTable;
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000936 std::vector<std::string> CollectorTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000937
938 // Read all the records for this module.
939 while (!Stream.AtEndOfStream()) {
940 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000941 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000942 if (Stream.ReadBlockEnd())
943 return Error("Error at end of module block");
944
945 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000946 ResolveGlobalAndAliasInits();
947 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000948 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000949 if (!FunctionsWithBodies.empty())
950 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000951
Chandler Carruth69940402007-08-04 01:51:18 +0000952 // Look for intrinsic functions which need to be upgraded at some point
953 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
954 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +0000955 Function* NewFn;
956 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +0000957 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
958 }
959
Chris Lattner980e5aa2007-05-01 05:52:21 +0000960 // Force deallocation of memory for these vectors to favor the client that
961 // want lazy deserialization.
962 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
963 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
964 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000965 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000966 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000967
968 if (Code == bitc::ENTER_SUBBLOCK) {
969 switch (Stream.ReadSubBlockID()) {
970 default: // Skip unknown content.
971 if (Stream.SkipBlock())
972 return Error("Malformed block record");
973 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000974 case bitc::BLOCKINFO_BLOCK_ID:
975 if (Stream.ReadBlockInfoBlock())
976 return Error("Malformed BlockInfoBlock");
977 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000978 case bitc::PARAMATTR_BLOCK_ID:
979 if (ParseParamAttrBlock())
980 return true;
981 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000982 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000983 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000984 return true;
985 break;
986 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000987 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000988 return true;
989 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000990 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000991 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000992 return true;
993 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000994 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000995 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000996 return true;
997 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000998 case bitc::FUNCTION_BLOCK_ID:
999 // If this is the first function body we've seen, reverse the
1000 // FunctionsWithBodies list.
1001 if (!HasReversedFunctionsWithBodies) {
1002 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1003 HasReversedFunctionsWithBodies = true;
1004 }
1005
Chris Lattner980e5aa2007-05-01 05:52:21 +00001006 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001007 return true;
1008 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001009 }
1010 continue;
1011 }
1012
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001013 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001014 Stream.ReadAbbrevRecord();
1015 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001016 }
1017
1018 // Read a record.
1019 switch (Stream.ReadRecord(Code, Record)) {
1020 default: break; // Default behavior, ignore unknown content.
1021 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1022 if (Record.size() < 1)
1023 return Error("Malformed MODULE_CODE_VERSION");
1024 // Only version #0 is supported so far.
1025 if (Record[0] != 0)
1026 return Error("Unknown bitstream version!");
1027 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001028 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001029 std::string S;
1030 if (ConvertToString(Record, 0, S))
1031 return Error("Invalid MODULE_CODE_TRIPLE record");
1032 TheModule->setTargetTriple(S);
1033 break;
1034 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001035 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001036 std::string S;
1037 if (ConvertToString(Record, 0, S))
1038 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1039 TheModule->setDataLayout(S);
1040 break;
1041 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001042 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001043 std::string S;
1044 if (ConvertToString(Record, 0, S))
1045 return Error("Invalid MODULE_CODE_ASM record");
1046 TheModule->setModuleInlineAsm(S);
1047 break;
1048 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001049 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001050 std::string S;
1051 if (ConvertToString(Record, 0, S))
1052 return Error("Invalid MODULE_CODE_DEPLIB record");
1053 TheModule->addLibrary(S);
1054 break;
1055 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001056 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001057 std::string S;
1058 if (ConvertToString(Record, 0, S))
1059 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1060 SectionTable.push_back(S);
1061 break;
1062 }
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001063 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
1064 std::string S;
1065 if (ConvertToString(Record, 0, S))
1066 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
1067 CollectorTable.push_back(S);
1068 break;
1069 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001070 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001071 // linkage, alignment, section, visibility, threadlocal]
1072 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001073 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001074 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1075 const Type *Ty = getTypeByID(Record[0]);
1076 if (!isa<PointerType>(Ty))
1077 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001078 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001079 Ty = cast<PointerType>(Ty)->getElementType();
1080
1081 bool isConstant = Record[1];
1082 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1083 unsigned Alignment = (1 << Record[4]) >> 1;
1084 std::string Section;
1085 if (Record[5]) {
1086 if (Record[5]-1 >= SectionTable.size())
1087 return Error("Invalid section ID");
1088 Section = SectionTable[Record[5]-1];
1089 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001090 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001091 if (Record.size() > 6)
1092 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001093 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001094 if (Record.size() > 7)
1095 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001096
1097 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001098 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1099 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001100 NewGV->setAlignment(Alignment);
1101 if (!Section.empty())
1102 NewGV->setSection(Section);
1103 NewGV->setVisibility(Visibility);
1104 NewGV->setThreadLocal(isThreadLocal);
1105
Chris Lattner0b2482a2007-04-23 21:26:05 +00001106 ValueList.push_back(NewGV);
1107
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001108 // Remember which value to use for the global initializer.
1109 if (unsigned InitID = Record[2])
1110 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001111 break;
1112 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001113 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001114 // alignment, section, visibility, collector]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001115 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001116 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001117 return Error("Invalid MODULE_CODE_FUNCTION record");
1118 const Type *Ty = getTypeByID(Record[0]);
1119 if (!isa<PointerType>(Ty))
1120 return Error("Function not a pointer type!");
1121 const FunctionType *FTy =
1122 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1123 if (!FTy)
1124 return Error("Function not a pointer to function type!");
1125
Gabor Greif051a9502008-04-06 20:25:17 +00001126 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1127 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001128
1129 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001130 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001131 Func->setLinkage(GetDecodedLinkage(Record[3]));
Chris Lattner58d74912008-03-12 17:45:29 +00001132 Func->setParamAttrs(getParamAttrs(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001133
1134 Func->setAlignment((1 << Record[5]) >> 1);
1135 if (Record[6]) {
1136 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001137 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001138 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001139 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001140 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001141 if (Record.size() > 8 && Record[8]) {
1142 if (Record[8]-1 > CollectorTable.size())
1143 return Error("Invalid collector ID");
1144 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1145 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001146
Chris Lattner0b2482a2007-04-23 21:26:05 +00001147 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001148
1149 // If this is a function with a body, remember the prototype we are
1150 // creating now, so that we can match up the body with them later.
1151 if (!isProto)
1152 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001153 break;
1154 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001155 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001156 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001157 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001158 if (Record.size() < 3)
1159 return Error("Invalid MODULE_ALIAS record");
1160 const Type *Ty = getTypeByID(Record[0]);
1161 if (!isa<PointerType>(Ty))
1162 return Error("Function not a pointer type!");
1163
1164 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1165 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001166 // Old bitcode files didn't have visibility field.
1167 if (Record.size() > 3)
1168 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001169 ValueList.push_back(NewGA);
1170 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1171 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001172 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001173 /// MODULE_CODE_PURGEVALS: [numvals]
1174 case bitc::MODULE_CODE_PURGEVALS:
1175 // Trim down the value list to the specified size.
1176 if (Record.size() < 1 || Record[0] > ValueList.size())
1177 return Error("Invalid MODULE_PURGEVALS record");
1178 ValueList.shrinkTo(Record[0]);
1179 break;
1180 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001181 Record.clear();
1182 }
1183
1184 return Error("Premature end of bitstream");
1185}
1186
Chris Lattner6fa6a322008-07-09 05:14:23 +00001187/// SkipWrapperHeader - Some systems wrap bc files with a special header for
1188/// padding or other reasons. The format of this header is:
1189///
1190/// struct bc_header {
1191/// uint32_t Magic; // 0x0B17C0DE
1192/// uint32_t Version; // Version, currently always 0.
1193/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1194/// uint32_t BitcodeSize; // Size of traditional bitcode file.
1195/// ... potentially other gunk ...
1196/// };
1197///
1198/// This function is called when we find a file with a matching magic number.
1199/// In this case, skip down to the subsection of the file that is actually a BC
1200/// file.
1201static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
1202 enum {
1203 KnownHeaderSize = 4*4, // Size of header we read.
1204 OffsetField = 2*4, // Offset in bytes to Offset field.
1205 SizeField = 3*4 // Offset in bytes to Size field.
1206 };
1207
1208
1209 // Must contain the header!
1210 if (BufEnd-BufPtr < KnownHeaderSize) return true;
1211
1212 unsigned Offset = ( BufPtr[OffsetField ] |
1213 (BufPtr[OffsetField+1] << 8) |
1214 (BufPtr[OffsetField+2] << 16) |
1215 (BufPtr[OffsetField+3] << 24));
1216 unsigned Size = ( BufPtr[SizeField ] |
1217 (BufPtr[SizeField +1] << 8) |
1218 (BufPtr[SizeField +2] << 16) |
1219 (BufPtr[SizeField +3] << 24));
1220
1221 // Verify that Offset+Size fits in the file.
1222 if (Offset+Size > unsigned(BufEnd-BufPtr))
1223 return true;
1224 BufPtr += Offset;
1225 BufEnd = BufPtr+Size;
1226 return false;
1227}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001228
Chris Lattnerc453f762007-04-29 07:54:31 +00001229bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001230 TheModule = 0;
1231
Chris Lattnerc453f762007-04-29 07:54:31 +00001232 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001233 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1234
Chris Lattnerc453f762007-04-29 07:54:31 +00001235 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001236 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1237
1238 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1239 // The magic number is 0x0B17C0DE stored in little endian.
1240 if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 &&
1241 BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
1242 if (SkipWrapperHeader(BufPtr, BufEnd))
1243 return Error("Invalid bitcode wrapper header");
1244
1245 Stream.init(BufPtr, BufEnd);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001246
1247 // Sniff for the signature.
1248 if (Stream.Read(8) != 'B' ||
1249 Stream.Read(8) != 'C' ||
1250 Stream.Read(4) != 0x0 ||
1251 Stream.Read(4) != 0xC ||
1252 Stream.Read(4) != 0xE ||
1253 Stream.Read(4) != 0xD)
1254 return Error("Invalid bitcode signature");
1255
1256 // We expect a number of well-defined blocks, though we don't necessarily
1257 // need to understand them all.
1258 while (!Stream.AtEndOfStream()) {
1259 unsigned Code = Stream.ReadCode();
1260
1261 if (Code != bitc::ENTER_SUBBLOCK)
1262 return Error("Invalid record at top-level");
1263
1264 unsigned BlockID = Stream.ReadSubBlockID();
1265
1266 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001267 switch (BlockID) {
1268 case bitc::BLOCKINFO_BLOCK_ID:
1269 if (Stream.ReadBlockInfoBlock())
1270 return Error("Malformed BlockInfoBlock");
1271 break;
1272 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001273 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001274 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001275 break;
1276 default:
1277 if (Stream.SkipBlock())
1278 return Error("Malformed block record");
1279 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001280 }
1281 }
1282
1283 return false;
1284}
Chris Lattnerc453f762007-04-29 07:54:31 +00001285
Chris Lattner48f84872007-05-01 04:59:48 +00001286
Chris Lattner980e5aa2007-05-01 05:52:21 +00001287/// ParseFunctionBody - Lazily parse the specified function body block.
1288bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001289 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001290 return Error("Malformed block record");
1291
1292 unsigned ModuleValueListSize = ValueList.size();
1293
1294 // Add all the function arguments to the value table.
1295 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1296 ValueList.push_back(I);
1297
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001298 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001299 BasicBlock *CurBB = 0;
1300 unsigned CurBBNo = 0;
1301
Chris Lattner980e5aa2007-05-01 05:52:21 +00001302 // Read all the records.
1303 SmallVector<uint64_t, 64> Record;
1304 while (1) {
1305 unsigned Code = Stream.ReadCode();
1306 if (Code == bitc::END_BLOCK) {
1307 if (Stream.ReadBlockEnd())
1308 return Error("Error at end of function block");
1309 break;
1310 }
1311
1312 if (Code == bitc::ENTER_SUBBLOCK) {
1313 switch (Stream.ReadSubBlockID()) {
1314 default: // Skip unknown content.
1315 if (Stream.SkipBlock())
1316 return Error("Malformed block record");
1317 break;
1318 case bitc::CONSTANTS_BLOCK_ID:
1319 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001320 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001321 break;
1322 case bitc::VALUE_SYMTAB_BLOCK_ID:
1323 if (ParseValueSymbolTable()) return true;
1324 break;
1325 }
1326 continue;
1327 }
1328
1329 if (Code == bitc::DEFINE_ABBREV) {
1330 Stream.ReadAbbrevRecord();
1331 continue;
1332 }
1333
1334 // Read a record.
1335 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001336 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001337 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001338 default: // Default behavior: reject
1339 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001340 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001341 if (Record.size() < 1 || Record[0] == 0)
1342 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001343 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001344 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001345 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001346 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001347 CurBB = FunctionBBs[0];
1348 continue;
1349
Chris Lattnerabfbf852007-05-06 00:21:25 +00001350 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1351 unsigned OpNum = 0;
1352 Value *LHS, *RHS;
1353 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1354 getValue(Record, OpNum, LHS->getType(), RHS) ||
1355 OpNum+1 != Record.size())
1356 return Error("Invalid BINOP record");
1357
1358 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1359 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001360 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001361 break;
1362 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001363 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1364 unsigned OpNum = 0;
1365 Value *Op;
1366 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1367 OpNum+2 != Record.size())
1368 return Error("Invalid CAST record");
1369
1370 const Type *ResTy = getTypeByID(Record[OpNum]);
1371 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1372 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001373 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001374 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Chris Lattner231cbcb2007-05-02 04:27:25 +00001375 break;
1376 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001377 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001378 unsigned OpNum = 0;
1379 Value *BasePtr;
1380 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001381 return Error("Invalid GEP record");
1382
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001383 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001384 while (OpNum != Record.size()) {
1385 Value *Op;
1386 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001387 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001388 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001389 }
1390
Gabor Greif051a9502008-04-06 20:25:17 +00001391 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001392 break;
1393 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001394
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001395 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1396 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001397 unsigned OpNum = 0;
1398 Value *Agg;
1399 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1400 return Error("Invalid EXTRACTVAL record");
1401
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001402 SmallVector<unsigned, 4> EXTRACTVALIdx;
1403 for (unsigned RecSize = Record.size();
1404 OpNum != RecSize; ++OpNum) {
1405 uint64_t Index = Record[OpNum];
1406 if ((unsigned)Index != Index)
1407 return Error("Invalid EXTRACTVAL index");
1408 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001409 }
1410
1411 I = ExtractValueInst::Create(Agg,
1412 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1413 break;
1414 }
1415
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001416 case bitc::FUNC_CODE_INST_INSERTVAL: {
1417 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001418 unsigned OpNum = 0;
1419 Value *Agg;
1420 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1421 return Error("Invalid INSERTVAL record");
1422 Value *Val;
1423 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1424 return Error("Invalid INSERTVAL record");
1425
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001426 SmallVector<unsigned, 4> INSERTVALIdx;
1427 for (unsigned RecSize = Record.size();
1428 OpNum != RecSize; ++OpNum) {
1429 uint64_t Index = Record[OpNum];
1430 if ((unsigned)Index != Index)
1431 return Error("Invalid INSERTVAL index");
1432 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001433 }
1434
1435 I = InsertValueInst::Create(Agg, Val,
1436 INSERTVALIdx.begin(), INSERTVALIdx.end());
1437 break;
1438 }
1439
Chris Lattnerabfbf852007-05-06 00:21:25 +00001440 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1441 unsigned OpNum = 0;
1442 Value *TrueVal, *FalseVal, *Cond;
1443 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1444 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1445 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001446 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001447
Gabor Greif051a9502008-04-06 20:25:17 +00001448 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001449 break;
1450 }
1451
1452 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001453 unsigned OpNum = 0;
1454 Value *Vec, *Idx;
1455 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1456 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001457 return Error("Invalid EXTRACTELT record");
1458 I = new ExtractElementInst(Vec, Idx);
1459 break;
1460 }
1461
1462 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001463 unsigned OpNum = 0;
1464 Value *Vec, *Elt, *Idx;
1465 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1466 getValue(Record, OpNum,
1467 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1468 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001469 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001470 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001471 break;
1472 }
1473
Chris Lattnerabfbf852007-05-06 00:21:25 +00001474 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1475 unsigned OpNum = 0;
1476 Value *Vec1, *Vec2, *Mask;
1477 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1478 getValue(Record, OpNum, Vec1->getType(), Vec2))
1479 return Error("Invalid SHUFFLEVEC record");
1480
1481 const Type *MaskTy =
1482 VectorType::get(Type::Int32Ty,
1483 cast<VectorType>(Vec1->getType())->getNumElements());
1484
1485 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001486 return Error("Invalid SHUFFLEVEC record");
1487 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1488 break;
1489 }
1490
1491 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001492 unsigned OpNum = 0;
1493 Value *LHS, *RHS;
1494 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1495 getValue(Record, OpNum, LHS->getType(), RHS) ||
1496 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001497 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001498
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001499 if (LHS->getType()->isFloatingPoint())
Nate Begemanac80ade2008-05-12 19:01:56 +00001500 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001501 else if (!isa<VectorType>(LHS->getType()))
1502 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanac80ade2008-05-12 19:01:56 +00001503 else if (LHS->getType()->isFPOrFPVector())
1504 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1505 else
1506 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001507 break;
1508 }
Devang Patel197be3d2008-02-22 02:49:49 +00001509 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1510 if (Record.size() != 2)
1511 return Error("Invalid GETRESULT record");
1512 unsigned OpNum = 0;
1513 Value *Op;
1514 getValueTypePair(Record, OpNum, NextValueNo, Op);
1515 unsigned Index = Record[1];
1516 I = new GetResultInst(Op, Index);
1517 break;
1518 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001519
Chris Lattner231cbcb2007-05-02 04:27:25 +00001520 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001521 {
1522 unsigned Size = Record.size();
1523 if (Size == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00001524 I = ReturnInst::Create();
Devang Pateld9d99ff2008-02-26 01:29:32 +00001525 break;
1526 } else {
1527 unsigned OpNum = 0;
Devang Patelf4511cd2008-02-26 19:38:17 +00001528 SmallVector<Value *,4> Vs;
Devang Pateld9d99ff2008-02-26 01:29:32 +00001529 do {
1530 Value *Op = NULL;
1531 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1532 return Error("Invalid RET record");
1533 Vs.push_back(Op);
1534 } while(OpNum != Record.size());
1535
Devang Patelf4511cd2008-02-26 19:38:17 +00001536 // SmallVector Vs has at least one element.
Gabor Greif051a9502008-04-06 20:25:17 +00001537 I = ReturnInst::Create(&Vs[0], Vs.size());
Devang Pateld9d99ff2008-02-26 01:29:32 +00001538 break;
1539 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001540 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001541 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001542 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001543 return Error("Invalid BR record");
1544 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1545 if (TrueDest == 0)
1546 return Error("Invalid BR record");
1547
1548 if (Record.size() == 1)
Gabor Greif051a9502008-04-06 20:25:17 +00001549 I = BranchInst::Create(TrueDest);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001550 else {
1551 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1552 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1553 if (FalseDest == 0 || Cond == 0)
1554 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001555 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001556 }
1557 break;
1558 }
1559 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1560 if (Record.size() < 3 || (Record.size() & 1) == 0)
1561 return Error("Invalid SWITCH record");
1562 const Type *OpTy = getTypeByID(Record[0]);
1563 Value *Cond = getFnValueByID(Record[1], OpTy);
1564 BasicBlock *Default = getBasicBlock(Record[2]);
1565 if (OpTy == 0 || Cond == 0 || Default == 0)
1566 return Error("Invalid SWITCH record");
1567 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001568 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001569 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1570 ConstantInt *CaseVal =
1571 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1572 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1573 if (CaseVal == 0 || DestBB == 0) {
1574 delete SI;
1575 return Error("Invalid SWITCH record!");
1576 }
1577 SI->addCase(CaseVal, DestBB);
1578 }
1579 I = SI;
1580 break;
1581 }
1582
Duncan Sandsdc024672007-11-27 13:23:08 +00001583 case bitc::FUNC_CODE_INST_INVOKE: {
1584 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001585 if (Record.size() < 4) return Error("Invalid INVOKE record");
Chris Lattner58d74912008-03-12 17:45:29 +00001586 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001587 unsigned CCInfo = Record[1];
1588 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1589 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001590
Chris Lattnera9bb7132007-05-08 05:38:01 +00001591 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001592 Value *Callee;
1593 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001594 return Error("Invalid INVOKE record");
1595
Chris Lattner7337ab92007-05-06 00:00:00 +00001596 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1597 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001598 dyn_cast<FunctionType>(CalleeTy->getElementType());
1599
1600 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001601 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1602 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001603 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001604
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001605 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001606 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1607 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1608 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001609 }
1610
Chris Lattner7337ab92007-05-06 00:00:00 +00001611 if (!FTy->isVarArg()) {
1612 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001613 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001614 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001615 // Read type/value pairs for varargs params.
1616 while (OpNum != Record.size()) {
1617 Value *Op;
1618 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1619 return Error("Invalid INVOKE record");
1620 Ops.push_back(Op);
1621 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001622 }
1623
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001624 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1625 Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001626 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Duncan Sandsdc024672007-11-27 13:23:08 +00001627 cast<InvokeInst>(I)->setParamAttrs(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001628 break;
1629 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001630 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1631 I = new UnwindInst();
1632 break;
1633 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1634 I = new UnreachableInst();
1635 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001636 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001637 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001638 return Error("Invalid PHI record");
1639 const Type *Ty = getTypeByID(Record[0]);
1640 if (!Ty) return Error("Invalid PHI record");
1641
Gabor Greif051a9502008-04-06 20:25:17 +00001642 PHINode *PN = PHINode::Create(Ty);
Chris Lattner86941612008-04-13 00:14:42 +00001643 PN->reserveOperandSpace((Record.size()-1)/2);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001644
Chris Lattner15e6d172007-05-04 19:11:41 +00001645 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1646 Value *V = getFnValueByID(Record[1+i], Ty);
1647 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001648 if (!V || !BB) return Error("Invalid PHI record");
1649 PN->addIncoming(V, BB);
1650 }
1651 I = PN;
1652 break;
1653 }
1654
1655 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1656 if (Record.size() < 3)
1657 return Error("Invalid MALLOC record");
1658 const PointerType *Ty =
1659 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1660 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1661 unsigned Align = Record[2];
1662 if (!Ty || !Size) return Error("Invalid MALLOC record");
1663 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1664 break;
1665 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001666 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1667 unsigned OpNum = 0;
1668 Value *Op;
1669 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1670 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001671 return Error("Invalid FREE record");
1672 I = new FreeInst(Op);
1673 break;
1674 }
1675 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1676 if (Record.size() < 3)
1677 return Error("Invalid ALLOCA record");
1678 const PointerType *Ty =
1679 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1680 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1681 unsigned Align = Record[2];
1682 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1683 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1684 break;
1685 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001686 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001687 unsigned OpNum = 0;
1688 Value *Op;
1689 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1690 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001691 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001692
1693 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001694 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001695 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001696 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1697 unsigned OpNum = 0;
1698 Value *Val, *Ptr;
1699 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1700 getValue(Record, OpNum,
1701 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1702 OpNum+2 != Record.size())
1703 return Error("Invalid STORE record");
1704
1705 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1706 break;
1707 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001708 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001709 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001710 unsigned OpNum = 0;
1711 Value *Val, *Ptr;
1712 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001713 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001714 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001715 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001716
1717 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001718 break;
1719 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001720 case bitc::FUNC_CODE_INST_CALL: {
1721 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1722 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001723 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001724
Chris Lattner58d74912008-03-12 17:45:29 +00001725 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001726 unsigned CCInfo = Record[1];
1727
1728 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001729 Value *Callee;
1730 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1731 return Error("Invalid CALL record");
1732
1733 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001734 const FunctionType *FTy = 0;
1735 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001736 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001737 return Error("Invalid CALL record");
1738
1739 SmallVector<Value*, 16> Args;
1740 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001741 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001742 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1743 Args.push_back(getBasicBlock(Record[OpNum]));
1744 else
1745 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001746 if (Args.back() == 0) return Error("Invalid CALL record");
1747 }
1748
Chris Lattner0579f7f2007-05-03 22:04:19 +00001749 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001750 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001751 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001752 return Error("Invalid CALL record");
1753 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001754 while (OpNum != Record.size()) {
1755 Value *Op;
1756 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1757 return Error("Invalid CALL record");
1758 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001759 }
1760 }
1761
Gabor Greif051a9502008-04-06 20:25:17 +00001762 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001763 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1764 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Duncan Sandsdc024672007-11-27 13:23:08 +00001765 cast<CallInst>(I)->setParamAttrs(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001766 break;
1767 }
1768 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1769 if (Record.size() < 3)
1770 return Error("Invalid VAARG record");
1771 const Type *OpTy = getTypeByID(Record[0]);
1772 Value *Op = getFnValueByID(Record[1], OpTy);
1773 const Type *ResTy = getTypeByID(Record[2]);
1774 if (!OpTy || !Op || !ResTy)
1775 return Error("Invalid VAARG record");
1776 I = new VAArgInst(Op, ResTy);
1777 break;
1778 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001779 }
1780
1781 // Add instruction to end of current BB. If there is no current BB, reject
1782 // this file.
1783 if (CurBB == 0) {
1784 delete I;
1785 return Error("Invalid instruction with no BB");
1786 }
1787 CurBB->getInstList().push_back(I);
1788
1789 // If this was a terminator instruction, move to the next block.
1790 if (isa<TerminatorInst>(I)) {
1791 ++CurBBNo;
1792 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1793 }
1794
1795 // Non-void values get registered in the value table for future use.
1796 if (I && I->getType() != Type::VoidTy)
1797 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001798 }
1799
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001800 // Check the function list for unresolved values.
1801 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1802 if (A->getParent() == 0) {
1803 // We found at least one unresolved value. Nuke them all to avoid leaks.
1804 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1805 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1806 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1807 delete A;
1808 }
1809 }
Chris Lattner35a04702007-05-04 03:50:29 +00001810 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001811 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001812 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001813
1814 // Trim the value list down to the size it was before we parsed this function.
1815 ValueList.shrinkTo(ModuleValueListSize);
1816 std::vector<BasicBlock*>().swap(FunctionBBs);
1817
Chris Lattner48f84872007-05-01 04:59:48 +00001818 return false;
1819}
1820
Chris Lattnerb348bb82007-05-18 04:02:46 +00001821//===----------------------------------------------------------------------===//
1822// ModuleProvider implementation
1823//===----------------------------------------------------------------------===//
1824
1825
1826bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1827 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001828 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001829
1830 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1831 DeferredFunctionInfo.find(F);
1832 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1833
1834 // Move the bit stream to the saved position of the deferred function body and
1835 // restore the real linkage type for the function.
1836 Stream.JumpToBit(DFII->second.first);
1837 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1838
1839 if (ParseFunctionBody(F)) {
1840 if (ErrInfo) *ErrInfo = ErrorString;
1841 return true;
1842 }
Chandler Carruth69940402007-08-04 01:51:18 +00001843
1844 // Upgrade any old intrinsic calls in the function.
1845 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1846 E = UpgradedIntrinsics.end(); I != E; ++I) {
1847 if (I->first != I->second) {
1848 for (Value::use_iterator UI = I->first->use_begin(),
1849 UE = I->first->use_end(); UI != UE; ) {
1850 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1851 UpgradeIntrinsicCall(CI, I->second);
1852 }
1853 }
1854 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001855
1856 return false;
1857}
1858
1859void BitcodeReader::dematerializeFunction(Function *F) {
1860 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001861 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001862 return;
1863
1864 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1865
1866 // Just forget the function body, we can remat it later.
1867 F->deleteBody();
1868 F->setLinkage(GlobalValue::GhostLinkage);
1869}
1870
1871
1872Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1873 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1874 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1875 ++I) {
1876 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001877 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001878 materializeFunction(F, ErrInfo))
1879 return 0;
1880 }
Chandler Carruth69940402007-08-04 01:51:18 +00001881
1882 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1883 // delete the old functions to clean up. We can't do this unless the entire
1884 // module is materialized because there could always be another function body
1885 // with calls to the old function.
1886 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1887 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1888 if (I->first != I->second) {
1889 for (Value::use_iterator UI = I->first->use_begin(),
1890 UE = I->first->use_end(); UI != UE; ) {
1891 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1892 UpgradeIntrinsicCall(CI, I->second);
1893 }
1894 ValueList.replaceUsesOfWith(I->first, I->second);
1895 I->first->eraseFromParent();
1896 }
1897 }
1898 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1899
Chris Lattnerb348bb82007-05-18 04:02:46 +00001900 return TheModule;
1901}
1902
1903
1904/// This method is provided by the parent ModuleProvde class and overriden
1905/// here. It simply releases the module from its provided and frees up our
1906/// state.
1907/// @brief Release our hold on the generated module
1908Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1909 // Since we're losing control of this Module, we must hand it back complete
1910 Module *M = ModuleProvider::releaseModule(ErrInfo);
1911 FreeState();
1912 return M;
1913}
1914
Chris Lattner48f84872007-05-01 04:59:48 +00001915
Chris Lattnerc453f762007-04-29 07:54:31 +00001916//===----------------------------------------------------------------------===//
1917// External interface
1918//===----------------------------------------------------------------------===//
1919
1920/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1921///
1922ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1923 std::string *ErrMsg) {
1924 BitcodeReader *R = new BitcodeReader(Buffer);
1925 if (R->ParseBitcode()) {
1926 if (ErrMsg)
1927 *ErrMsg = R->getErrorString();
1928
1929 // Don't let the BitcodeReader dtor delete 'Buffer'.
1930 R->releaseMemoryBuffer();
1931 delete R;
1932 return 0;
1933 }
1934 return R;
1935}
1936
1937/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1938/// If an error occurs, return null and fill in *ErrMsg if non-null.
1939Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1940 BitcodeReader *R;
1941 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1942 if (!R) return 0;
1943
Chris Lattnerb348bb82007-05-18 04:02:46 +00001944 // Read in the entire module.
1945 Module *M = R->materializeModule(ErrMsg);
1946
1947 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1948 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001949 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001950
1951 // If there was no error, tell ModuleProvider not to delete it when its dtor
1952 // is run.
1953 if (M)
1954 M = R->releaseModule(ErrMsg);
1955
Chris Lattnerc453f762007-04-29 07:54:31 +00001956 delete R;
1957 return M;
1958}