blob: ee9e115412065c13e644ff42c1aa4bb467aa541c [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 }
Chris Lattnerf4a97da2008-08-21 00:11:50 +0000136
137 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
138 static inline bool classof(const ConstantPlaceHolder *) { return true; }
139 static bool classof(const Value *V) {
140 return isa<ConstantExpr>(V) &&
141 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
142 }
143
144
Gabor Greifefe65362008-05-10 08:32:32 +0000145 /// Provide fast operand accessors
146 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000147 };
148}
149
Gabor Greifefe65362008-05-10 08:32:32 +0000150
151 // FIXME: can we inherit this from ConstantExpr?
152template <>
153struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
154};
155
156DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
157}
158
159void BitcodeReaderValueList::resize(unsigned Desired) {
160 if (Desired > Capacity) {
161 // Since we expect many values to come from the bitcode file we better
162 // allocate the double amount, so that the array size grows exponentially
163 // at each reallocation. Also, add a small amount of 100 extra elements
164 // each time, to reallocate less frequently when the array is still small.
165 //
166 Capacity = Desired * 2 + 100;
167 Use *New = allocHungoffUses(Capacity);
168 Use *Old = OperandList;
169 unsigned Ops = getNumOperands();
170 for (int i(Ops - 1); i >= 0; --i)
171 New[i] = Old[i].get();
172 OperandList = New;
173 if (Old) Use::zap(Old, Old + Ops, true);
174 }
175}
176
Chris Lattner522b7b12007-04-24 05:48:56 +0000177Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
178 const Type *Ty) {
179 if (Idx >= size()) {
180 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000181 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000182 NumOperands = Idx+1;
183 }
184
Gabor Greifefe65362008-05-10 08:32:32 +0000185 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000186 assert(Ty == V->getType() && "Type mismatch in constant table!");
187 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000188 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000189
190 // Create and return a placeholder, which will later be RAUW'd.
191 Constant *C = new ConstantPlaceHolder(Ty);
Gabor Greif6c80c382008-05-26 21:33:52 +0000192 OperandList[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000193 return C;
194}
195
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000196Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
197 if (Idx >= size()) {
198 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000199 resize(Idx + 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000200 NumOperands = Idx+1;
201 }
202
Gabor Greifefe65362008-05-10 08:32:32 +0000203 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000204 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
205 return V;
206 }
207
Chris Lattner01ff65f2007-05-02 05:16:49 +0000208 // No type specified, must be invalid reference.
209 if (Ty == 0) return 0;
210
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000211 // Create and return a placeholder, which will later be RAUW'd.
212 Value *V = new Argument(Ty);
Gabor Greif6c80c382008-05-26 21:33:52 +0000213 OperandList[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000214 return V;
215}
216
Chris Lattnerf4a97da2008-08-21 00:11:50 +0000217/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
218/// resolves any forward references. The idea behind this is that we sometimes
219/// get constants (such as large arrays) which reference *many* forward ref
220/// constants. Replacing each of these causes a lot of thrashing when
221/// building/reuniquing the constant. Instead of doing this, we look at all the
222/// uses and rewrite all the place holders at once for any constant that uses
223/// a placeholder.
224void BitcodeReaderValueList::ResolveConstantForwardRefs() {
225 // Sort the values by-pointer so that they are efficient to look up with a
226 // binary search.
227 std::sort(ResolveConstants.begin(), ResolveConstants.end());
228
229 SmallVector<Constant*, 64> NewOps;
230
231 while (!ResolveConstants.empty()) {
232 Value *RealVal = getOperand(ResolveConstants.back().second);
233 Constant *Placeholder = ResolveConstants.back().first;
234 ResolveConstants.pop_back();
235
236 // Loop over all users of the placeholder, updating them to reference the
237 // new value. If they reference more than one placeholder, update them all
238 // at once.
239 while (!Placeholder->use_empty()) {
240 User *U = Placeholder->use_back();
241 // If the using object isn't uniqued, just update the operands. This
242 // handles instructions and initializers for global variables.
243 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
244 U->replaceUsesOfWith(Placeholder, RealVal);
245 continue;
246 }
247
248 // Otherwise, we have a constant that uses the placeholder. Replace that
249 // constant with a new constant that has *all* placeholder uses updated.
250 Constant *UserC = cast<Constant>(U);
251 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
252 I != E; ++I) {
253 Value *NewOp;
254 if (!isa<ConstantPlaceHolder>(*I)) {
255 // Not a placeholder reference.
256 NewOp = *I;
257 } else if (*I == Placeholder) {
258 // Common case is that it just references this one placeholder.
259 NewOp = RealVal;
260 } else {
261 // Otherwise, look up the placeholder in ResolveConstants.
262 ResolveConstantsTy::iterator It =
263 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
264 std::pair<Constant*, unsigned>(cast<Constant>(*I),
265 0));
266 assert(It != ResolveConstants.end() && It->first == *I);
267 NewOp = this->getOperand(It->second);
268 }
269
270 NewOps.push_back(cast<Constant>(NewOp));
271 }
272
273 // Make the new constant.
274 Constant *NewC;
275 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
276 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
277 } else if (isa<ConstantStruct>(UserC)) {
278 NewC = ConstantStruct::get(&NewOps[0], NewOps.size());
279 } else if (isa<ConstantVector>(UserC)) {
280 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
281 } else {
282 // Must be a constant expression.
283 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
284 NewOps.size());
285 }
286
287 UserC->replaceAllUsesWith(NewC);
288 UserC->destroyConstant();
289 NewOps.clear();
290 }
291
292 delete Placeholder;
293 }
294}
295
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000296
297const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
298 // If the TypeID is in range, return it.
299 if (ID < TypeList.size())
300 return TypeList[ID].get();
301 if (!isTypeTable) return 0;
302
303 // The type table allows forward references. Push as many Opaque types as
304 // needed to get up to ID.
305 while (TypeList.size() <= ID)
306 TypeList.push_back(OpaqueType::get());
307 return TypeList.back().get();
308}
309
Chris Lattner48c85b82007-05-04 03:30:17 +0000310//===----------------------------------------------------------------------===//
311// Functions for parsing blocks from the bitcode file
312//===----------------------------------------------------------------------===//
313
314bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000315 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000316 return Error("Malformed block record");
317
318 if (!ParamAttrs.empty())
319 return Error("Multiple PARAMATTR blocks found!");
320
321 SmallVector<uint64_t, 64> Record;
322
Chris Lattner58d74912008-03-12 17:45:29 +0000323 SmallVector<ParamAttrsWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000324
325 // Read all the records.
326 while (1) {
327 unsigned Code = Stream.ReadCode();
328 if (Code == bitc::END_BLOCK) {
329 if (Stream.ReadBlockEnd())
330 return Error("Error at end of PARAMATTR block");
331 return false;
332 }
333
334 if (Code == bitc::ENTER_SUBBLOCK) {
335 // No known subblocks, always skip them.
336 Stream.ReadSubBlockID();
337 if (Stream.SkipBlock())
338 return Error("Malformed block record");
339 continue;
340 }
341
342 if (Code == bitc::DEFINE_ABBREV) {
343 Stream.ReadAbbrevRecord();
344 continue;
345 }
346
347 // Read a record.
348 Record.clear();
349 switch (Stream.ReadRecord(Code, Record)) {
350 default: // Default behavior: ignore.
351 break;
352 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
353 if (Record.size() & 1)
354 return Error("Invalid ENTRY record");
355
Chris Lattner48c85b82007-05-04 03:30:17 +0000356 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Duncan Sands5e41f652007-11-20 14:09:29 +0000357 if (Record[i+1] != ParamAttr::None)
358 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
Chris Lattner48c85b82007-05-04 03:30:17 +0000359 }
Chris Lattner461edd92008-03-12 02:25:52 +0000360
Chris Lattner58d74912008-03-12 17:45:29 +0000361 ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000362 Attrs.clear();
363 break;
364 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000365 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000366 }
367}
368
369
Chris Lattner86697142007-05-01 05:01:34 +0000370bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000371 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000372 return Error("Malformed block record");
373
374 if (!TypeList.empty())
375 return Error("Multiple TYPE_BLOCKs found!");
376
377 SmallVector<uint64_t, 64> Record;
378 unsigned NumRecords = 0;
379
380 // Read all the records for this type table.
381 while (1) {
382 unsigned Code = Stream.ReadCode();
383 if (Code == bitc::END_BLOCK) {
384 if (NumRecords != TypeList.size())
385 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000386 if (Stream.ReadBlockEnd())
387 return Error("Error at end of type table block");
388 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000389 }
390
391 if (Code == bitc::ENTER_SUBBLOCK) {
392 // No known subblocks, always skip them.
393 Stream.ReadSubBlockID();
394 if (Stream.SkipBlock())
395 return Error("Malformed block record");
396 continue;
397 }
398
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000399 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000400 Stream.ReadAbbrevRecord();
401 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000402 }
403
404 // Read a record.
405 Record.clear();
406 const Type *ResultTy = 0;
407 switch (Stream.ReadRecord(Code, Record)) {
408 default: // Default behavior: unknown type.
409 ResultTy = 0;
410 break;
411 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
412 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
413 // type list. This allows us to reserve space.
414 if (Record.size() < 1)
415 return Error("Invalid TYPE_CODE_NUMENTRY record");
416 TypeList.reserve(Record[0]);
417 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000418 case bitc::TYPE_CODE_VOID: // VOID
419 ResultTy = Type::VoidTy;
420 break;
421 case bitc::TYPE_CODE_FLOAT: // FLOAT
422 ResultTy = Type::FloatTy;
423 break;
424 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
425 ResultTy = Type::DoubleTy;
426 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000427 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
428 ResultTy = Type::X86_FP80Ty;
429 break;
430 case bitc::TYPE_CODE_FP128: // FP128
431 ResultTy = Type::FP128Ty;
432 break;
433 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
434 ResultTy = Type::PPC_FP128Ty;
435 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000436 case bitc::TYPE_CODE_LABEL: // LABEL
437 ResultTy = Type::LabelTy;
438 break;
439 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
440 ResultTy = 0;
441 break;
442 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
443 if (Record.size() < 1)
444 return Error("Invalid Integer type record");
445
446 ResultTy = IntegerType::get(Record[0]);
447 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000448 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
449 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000450 if (Record.size() < 1)
451 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000452 unsigned AddressSpace = 0;
453 if (Record.size() == 2)
454 AddressSpace = Record[1];
455 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000456 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000457 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000458 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000459 // FIXME: attrid is dead, remove it in LLVM 3.0
460 // FUNCTION: [vararg, attrid, retty, paramty x N]
461 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000462 return Error("Invalid FUNCTION type record");
463 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000464 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000465 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000466
Chris Lattnera1afde72007-11-27 17:48:06 +0000467 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000468 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000469 break;
470 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000471 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000472 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000473 return Error("Invalid STRUCT type record");
474 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000475 for (unsigned i = 1, e = Record.size(); i != e; ++i)
476 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000477 ResultTy = StructType::get(EltTys, Record[0]);
478 break;
479 }
480 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
481 if (Record.size() < 2)
482 return Error("Invalid ARRAY type record");
483 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
484 break;
485 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
486 if (Record.size() < 2)
487 return Error("Invalid VECTOR type record");
488 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
489 break;
490 }
491
492 if (NumRecords == TypeList.size()) {
493 // If this is a new type slot, just append it.
494 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
495 ++NumRecords;
496 } else if (ResultTy == 0) {
497 // Otherwise, this was forward referenced, so an opaque type was created,
498 // but the result type is actually just an opaque. Leave the one we
499 // created previously.
500 ++NumRecords;
501 } else {
502 // Otherwise, this was forward referenced, so an opaque type was created.
503 // Resolve the opaque type to the real type now.
504 assert(NumRecords < TypeList.size() && "Typelist imbalance");
505 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
506
507 // Don't directly push the new type on the Tab. Instead we want to replace
508 // the opaque type we previously inserted with the new concrete value. The
509 // refinement from the abstract (opaque) type to the new type causes all
510 // uses of the abstract type to use the concrete type (NewTy). This will
511 // also cause the opaque type to be deleted.
512 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
513
514 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000515 // value table... or with a preexisting type that was already in the
516 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000517 assert(TypeList[NumRecords-1].get() != OldTy &&
518 "refineAbstractType didn't work!");
519 }
520 }
521}
522
523
Chris Lattner86697142007-05-01 05:01:34 +0000524bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000525 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000526 return Error("Malformed block record");
527
528 SmallVector<uint64_t, 64> Record;
529
530 // Read all the records for this type table.
531 std::string TypeName;
532 while (1) {
533 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000534 if (Code == bitc::END_BLOCK) {
535 if (Stream.ReadBlockEnd())
536 return Error("Error at end of type symbol table block");
537 return false;
538 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000539
540 if (Code == bitc::ENTER_SUBBLOCK) {
541 // No known subblocks, always skip them.
542 Stream.ReadSubBlockID();
543 if (Stream.SkipBlock())
544 return Error("Malformed block record");
545 continue;
546 }
547
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000548 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000549 Stream.ReadAbbrevRecord();
550 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000551 }
552
553 // Read a record.
554 Record.clear();
555 switch (Stream.ReadRecord(Code, Record)) {
556 default: // Default behavior: unknown type.
557 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000558 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000559 if (ConvertToString(Record, 1, TypeName))
560 return Error("Invalid TST_ENTRY record");
561 unsigned TypeID = Record[0];
562 if (TypeID >= TypeList.size())
563 return Error("Invalid Type ID in TST_ENTRY record");
564
565 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
566 TypeName.clear();
567 break;
568 }
569 }
570}
571
Chris Lattner86697142007-05-01 05:01:34 +0000572bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000573 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000574 return Error("Malformed block record");
575
576 SmallVector<uint64_t, 64> Record;
577
578 // Read all the records for this value table.
579 SmallString<128> ValueName;
580 while (1) {
581 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000582 if (Code == bitc::END_BLOCK) {
583 if (Stream.ReadBlockEnd())
584 return Error("Error at end of value symbol table block");
585 return false;
586 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000587 if (Code == bitc::ENTER_SUBBLOCK) {
588 // No known subblocks, always skip them.
589 Stream.ReadSubBlockID();
590 if (Stream.SkipBlock())
591 return Error("Malformed block record");
592 continue;
593 }
594
595 if (Code == bitc::DEFINE_ABBREV) {
596 Stream.ReadAbbrevRecord();
597 continue;
598 }
599
600 // Read a record.
601 Record.clear();
602 switch (Stream.ReadRecord(Code, Record)) {
603 default: // Default behavior: unknown type.
604 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000605 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000606 if (ConvertToString(Record, 1, ValueName))
607 return Error("Invalid TST_ENTRY record");
608 unsigned ValueID = Record[0];
609 if (ValueID >= ValueList.size())
610 return Error("Invalid Value ID in VST_ENTRY record");
611 Value *V = ValueList[ValueID];
612
613 V->setName(&ValueName[0], ValueName.size());
614 ValueName.clear();
615 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000616 }
617 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000618 if (ConvertToString(Record, 1, ValueName))
619 return Error("Invalid VST_BBENTRY record");
620 BasicBlock *BB = getBasicBlock(Record[0]);
621 if (BB == 0)
622 return Error("Invalid BB ID in VST_BBENTRY record");
623
624 BB->setName(&ValueName[0], ValueName.size());
625 ValueName.clear();
626 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000627 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000628 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000629 }
630}
631
Chris Lattner0eef0802007-04-24 04:04:35 +0000632/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
633/// the LSB for dense VBR encoding.
634static uint64_t DecodeSignRotatedValue(uint64_t V) {
635 if ((V & 1) == 0)
636 return V >> 1;
637 if (V != 1)
638 return -(V >> 1);
639 // There is no such thing as -0 with integers. "-0" really means MININT.
640 return 1ULL << 63;
641}
642
Chris Lattner07d98b42007-04-26 02:46:40 +0000643/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
644/// values and aliases that we can.
645bool BitcodeReader::ResolveGlobalAndAliasInits() {
646 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
647 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
648
649 GlobalInitWorklist.swap(GlobalInits);
650 AliasInitWorklist.swap(AliasInits);
651
652 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000653 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000654 if (ValID >= ValueList.size()) {
655 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000656 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000657 } else {
658 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
659 GlobalInitWorklist.back().first->setInitializer(C);
660 else
661 return Error("Global variable initializer is not a constant!");
662 }
663 GlobalInitWorklist.pop_back();
664 }
665
666 while (!AliasInitWorklist.empty()) {
667 unsigned ValID = AliasInitWorklist.back().second;
668 if (ValID >= ValueList.size()) {
669 AliasInits.push_back(AliasInitWorklist.back());
670 } else {
671 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000672 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000673 else
674 return Error("Alias initializer is not a constant!");
675 }
676 AliasInitWorklist.pop_back();
677 }
678 return false;
679}
680
681
Chris Lattner86697142007-05-01 05:01:34 +0000682bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000683 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000684 return Error("Malformed block record");
685
686 SmallVector<uint64_t, 64> Record;
687
688 // Read all the records for this value table.
689 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000690 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000691 while (1) {
692 unsigned Code = Stream.ReadCode();
Chris Lattnerf4a97da2008-08-21 00:11:50 +0000693 if (Code == bitc::END_BLOCK)
694 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000695
696 if (Code == bitc::ENTER_SUBBLOCK) {
697 // No known subblocks, always skip them.
698 Stream.ReadSubBlockID();
699 if (Stream.SkipBlock())
700 return Error("Malformed block record");
701 continue;
702 }
703
704 if (Code == bitc::DEFINE_ABBREV) {
705 Stream.ReadAbbrevRecord();
706 continue;
707 }
708
709 // Read a record.
710 Record.clear();
711 Value *V = 0;
712 switch (Stream.ReadRecord(Code, Record)) {
713 default: // Default behavior: unknown constant
714 case bitc::CST_CODE_UNDEF: // UNDEF
715 V = UndefValue::get(CurTy);
716 break;
717 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
718 if (Record.empty())
719 return Error("Malformed CST_SETTYPE record");
720 if (Record[0] >= TypeList.size())
721 return Error("Invalid Type ID in CST_SETTYPE record");
722 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000723 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000724 case bitc::CST_CODE_NULL: // NULL
725 V = Constant::getNullValue(CurTy);
726 break;
727 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000728 if (!isa<IntegerType>(CurTy) || Record.empty())
729 return Error("Invalid CST_INTEGER record");
730 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
731 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000732 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
733 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000734 return Error("Invalid WIDE_INTEGER record");
735
Chris Lattner15e6d172007-05-04 19:11:41 +0000736 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000737 SmallVector<uint64_t, 8> Words;
738 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000739 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000740 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000741 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000742 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000743 break;
744 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000745 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000746 if (Record.empty())
747 return Error("Invalid FLOAT record");
748 if (CurTy == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000749 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000750 else if (CurTy == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000751 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000752 else if (CurTy == Type::X86_FP80Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000753 V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000754 else if (CurTy == Type::FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000755 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000756 else if (CurTy == Type::PPC_FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000757 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000758 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000759 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000760 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000761 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000762
Chris Lattner15e6d172007-05-04 19:11:41 +0000763 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
764 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000765 return Error("Invalid CST_AGGREGATE record");
766
Chris Lattner15e6d172007-05-04 19:11:41 +0000767 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000768 std::vector<Constant*> Elts;
769
770 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
771 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000772 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000773 STy->getElementType(i)));
774 V = ConstantStruct::get(STy, Elts);
775 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
776 const Type *EltTy = ATy->getElementType();
777 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000778 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000779 V = ConstantArray::get(ATy, Elts);
780 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
781 const Type *EltTy = VTy->getElementType();
782 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000783 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000784 V = ConstantVector::get(Elts);
785 } else {
786 V = UndefValue::get(CurTy);
787 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000788 break;
789 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000790 case bitc::CST_CODE_STRING: { // STRING: [values]
791 if (Record.empty())
792 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000793
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000794 const ArrayType *ATy = cast<ArrayType>(CurTy);
795 const Type *EltTy = ATy->getElementType();
796
797 unsigned Size = Record.size();
798 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000799 for (unsigned i = 0; i != Size; ++i)
800 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
801 V = ConstantArray::get(ATy, Elts);
802 break;
803 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000804 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
805 if (Record.empty())
806 return Error("Invalid CST_AGGREGATE record");
807
808 const ArrayType *ATy = cast<ArrayType>(CurTy);
809 const Type *EltTy = ATy->getElementType();
810
811 unsigned Size = Record.size();
812 std::vector<Constant*> Elts;
813 for (unsigned i = 0; i != Size; ++i)
814 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
815 Elts.push_back(Constant::getNullValue(EltTy));
816 V = ConstantArray::get(ATy, Elts);
817 break;
818 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000819 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
820 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
821 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000822 if (Opc < 0) {
823 V = UndefValue::get(CurTy); // Unknown binop.
824 } else {
825 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
826 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
827 V = ConstantExpr::get(Opc, LHS, RHS);
828 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000829 break;
830 }
831 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
832 if (Record.size() < 3) return Error("Invalid CE_CAST record");
833 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000834 if (Opc < 0) {
835 V = UndefValue::get(CurTy); // Unknown cast.
836 } else {
837 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000838 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000839 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
840 V = ConstantExpr::getCast(Opc, Op, CurTy);
841 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000842 break;
843 }
844 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000845 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000846 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000847 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000848 const Type *ElTy = getTypeByID(Record[i]);
849 if (!ElTy) return Error("Invalid CE_GEP record");
850 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
851 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000852 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
853 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000854 }
855 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
856 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
857 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
858 Type::Int1Ty),
859 ValueList.getConstantFwdRef(Record[1],CurTy),
860 ValueList.getConstantFwdRef(Record[2],CurTy));
861 break;
862 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
863 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
864 const VectorType *OpTy =
865 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
866 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
867 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
868 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
869 OpTy->getElementType());
870 V = ConstantExpr::getExtractElement(Op0, Op1);
871 break;
872 }
873 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
874 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
875 if (Record.size() < 3 || OpTy == 0)
876 return Error("Invalid CE_INSERTELT record");
877 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
878 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
879 OpTy->getElementType());
880 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
881 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
882 break;
883 }
884 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
885 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
886 if (Record.size() < 3 || OpTy == 0)
887 return Error("Invalid CE_INSERTELT record");
888 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
889 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
890 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
891 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
892 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
893 break;
894 }
895 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
896 if (Record.size() < 4) return Error("Invalid CE_CMP record");
897 const Type *OpTy = getTypeByID(Record[0]);
898 if (OpTy == 0) return Error("Invalid CE_CMP record");
899 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
900 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
901
902 if (OpTy->isFloatingPoint())
903 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanbaa64eb2008-05-12 20:33:52 +0000904 else if (!isa<VectorType>(OpTy))
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000905 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +0000906 else if (OpTy->isFPOrFPVector())
907 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
908 else
909 V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000910 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000911 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000912 case bitc::CST_CODE_INLINEASM: {
913 if (Record.size() < 2) return Error("Invalid INLINEASM record");
914 std::string AsmStr, ConstrStr;
915 bool HasSideEffects = Record[0];
916 unsigned AsmStrSize = Record[1];
917 if (2+AsmStrSize >= Record.size())
918 return Error("Invalid INLINEASM record");
919 unsigned ConstStrSize = Record[2+AsmStrSize];
920 if (3+AsmStrSize+ConstStrSize > Record.size())
921 return Error("Invalid INLINEASM record");
922
923 for (unsigned i = 0; i != AsmStrSize; ++i)
924 AsmStr += (char)Record[2+i];
925 for (unsigned i = 0; i != ConstStrSize; ++i)
926 ConstrStr += (char)Record[3+AsmStrSize+i];
927 const PointerType *PTy = cast<PointerType>(CurTy);
928 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
929 AsmStr, ConstrStr, HasSideEffects);
930 break;
931 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000932 }
933
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000934 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000935 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000936 }
Chris Lattnerf4a97da2008-08-21 00:11:50 +0000937
938 if (NextCstNo != ValueList.size())
939 return Error("Invalid constant reference!");
940
941 if (Stream.ReadBlockEnd())
942 return Error("Error at end of constants block");
943
944 // Once all the constants have been read, go through and resolve forward
945 // references.
946 ValueList.ResolveConstantForwardRefs();
947 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000948}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000949
Chris Lattner980e5aa2007-05-01 05:52:21 +0000950/// RememberAndSkipFunctionBody - When we see the block for a function body,
951/// remember where it is and then skip it. This lets us lazily deserialize the
952/// functions.
953bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000954 // Get the function we are talking about.
955 if (FunctionsWithBodies.empty())
956 return Error("Insufficient function protos");
957
958 Function *Fn = FunctionsWithBodies.back();
959 FunctionsWithBodies.pop_back();
960
961 // Save the current stream state.
962 uint64_t CurBit = Stream.GetCurrentBitNo();
963 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
964
965 // Set the functions linkage to GhostLinkage so we know it is lazily
966 // deserialized.
967 Fn->setLinkage(GlobalValue::GhostLinkage);
968
969 // Skip over the function block for now.
970 if (Stream.SkipBlock())
971 return Error("Malformed block record");
972 return false;
973}
974
Chris Lattner86697142007-05-01 05:01:34 +0000975bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000976 // Reject multiple MODULE_BLOCK's in a single bitstream.
977 if (TheModule)
978 return Error("Multiple MODULE_BLOCKs in same stream");
979
Chris Lattnere17b6582007-05-05 00:17:00 +0000980 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000981 return Error("Malformed block record");
982
983 // Otherwise, create the module.
984 TheModule = new Module(ModuleID);
985
986 SmallVector<uint64_t, 64> Record;
987 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000988 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000989
990 // Read all the records for this module.
991 while (!Stream.AtEndOfStream()) {
992 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000993 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000994 if (Stream.ReadBlockEnd())
995 return Error("Error at end of module block");
996
997 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000998 ResolveGlobalAndAliasInits();
999 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001000 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001001 if (!FunctionsWithBodies.empty())
1002 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001003
Chandler Carruth69940402007-08-04 01:51:18 +00001004 // Look for intrinsic functions which need to be upgraded at some point
1005 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1006 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001007 Function* NewFn;
1008 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001009 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1010 }
1011
Chris Lattner980e5aa2007-05-01 05:52:21 +00001012 // Force deallocation of memory for these vectors to favor the client that
1013 // want lazy deserialization.
1014 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1015 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1016 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001017 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001018 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001019
1020 if (Code == bitc::ENTER_SUBBLOCK) {
1021 switch (Stream.ReadSubBlockID()) {
1022 default: // Skip unknown content.
1023 if (Stream.SkipBlock())
1024 return Error("Malformed block record");
1025 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001026 case bitc::BLOCKINFO_BLOCK_ID:
1027 if (Stream.ReadBlockInfoBlock())
1028 return Error("Malformed BlockInfoBlock");
1029 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001030 case bitc::PARAMATTR_BLOCK_ID:
1031 if (ParseParamAttrBlock())
1032 return true;
1033 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001034 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001035 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001036 return true;
1037 break;
1038 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001039 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001040 return true;
1041 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001042 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001043 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001044 return true;
1045 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001046 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001047 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001048 return true;
1049 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001050 case bitc::FUNCTION_BLOCK_ID:
1051 // If this is the first function body we've seen, reverse the
1052 // FunctionsWithBodies list.
1053 if (!HasReversedFunctionsWithBodies) {
1054 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1055 HasReversedFunctionsWithBodies = true;
1056 }
1057
Chris Lattner980e5aa2007-05-01 05:52:21 +00001058 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001059 return true;
1060 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001061 }
1062 continue;
1063 }
1064
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001065 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001066 Stream.ReadAbbrevRecord();
1067 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001068 }
1069
1070 // Read a record.
1071 switch (Stream.ReadRecord(Code, Record)) {
1072 default: break; // Default behavior, ignore unknown content.
1073 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1074 if (Record.size() < 1)
1075 return Error("Malformed MODULE_CODE_VERSION");
1076 // Only version #0 is supported so far.
1077 if (Record[0] != 0)
1078 return Error("Unknown bitstream version!");
1079 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001080 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001081 std::string S;
1082 if (ConvertToString(Record, 0, S))
1083 return Error("Invalid MODULE_CODE_TRIPLE record");
1084 TheModule->setTargetTriple(S);
1085 break;
1086 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001087 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001088 std::string S;
1089 if (ConvertToString(Record, 0, S))
1090 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1091 TheModule->setDataLayout(S);
1092 break;
1093 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001094 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001095 std::string S;
1096 if (ConvertToString(Record, 0, S))
1097 return Error("Invalid MODULE_CODE_ASM record");
1098 TheModule->setModuleInlineAsm(S);
1099 break;
1100 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001101 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001102 std::string S;
1103 if (ConvertToString(Record, 0, S))
1104 return Error("Invalid MODULE_CODE_DEPLIB record");
1105 TheModule->addLibrary(S);
1106 break;
1107 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001108 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001109 std::string S;
1110 if (ConvertToString(Record, 0, S))
1111 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1112 SectionTable.push_back(S);
1113 break;
1114 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001115 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001116 std::string S;
1117 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001118 return Error("Invalid MODULE_CODE_GCNAME record");
1119 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001120 break;
1121 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001122 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001123 // linkage, alignment, section, visibility, threadlocal]
1124 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001125 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001126 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1127 const Type *Ty = getTypeByID(Record[0]);
1128 if (!isa<PointerType>(Ty))
1129 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001130 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001131 Ty = cast<PointerType>(Ty)->getElementType();
1132
1133 bool isConstant = Record[1];
1134 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1135 unsigned Alignment = (1 << Record[4]) >> 1;
1136 std::string Section;
1137 if (Record[5]) {
1138 if (Record[5]-1 >= SectionTable.size())
1139 return Error("Invalid section ID");
1140 Section = SectionTable[Record[5]-1];
1141 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001142 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001143 if (Record.size() > 6)
1144 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001145 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001146 if (Record.size() > 7)
1147 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001148
1149 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001150 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1151 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001152 NewGV->setAlignment(Alignment);
1153 if (!Section.empty())
1154 NewGV->setSection(Section);
1155 NewGV->setVisibility(Visibility);
1156 NewGV->setThreadLocal(isThreadLocal);
1157
Chris Lattner0b2482a2007-04-23 21:26:05 +00001158 ValueList.push_back(NewGV);
1159
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001160 // Remember which value to use for the global initializer.
1161 if (unsigned InitID = Record[2])
1162 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001163 break;
1164 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001165 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001166 // alignment, section, visibility, gc]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001167 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001168 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001169 return Error("Invalid MODULE_CODE_FUNCTION record");
1170 const Type *Ty = getTypeByID(Record[0]);
1171 if (!isa<PointerType>(Ty))
1172 return Error("Function not a pointer type!");
1173 const FunctionType *FTy =
1174 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1175 if (!FTy)
1176 return Error("Function not a pointer to function type!");
1177
Gabor Greif051a9502008-04-06 20:25:17 +00001178 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1179 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001180
1181 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001182 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001183 Func->setLinkage(GetDecodedLinkage(Record[3]));
Chris Lattner58d74912008-03-12 17:45:29 +00001184 Func->setParamAttrs(getParamAttrs(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001185
1186 Func->setAlignment((1 << Record[5]) >> 1);
1187 if (Record[6]) {
1188 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001189 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001190 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001191 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001192 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001193 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001194 if (Record[8]-1 > GCTable.size())
1195 return Error("Invalid GC ID");
1196 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001197 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001198
Chris Lattner0b2482a2007-04-23 21:26:05 +00001199 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001200
1201 // If this is a function with a body, remember the prototype we are
1202 // creating now, so that we can match up the body with them later.
1203 if (!isProto)
1204 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001205 break;
1206 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001207 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001208 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001209 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001210 if (Record.size() < 3)
1211 return Error("Invalid MODULE_ALIAS record");
1212 const Type *Ty = getTypeByID(Record[0]);
1213 if (!isa<PointerType>(Ty))
1214 return Error("Function not a pointer type!");
1215
1216 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1217 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001218 // Old bitcode files didn't have visibility field.
1219 if (Record.size() > 3)
1220 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001221 ValueList.push_back(NewGA);
1222 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1223 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001224 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001225 /// MODULE_CODE_PURGEVALS: [numvals]
1226 case bitc::MODULE_CODE_PURGEVALS:
1227 // Trim down the value list to the specified size.
1228 if (Record.size() < 1 || Record[0] > ValueList.size())
1229 return Error("Invalid MODULE_PURGEVALS record");
1230 ValueList.shrinkTo(Record[0]);
1231 break;
1232 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001233 Record.clear();
1234 }
1235
1236 return Error("Premature end of bitstream");
1237}
1238
Chris Lattner6fa6a322008-07-09 05:14:23 +00001239/// SkipWrapperHeader - Some systems wrap bc files with a special header for
1240/// padding or other reasons. The format of this header is:
1241///
1242/// struct bc_header {
1243/// uint32_t Magic; // 0x0B17C0DE
1244/// uint32_t Version; // Version, currently always 0.
1245/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1246/// uint32_t BitcodeSize; // Size of traditional bitcode file.
1247/// ... potentially other gunk ...
1248/// };
1249///
1250/// This function is called when we find a file with a matching magic number.
1251/// In this case, skip down to the subsection of the file that is actually a BC
1252/// file.
1253static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
1254 enum {
1255 KnownHeaderSize = 4*4, // Size of header we read.
1256 OffsetField = 2*4, // Offset in bytes to Offset field.
1257 SizeField = 3*4 // Offset in bytes to Size field.
1258 };
1259
1260
1261 // Must contain the header!
1262 if (BufEnd-BufPtr < KnownHeaderSize) return true;
1263
1264 unsigned Offset = ( BufPtr[OffsetField ] |
1265 (BufPtr[OffsetField+1] << 8) |
1266 (BufPtr[OffsetField+2] << 16) |
1267 (BufPtr[OffsetField+3] << 24));
1268 unsigned Size = ( BufPtr[SizeField ] |
1269 (BufPtr[SizeField +1] << 8) |
1270 (BufPtr[SizeField +2] << 16) |
1271 (BufPtr[SizeField +3] << 24));
1272
1273 // Verify that Offset+Size fits in the file.
1274 if (Offset+Size > unsigned(BufEnd-BufPtr))
1275 return true;
1276 BufPtr += Offset;
1277 BufEnd = BufPtr+Size;
1278 return false;
1279}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001280
Chris Lattnerc453f762007-04-29 07:54:31 +00001281bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001282 TheModule = 0;
1283
Chris Lattnerc453f762007-04-29 07:54:31 +00001284 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001285 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1286
Chris Lattnerc453f762007-04-29 07:54:31 +00001287 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001288 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1289
1290 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1291 // The magic number is 0x0B17C0DE stored in little endian.
1292 if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 &&
1293 BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
1294 if (SkipWrapperHeader(BufPtr, BufEnd))
1295 return Error("Invalid bitcode wrapper header");
1296
1297 Stream.init(BufPtr, BufEnd);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001298
1299 // Sniff for the signature.
1300 if (Stream.Read(8) != 'B' ||
1301 Stream.Read(8) != 'C' ||
1302 Stream.Read(4) != 0x0 ||
1303 Stream.Read(4) != 0xC ||
1304 Stream.Read(4) != 0xE ||
1305 Stream.Read(4) != 0xD)
1306 return Error("Invalid bitcode signature");
1307
1308 // We expect a number of well-defined blocks, though we don't necessarily
1309 // need to understand them all.
1310 while (!Stream.AtEndOfStream()) {
1311 unsigned Code = Stream.ReadCode();
1312
1313 if (Code != bitc::ENTER_SUBBLOCK)
1314 return Error("Invalid record at top-level");
1315
1316 unsigned BlockID = Stream.ReadSubBlockID();
1317
1318 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001319 switch (BlockID) {
1320 case bitc::BLOCKINFO_BLOCK_ID:
1321 if (Stream.ReadBlockInfoBlock())
1322 return Error("Malformed BlockInfoBlock");
1323 break;
1324 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001325 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001326 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001327 break;
1328 default:
1329 if (Stream.SkipBlock())
1330 return Error("Malformed block record");
1331 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001332 }
1333 }
1334
1335 return false;
1336}
Chris Lattnerc453f762007-04-29 07:54:31 +00001337
Chris Lattner48f84872007-05-01 04:59:48 +00001338
Chris Lattner980e5aa2007-05-01 05:52:21 +00001339/// ParseFunctionBody - Lazily parse the specified function body block.
1340bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001341 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001342 return Error("Malformed block record");
1343
1344 unsigned ModuleValueListSize = ValueList.size();
1345
1346 // Add all the function arguments to the value table.
1347 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1348 ValueList.push_back(I);
1349
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001350 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001351 BasicBlock *CurBB = 0;
1352 unsigned CurBBNo = 0;
1353
Chris Lattner980e5aa2007-05-01 05:52:21 +00001354 // Read all the records.
1355 SmallVector<uint64_t, 64> Record;
1356 while (1) {
1357 unsigned Code = Stream.ReadCode();
1358 if (Code == bitc::END_BLOCK) {
1359 if (Stream.ReadBlockEnd())
1360 return Error("Error at end of function block");
1361 break;
1362 }
1363
1364 if (Code == bitc::ENTER_SUBBLOCK) {
1365 switch (Stream.ReadSubBlockID()) {
1366 default: // Skip unknown content.
1367 if (Stream.SkipBlock())
1368 return Error("Malformed block record");
1369 break;
1370 case bitc::CONSTANTS_BLOCK_ID:
1371 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001372 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001373 break;
1374 case bitc::VALUE_SYMTAB_BLOCK_ID:
1375 if (ParseValueSymbolTable()) return true;
1376 break;
1377 }
1378 continue;
1379 }
1380
1381 if (Code == bitc::DEFINE_ABBREV) {
1382 Stream.ReadAbbrevRecord();
1383 continue;
1384 }
1385
1386 // Read a record.
1387 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001388 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001389 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001390 default: // Default behavior: reject
1391 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001392 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001393 if (Record.size() < 1 || Record[0] == 0)
1394 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001395 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001396 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001397 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001398 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001399 CurBB = FunctionBBs[0];
1400 continue;
1401
Chris Lattnerabfbf852007-05-06 00:21:25 +00001402 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1403 unsigned OpNum = 0;
1404 Value *LHS, *RHS;
1405 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1406 getValue(Record, OpNum, LHS->getType(), RHS) ||
1407 OpNum+1 != Record.size())
1408 return Error("Invalid BINOP record");
1409
1410 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1411 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001412 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001413 break;
1414 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001415 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1416 unsigned OpNum = 0;
1417 Value *Op;
1418 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1419 OpNum+2 != Record.size())
1420 return Error("Invalid CAST record");
1421
1422 const Type *ResTy = getTypeByID(Record[OpNum]);
1423 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1424 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001425 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001426 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Chris Lattner231cbcb2007-05-02 04:27:25 +00001427 break;
1428 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001429 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001430 unsigned OpNum = 0;
1431 Value *BasePtr;
1432 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001433 return Error("Invalid GEP record");
1434
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001435 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001436 while (OpNum != Record.size()) {
1437 Value *Op;
1438 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001439 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001440 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001441 }
1442
Gabor Greif051a9502008-04-06 20:25:17 +00001443 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001444 break;
1445 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001446
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001447 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1448 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001449 unsigned OpNum = 0;
1450 Value *Agg;
1451 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1452 return Error("Invalid EXTRACTVAL record");
1453
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001454 SmallVector<unsigned, 4> EXTRACTVALIdx;
1455 for (unsigned RecSize = Record.size();
1456 OpNum != RecSize; ++OpNum) {
1457 uint64_t Index = Record[OpNum];
1458 if ((unsigned)Index != Index)
1459 return Error("Invalid EXTRACTVAL index");
1460 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001461 }
1462
1463 I = ExtractValueInst::Create(Agg,
1464 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1465 break;
1466 }
1467
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001468 case bitc::FUNC_CODE_INST_INSERTVAL: {
1469 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001470 unsigned OpNum = 0;
1471 Value *Agg;
1472 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1473 return Error("Invalid INSERTVAL record");
1474 Value *Val;
1475 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1476 return Error("Invalid INSERTVAL record");
1477
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001478 SmallVector<unsigned, 4> INSERTVALIdx;
1479 for (unsigned RecSize = Record.size();
1480 OpNum != RecSize; ++OpNum) {
1481 uint64_t Index = Record[OpNum];
1482 if ((unsigned)Index != Index)
1483 return Error("Invalid INSERTVAL index");
1484 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001485 }
1486
1487 I = InsertValueInst::Create(Agg, Val,
1488 INSERTVALIdx.begin(), INSERTVALIdx.end());
1489 break;
1490 }
1491
Chris Lattnerabfbf852007-05-06 00:21:25 +00001492 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1493 unsigned OpNum = 0;
1494 Value *TrueVal, *FalseVal, *Cond;
1495 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1496 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1497 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001498 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001499
Gabor Greif051a9502008-04-06 20:25:17 +00001500 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001501 break;
1502 }
1503
1504 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001505 unsigned OpNum = 0;
1506 Value *Vec, *Idx;
1507 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1508 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001509 return Error("Invalid EXTRACTELT record");
1510 I = new ExtractElementInst(Vec, Idx);
1511 break;
1512 }
1513
1514 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001515 unsigned OpNum = 0;
1516 Value *Vec, *Elt, *Idx;
1517 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1518 getValue(Record, OpNum,
1519 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1520 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001521 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001522 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001523 break;
1524 }
1525
Chris Lattnerabfbf852007-05-06 00:21:25 +00001526 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1527 unsigned OpNum = 0;
1528 Value *Vec1, *Vec2, *Mask;
1529 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1530 getValue(Record, OpNum, Vec1->getType(), Vec2))
1531 return Error("Invalid SHUFFLEVEC record");
1532
1533 const Type *MaskTy =
1534 VectorType::get(Type::Int32Ty,
1535 cast<VectorType>(Vec1->getType())->getNumElements());
1536
1537 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001538 return Error("Invalid SHUFFLEVEC record");
1539 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1540 break;
1541 }
1542
1543 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001544 unsigned OpNum = 0;
1545 Value *LHS, *RHS;
1546 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1547 getValue(Record, OpNum, LHS->getType(), RHS) ||
1548 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001549 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001550
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001551 if (LHS->getType()->isFloatingPoint())
Nate Begemanac80ade2008-05-12 19:01:56 +00001552 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001553 else if (!isa<VectorType>(LHS->getType()))
1554 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanac80ade2008-05-12 19:01:56 +00001555 else if (LHS->getType()->isFPOrFPVector())
1556 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1557 else
1558 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001559 break;
1560 }
Devang Patel197be3d2008-02-22 02:49:49 +00001561 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1562 if (Record.size() != 2)
1563 return Error("Invalid GETRESULT record");
1564 unsigned OpNum = 0;
1565 Value *Op;
1566 getValueTypePair(Record, OpNum, NextValueNo, Op);
1567 unsigned Index = Record[1];
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001568 I = ExtractValueInst::Create(Op, Index);
Devang Patel197be3d2008-02-22 02:49:49 +00001569 break;
1570 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001571
Chris Lattner231cbcb2007-05-02 04:27:25 +00001572 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001573 {
1574 unsigned Size = Record.size();
1575 if (Size == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00001576 I = ReturnInst::Create();
Devang Pateld9d99ff2008-02-26 01:29:32 +00001577 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001578 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00001579
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001580 unsigned OpNum = 0;
1581 SmallVector<Value *,4> Vs;
1582 do {
1583 Value *Op = NULL;
1584 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1585 return Error("Invalid RET record");
1586 Vs.push_back(Op);
1587 } while(OpNum != Record.size());
1588
1589 const Type *ReturnType = F->getReturnType();
1590 if (Vs.size() > 1 ||
1591 (isa<StructType>(ReturnType) &&
1592 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1593 Value *RV = UndefValue::get(ReturnType);
1594 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1595 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1596 CurBB->getInstList().push_back(I);
1597 ValueList.AssignValue(I, NextValueNo++);
1598 RV = I;
1599 }
1600 I = ReturnInst::Create(RV);
Devang Pateld9d99ff2008-02-26 01:29:32 +00001601 break;
1602 }
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001603
1604 I = ReturnInst::Create(Vs[0]);
1605 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00001606 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001607 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001608 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001609 return Error("Invalid BR record");
1610 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1611 if (TrueDest == 0)
1612 return Error("Invalid BR record");
1613
1614 if (Record.size() == 1)
Gabor Greif051a9502008-04-06 20:25:17 +00001615 I = BranchInst::Create(TrueDest);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001616 else {
1617 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1618 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1619 if (FalseDest == 0 || Cond == 0)
1620 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001621 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001622 }
1623 break;
1624 }
1625 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1626 if (Record.size() < 3 || (Record.size() & 1) == 0)
1627 return Error("Invalid SWITCH record");
1628 const Type *OpTy = getTypeByID(Record[0]);
1629 Value *Cond = getFnValueByID(Record[1], OpTy);
1630 BasicBlock *Default = getBasicBlock(Record[2]);
1631 if (OpTy == 0 || Cond == 0 || Default == 0)
1632 return Error("Invalid SWITCH record");
1633 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001634 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001635 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1636 ConstantInt *CaseVal =
1637 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1638 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1639 if (CaseVal == 0 || DestBB == 0) {
1640 delete SI;
1641 return Error("Invalid SWITCH record!");
1642 }
1643 SI->addCase(CaseVal, DestBB);
1644 }
1645 I = SI;
1646 break;
1647 }
1648
Duncan Sandsdc024672007-11-27 13:23:08 +00001649 case bitc::FUNC_CODE_INST_INVOKE: {
1650 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001651 if (Record.size() < 4) return Error("Invalid INVOKE record");
Chris Lattner58d74912008-03-12 17:45:29 +00001652 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001653 unsigned CCInfo = Record[1];
1654 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1655 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001656
Chris Lattnera9bb7132007-05-08 05:38:01 +00001657 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001658 Value *Callee;
1659 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001660 return Error("Invalid INVOKE record");
1661
Chris Lattner7337ab92007-05-06 00:00:00 +00001662 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1663 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001664 dyn_cast<FunctionType>(CalleeTy->getElementType());
1665
1666 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001667 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1668 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001669 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001670
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001671 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001672 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1673 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1674 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001675 }
1676
Chris Lattner7337ab92007-05-06 00:00:00 +00001677 if (!FTy->isVarArg()) {
1678 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001679 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001680 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001681 // Read type/value pairs for varargs params.
1682 while (OpNum != Record.size()) {
1683 Value *Op;
1684 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1685 return Error("Invalid INVOKE record");
1686 Ops.push_back(Op);
1687 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001688 }
1689
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001690 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1691 Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001692 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Duncan Sandsdc024672007-11-27 13:23:08 +00001693 cast<InvokeInst>(I)->setParamAttrs(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001694 break;
1695 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001696 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1697 I = new UnwindInst();
1698 break;
1699 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1700 I = new UnreachableInst();
1701 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001702 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001703 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001704 return Error("Invalid PHI record");
1705 const Type *Ty = getTypeByID(Record[0]);
1706 if (!Ty) return Error("Invalid PHI record");
1707
Gabor Greif051a9502008-04-06 20:25:17 +00001708 PHINode *PN = PHINode::Create(Ty);
Chris Lattner86941612008-04-13 00:14:42 +00001709 PN->reserveOperandSpace((Record.size()-1)/2);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001710
Chris Lattner15e6d172007-05-04 19:11:41 +00001711 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1712 Value *V = getFnValueByID(Record[1+i], Ty);
1713 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001714 if (!V || !BB) return Error("Invalid PHI record");
1715 PN->addIncoming(V, BB);
1716 }
1717 I = PN;
1718 break;
1719 }
1720
1721 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1722 if (Record.size() < 3)
1723 return Error("Invalid MALLOC record");
1724 const PointerType *Ty =
1725 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1726 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1727 unsigned Align = Record[2];
1728 if (!Ty || !Size) return Error("Invalid MALLOC record");
1729 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1730 break;
1731 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001732 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1733 unsigned OpNum = 0;
1734 Value *Op;
1735 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1736 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001737 return Error("Invalid FREE record");
1738 I = new FreeInst(Op);
1739 break;
1740 }
1741 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1742 if (Record.size() < 3)
1743 return Error("Invalid ALLOCA record");
1744 const PointerType *Ty =
1745 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1746 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1747 unsigned Align = Record[2];
1748 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1749 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1750 break;
1751 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001752 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001753 unsigned OpNum = 0;
1754 Value *Op;
1755 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1756 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001757 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001758
1759 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001760 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001761 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001762 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1763 unsigned OpNum = 0;
1764 Value *Val, *Ptr;
1765 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1766 getValue(Record, OpNum,
1767 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1768 OpNum+2 != Record.size())
1769 return Error("Invalid STORE record");
1770
1771 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1772 break;
1773 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001774 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001775 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001776 unsigned OpNum = 0;
1777 Value *Val, *Ptr;
1778 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001779 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001780 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001781 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001782
1783 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001784 break;
1785 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001786 case bitc::FUNC_CODE_INST_CALL: {
1787 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1788 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001789 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001790
Chris Lattner58d74912008-03-12 17:45:29 +00001791 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001792 unsigned CCInfo = Record[1];
1793
1794 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001795 Value *Callee;
1796 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1797 return Error("Invalid CALL record");
1798
1799 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001800 const FunctionType *FTy = 0;
1801 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001802 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001803 return Error("Invalid CALL record");
1804
1805 SmallVector<Value*, 16> Args;
1806 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001807 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001808 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1809 Args.push_back(getBasicBlock(Record[OpNum]));
1810 else
1811 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001812 if (Args.back() == 0) return Error("Invalid CALL record");
1813 }
1814
Chris Lattner0579f7f2007-05-03 22:04:19 +00001815 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001816 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001817 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001818 return Error("Invalid CALL record");
1819 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001820 while (OpNum != Record.size()) {
1821 Value *Op;
1822 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1823 return Error("Invalid CALL record");
1824 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001825 }
1826 }
1827
Gabor Greif051a9502008-04-06 20:25:17 +00001828 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001829 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1830 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Duncan Sandsdc024672007-11-27 13:23:08 +00001831 cast<CallInst>(I)->setParamAttrs(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001832 break;
1833 }
1834 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1835 if (Record.size() < 3)
1836 return Error("Invalid VAARG record");
1837 const Type *OpTy = getTypeByID(Record[0]);
1838 Value *Op = getFnValueByID(Record[1], OpTy);
1839 const Type *ResTy = getTypeByID(Record[2]);
1840 if (!OpTy || !Op || !ResTy)
1841 return Error("Invalid VAARG record");
1842 I = new VAArgInst(Op, ResTy);
1843 break;
1844 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001845 }
1846
1847 // Add instruction to end of current BB. If there is no current BB, reject
1848 // this file.
1849 if (CurBB == 0) {
1850 delete I;
1851 return Error("Invalid instruction with no BB");
1852 }
1853 CurBB->getInstList().push_back(I);
1854
1855 // If this was a terminator instruction, move to the next block.
1856 if (isa<TerminatorInst>(I)) {
1857 ++CurBBNo;
1858 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1859 }
1860
1861 // Non-void values get registered in the value table for future use.
1862 if (I && I->getType() != Type::VoidTy)
1863 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001864 }
1865
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001866 // Check the function list for unresolved values.
1867 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1868 if (A->getParent() == 0) {
1869 // We found at least one unresolved value. Nuke them all to avoid leaks.
1870 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1871 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1872 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1873 delete A;
1874 }
1875 }
Chris Lattner35a04702007-05-04 03:50:29 +00001876 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001877 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001878 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001879
1880 // Trim the value list down to the size it was before we parsed this function.
1881 ValueList.shrinkTo(ModuleValueListSize);
1882 std::vector<BasicBlock*>().swap(FunctionBBs);
1883
Chris Lattner48f84872007-05-01 04:59:48 +00001884 return false;
1885}
1886
Chris Lattnerb348bb82007-05-18 04:02:46 +00001887//===----------------------------------------------------------------------===//
1888// ModuleProvider implementation
1889//===----------------------------------------------------------------------===//
1890
1891
1892bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1893 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001894 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001895
1896 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1897 DeferredFunctionInfo.find(F);
1898 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1899
1900 // Move the bit stream to the saved position of the deferred function body and
1901 // restore the real linkage type for the function.
1902 Stream.JumpToBit(DFII->second.first);
1903 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1904
1905 if (ParseFunctionBody(F)) {
1906 if (ErrInfo) *ErrInfo = ErrorString;
1907 return true;
1908 }
Chandler Carruth69940402007-08-04 01:51:18 +00001909
1910 // Upgrade any old intrinsic calls in the function.
1911 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1912 E = UpgradedIntrinsics.end(); I != E; ++I) {
1913 if (I->first != I->second) {
1914 for (Value::use_iterator UI = I->first->use_begin(),
1915 UE = I->first->use_end(); UI != UE; ) {
1916 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1917 UpgradeIntrinsicCall(CI, I->second);
1918 }
1919 }
1920 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001921
1922 return false;
1923}
1924
1925void BitcodeReader::dematerializeFunction(Function *F) {
1926 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001927 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001928 return;
1929
1930 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1931
1932 // Just forget the function body, we can remat it later.
1933 F->deleteBody();
1934 F->setLinkage(GlobalValue::GhostLinkage);
1935}
1936
1937
1938Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1939 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1940 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1941 ++I) {
1942 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001943 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001944 materializeFunction(F, ErrInfo))
1945 return 0;
1946 }
Chandler Carruth69940402007-08-04 01:51:18 +00001947
1948 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1949 // delete the old functions to clean up. We can't do this unless the entire
1950 // module is materialized because there could always be another function body
1951 // with calls to the old function.
1952 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1953 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1954 if (I->first != I->second) {
1955 for (Value::use_iterator UI = I->first->use_begin(),
1956 UE = I->first->use_end(); UI != UE; ) {
1957 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1958 UpgradeIntrinsicCall(CI, I->second);
1959 }
1960 ValueList.replaceUsesOfWith(I->first, I->second);
1961 I->first->eraseFromParent();
1962 }
1963 }
1964 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1965
Chris Lattnerb348bb82007-05-18 04:02:46 +00001966 return TheModule;
1967}
1968
1969
1970/// This method is provided by the parent ModuleProvde class and overriden
1971/// here. It simply releases the module from its provided and frees up our
1972/// state.
1973/// @brief Release our hold on the generated module
1974Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1975 // Since we're losing control of this Module, we must hand it back complete
1976 Module *M = ModuleProvider::releaseModule(ErrInfo);
1977 FreeState();
1978 return M;
1979}
1980
Chris Lattner48f84872007-05-01 04:59:48 +00001981
Chris Lattnerc453f762007-04-29 07:54:31 +00001982//===----------------------------------------------------------------------===//
1983// External interface
1984//===----------------------------------------------------------------------===//
1985
1986/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1987///
1988ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1989 std::string *ErrMsg) {
1990 BitcodeReader *R = new BitcodeReader(Buffer);
1991 if (R->ParseBitcode()) {
1992 if (ErrMsg)
1993 *ErrMsg = R->getErrorString();
1994
1995 // Don't let the BitcodeReader dtor delete 'Buffer'.
1996 R->releaseMemoryBuffer();
1997 delete R;
1998 return 0;
1999 }
2000 return R;
2001}
2002
2003/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2004/// If an error occurs, return null and fill in *ErrMsg if non-null.
2005Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
2006 BitcodeReader *R;
2007 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
2008 if (!R) return 0;
2009
Chris Lattnerb348bb82007-05-18 04:02:46 +00002010 // Read in the entire module.
2011 Module *M = R->materializeModule(ErrMsg);
2012
2013 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2014 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00002015 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002016
2017 // If there was no error, tell ModuleProvider not to delete it when its dtor
2018 // is run.
2019 if (M)
2020 M = R->releaseModule(ErrMsg);
2021
Chris Lattnerc453f762007-04-29 07:54:31 +00002022 delete R;
2023 return M;
2024}