blob: 6f91dda50128407751a0a88937b51c1fd7150d65 [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
Devang Patel19c87462008-09-26 22:53:05 +000035 std::vector<AttrListPtr>().swap(MAttributes);
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;
Duncan Sands667d4b82009-03-07 15:45:40 +000062 case 1: return GlobalValue::WeakAnyLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063 case 2: return GlobalValue::AppendingLinkage;
64 case 3: return GlobalValue::InternalLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000065 case 4: return GlobalValue::LinkOnceAnyLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000066 case 5: return GlobalValue::DLLImportLinkage;
67 case 6: return GlobalValue::DLLExportLinkage;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +000068 case 7: return GlobalValue::ExternalWeakLinkage;
Duncan Sands4dc2b392009-03-11 20:14:15 +000069 case 8: return GlobalValue::CommonLinkage;
Rafael Espindolabb46f522009-01-15 20:18:42 +000070 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000071 case 10: return GlobalValue::WeakODRLinkage;
72 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000073 }
74}
75
76static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
77 switch (Val) {
78 default: // Map unknown visibilities to default.
79 case 0: return GlobalValue::DefaultVisibility;
80 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000081 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000082 }
83}
84
Chris Lattnerf581c3b2007-04-24 07:07:11 +000085static int GetDecodedCastOpcode(unsigned Val) {
86 switch (Val) {
87 default: return -1;
88 case bitc::CAST_TRUNC : return Instruction::Trunc;
89 case bitc::CAST_ZEXT : return Instruction::ZExt;
90 case bitc::CAST_SEXT : return Instruction::SExt;
91 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
92 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
93 case bitc::CAST_UITOFP : return Instruction::UIToFP;
94 case bitc::CAST_SITOFP : return Instruction::SIToFP;
95 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
96 case bitc::CAST_FPEXT : return Instruction::FPExt;
97 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
98 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
99 case bitc::CAST_BITCAST : return Instruction::BitCast;
100 }
101}
102static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
103 switch (Val) {
104 default: return -1;
105 case bitc::BINOP_ADD: return Instruction::Add;
106 case bitc::BINOP_SUB: return Instruction::Sub;
107 case bitc::BINOP_MUL: return Instruction::Mul;
108 case bitc::BINOP_UDIV: return Instruction::UDiv;
109 case bitc::BINOP_SDIV:
110 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
111 case bitc::BINOP_UREM: return Instruction::URem;
112 case bitc::BINOP_SREM:
113 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
114 case bitc::BINOP_SHL: return Instruction::Shl;
115 case bitc::BINOP_LSHR: return Instruction::LShr;
116 case bitc::BINOP_ASHR: return Instruction::AShr;
117 case bitc::BINOP_AND: return Instruction::And;
118 case bitc::BINOP_OR: return Instruction::Or;
119 case bitc::BINOP_XOR: return Instruction::Xor;
120 }
121}
122
Gabor Greifefe65362008-05-10 08:32:32 +0000123namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000124namespace {
125 /// @brief A class for maintaining the slot number definition
126 /// as a placeholder for the actual definition for forward constants defs.
127 class ConstantPlaceHolder : public ConstantExpr {
128 ConstantPlaceHolder(); // DO NOT IMPLEMENT
129 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000130 public:
131 // allocate space for exactly one operand
132 void *operator new(size_t s) {
133 return User::operator new(s, 1);
134 }
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000135 explicit ConstantPlaceHolder(const Type *Ty)
Gabor Greifefe65362008-05-10 08:32:32 +0000136 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
137 Op<0>() = UndefValue::get(Type::Int32Ty);
Chris Lattner522b7b12007-04-24 05:48:56 +0000138 }
Chris Lattnerea693df2008-08-21 02:34:16 +0000139
140 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
141 static inline bool classof(const ConstantPlaceHolder *) { return true; }
142 static bool classof(const Value *V) {
143 return isa<ConstantExpr>(V) &&
144 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
145 }
146
147
Gabor Greifefe65362008-05-10 08:32:32 +0000148 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000149 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000150 };
151}
152
Chris Lattner46e77402009-03-31 22:55:09 +0000153// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000154template <>
155struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
156};
Gabor Greifefe65362008-05-10 08:32:32 +0000157}
158
Chris Lattner46e77402009-03-31 22:55:09 +0000159
160void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
161 if (Idx == size()) {
162 push_back(V);
163 return;
164 }
165
166 if (Idx >= size())
167 resize(Idx+1);
168
169 WeakVH &OldV = ValuePtrs[Idx];
170 if (OldV == 0) {
171 OldV = V;
172 return;
173 }
174
175 // Handle constants and non-constants (e.g. instrs) differently for
176 // efficiency.
177 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
178 ResolveConstants.push_back(std::make_pair(PHC, Idx));
179 OldV = V;
180 } else {
181 // If there was a forward reference to this value, replace it.
182 Value *PrevVal = OldV;
183 OldV->replaceAllUsesWith(V);
184 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000185 }
186}
Chris Lattner46e77402009-03-31 22:55:09 +0000187
Gabor Greifefe65362008-05-10 08:32:32 +0000188
Chris Lattner522b7b12007-04-24 05:48:56 +0000189Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
190 const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000191 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000192 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000193
Chris Lattner46e77402009-03-31 22:55:09 +0000194 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000195 assert(Ty == V->getType() && "Type mismatch in constant table!");
196 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000197 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000198
199 // Create and return a placeholder, which will later be RAUW'd.
200 Constant *C = new ConstantPlaceHolder(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000201 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000202 return C;
203}
204
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000205Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000206 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000207 resize(Idx + 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000208
Chris Lattner46e77402009-03-31 22:55:09 +0000209 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000210 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
211 return V;
212 }
213
Chris Lattner01ff65f2007-05-02 05:16:49 +0000214 // No type specified, must be invalid reference.
215 if (Ty == 0) return 0;
216
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000217 // Create and return a placeholder, which will later be RAUW'd.
218 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000219 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000220 return V;
221}
222
Chris Lattnerea693df2008-08-21 02:34:16 +0000223/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
224/// resolves any forward references. The idea behind this is that we sometimes
225/// get constants (such as large arrays) which reference *many* forward ref
226/// constants. Replacing each of these causes a lot of thrashing when
227/// building/reuniquing the constant. Instead of doing this, we look at all the
228/// uses and rewrite all the place holders at once for any constant that uses
229/// a placeholder.
230void BitcodeReaderValueList::ResolveConstantForwardRefs() {
231 // Sort the values by-pointer so that they are efficient to look up with a
232 // binary search.
233 std::sort(ResolveConstants.begin(), ResolveConstants.end());
234
235 SmallVector<Constant*, 64> NewOps;
236
237 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000238 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000239 Constant *Placeholder = ResolveConstants.back().first;
240 ResolveConstants.pop_back();
241
242 // Loop over all users of the placeholder, updating them to reference the
243 // new value. If they reference more than one placeholder, update them all
244 // at once.
245 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000246 Value::use_iterator UI = Placeholder->use_begin();
247
Chris Lattnerea693df2008-08-21 02:34:16 +0000248 // If the using object isn't uniqued, just update the operands. This
249 // handles instructions and initializers for global variables.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000250 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
251 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000252 continue;
253 }
254
255 // Otherwise, we have a constant that uses the placeholder. Replace that
256 // constant with a new constant that has *all* placeholder uses updated.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000257 Constant *UserC = cast<Constant>(*UI);
Chris Lattnerea693df2008-08-21 02:34:16 +0000258 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
259 I != E; ++I) {
260 Value *NewOp;
261 if (!isa<ConstantPlaceHolder>(*I)) {
262 // Not a placeholder reference.
263 NewOp = *I;
264 } else if (*I == Placeholder) {
265 // Common case is that it just references this one placeholder.
266 NewOp = RealVal;
267 } else {
268 // Otherwise, look up the placeholder in ResolveConstants.
269 ResolveConstantsTy::iterator It =
270 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
271 std::pair<Constant*, unsigned>(cast<Constant>(*I),
272 0));
273 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000274 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000275 }
276
277 NewOps.push_back(cast<Constant>(NewOp));
278 }
279
280 // Make the new constant.
281 Constant *NewC;
282 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
283 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
284 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
285 NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
286 UserCS->getType()->isPacked());
287 } else if (isa<ConstantVector>(UserC)) {
288 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +0000289 } else if (isa<ConstantExpr>(UserC)) {
Chris Lattnerea693df2008-08-21 02:34:16 +0000290 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
291 NewOps.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +0000292 } else {
293 assert(isa<MDNode>(UserC) && "Must be a metadata node.");
294 NewC = MDNode::get(&NewOps[0], NewOps.size());
Chris Lattnerea693df2008-08-21 02:34:16 +0000295 }
296
297 UserC->replaceAllUsesWith(NewC);
298 UserC->destroyConstant();
299 NewOps.clear();
300 }
301
302 delete Placeholder;
303 }
304}
305
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000306
307const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
308 // If the TypeID is in range, return it.
309 if (ID < TypeList.size())
310 return TypeList[ID].get();
311 if (!isTypeTable) return 0;
312
313 // The type table allows forward references. Push as many Opaque types as
314 // needed to get up to ID.
315 while (TypeList.size() <= ID)
316 TypeList.push_back(OpaqueType::get());
317 return TypeList.back().get();
318}
319
Chris Lattner48c85b82007-05-04 03:30:17 +0000320//===----------------------------------------------------------------------===//
321// Functions for parsing blocks from the bitcode file
322//===----------------------------------------------------------------------===//
323
Devang Patel05988662008-09-25 21:00:45 +0000324bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000325 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000326 return Error("Malformed block record");
327
Devang Patel19c87462008-09-26 22:53:05 +0000328 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000329 return Error("Multiple PARAMATTR blocks found!");
330
331 SmallVector<uint64_t, 64> Record;
332
Devang Patel05988662008-09-25 21:00:45 +0000333 SmallVector<AttributeWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000334
335 // Read all the records.
336 while (1) {
337 unsigned Code = Stream.ReadCode();
338 if (Code == bitc::END_BLOCK) {
339 if (Stream.ReadBlockEnd())
340 return Error("Error at end of PARAMATTR block");
341 return false;
342 }
343
344 if (Code == bitc::ENTER_SUBBLOCK) {
345 // No known subblocks, always skip them.
346 Stream.ReadSubBlockID();
347 if (Stream.SkipBlock())
348 return Error("Malformed block record");
349 continue;
350 }
351
352 if (Code == bitc::DEFINE_ABBREV) {
353 Stream.ReadAbbrevRecord();
354 continue;
355 }
356
357 // Read a record.
358 Record.clear();
359 switch (Stream.ReadRecord(Code, Record)) {
360 default: // Default behavior: ignore.
361 break;
362 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
363 if (Record.size() & 1)
364 return Error("Invalid ENTRY record");
365
Chris Lattner9a6cb152008-10-05 18:22:09 +0000366 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000367 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000368 // to index ~0. Index 0 is used for return value attributes but used to be
369 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000370 Attributes RetAttribute = Attribute::None;
371 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000372 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000373 // FIXME: remove in LLVM 3.0
374 // The alignment is stored as a 16-bit raw value from bits 31--16.
375 // We shift the bits above 31 down by 11 bits.
376
377 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
378 if (Alignment && !isPowerOf2_32(Alignment))
379 return Error("Alignment is not a power of two.");
380
381 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
382 if (Alignment)
383 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
384 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
385 Record[i+1] = ReconstitutedAttr;
386
Devang Patel19c87462008-09-26 22:53:05 +0000387 if (Record[i] == 0)
388 RetAttribute = Record[i+1];
389 else if (Record[i] == ~0U)
390 FnAttribute = Record[i+1];
391 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000392
393 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
394 Attribute::ReadOnly|Attribute::ReadNone);
395
396 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
397 (RetAttribute & OldRetAttrs) != 0) {
398 if (FnAttribute == Attribute::None) { // add a slot so they get added.
399 Record.push_back(~0U);
400 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000401 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000402
403 FnAttribute |= RetAttribute & OldRetAttrs;
404 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000405 }
Chris Lattner461edd92008-03-12 02:25:52 +0000406
Devang Patel19c87462008-09-26 22:53:05 +0000407 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000408 if (Record[i] == 0) {
409 if (RetAttribute != Attribute::None)
410 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
411 } else if (Record[i] == ~0U) {
412 if (FnAttribute != Attribute::None)
413 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
414 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000415 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
416 }
Devang Patel19c87462008-09-26 22:53:05 +0000417
418 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000419 Attrs.clear();
420 break;
421 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000422 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000423 }
424}
425
426
Chris Lattner86697142007-05-01 05:01:34 +0000427bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000428 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000429 return Error("Malformed block record");
430
431 if (!TypeList.empty())
432 return Error("Multiple TYPE_BLOCKs found!");
433
434 SmallVector<uint64_t, 64> Record;
435 unsigned NumRecords = 0;
436
437 // Read all the records for this type table.
438 while (1) {
439 unsigned Code = Stream.ReadCode();
440 if (Code == bitc::END_BLOCK) {
441 if (NumRecords != TypeList.size())
442 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000443 if (Stream.ReadBlockEnd())
444 return Error("Error at end of type table block");
445 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000446 }
447
448 if (Code == bitc::ENTER_SUBBLOCK) {
449 // No known subblocks, always skip them.
450 Stream.ReadSubBlockID();
451 if (Stream.SkipBlock())
452 return Error("Malformed block record");
453 continue;
454 }
455
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000456 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000457 Stream.ReadAbbrevRecord();
458 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000459 }
460
461 // Read a record.
462 Record.clear();
463 const Type *ResultTy = 0;
464 switch (Stream.ReadRecord(Code, Record)) {
465 default: // Default behavior: unknown type.
466 ResultTy = 0;
467 break;
468 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
469 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
470 // type list. This allows us to reserve space.
471 if (Record.size() < 1)
472 return Error("Invalid TYPE_CODE_NUMENTRY record");
473 TypeList.reserve(Record[0]);
474 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000475 case bitc::TYPE_CODE_VOID: // VOID
476 ResultTy = Type::VoidTy;
477 break;
478 case bitc::TYPE_CODE_FLOAT: // FLOAT
479 ResultTy = Type::FloatTy;
480 break;
481 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
482 ResultTy = Type::DoubleTy;
483 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000484 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
485 ResultTy = Type::X86_FP80Ty;
486 break;
487 case bitc::TYPE_CODE_FP128: // FP128
488 ResultTy = Type::FP128Ty;
489 break;
490 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
491 ResultTy = Type::PPC_FP128Ty;
492 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000493 case bitc::TYPE_CODE_LABEL: // LABEL
494 ResultTy = Type::LabelTy;
495 break;
496 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
497 ResultTy = 0;
498 break;
499 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
500 if (Record.size() < 1)
501 return Error("Invalid Integer type record");
502
503 ResultTy = IntegerType::get(Record[0]);
504 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000505 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
506 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000507 if (Record.size() < 1)
508 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000509 unsigned AddressSpace = 0;
510 if (Record.size() == 2)
511 AddressSpace = Record[1];
512 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000513 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000514 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000515 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000516 // FIXME: attrid is dead, remove it in LLVM 3.0
517 // FUNCTION: [vararg, attrid, retty, paramty x N]
518 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000519 return Error("Invalid FUNCTION type record");
520 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000521 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000522 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000523
Chris Lattnera1afde72007-11-27 17:48:06 +0000524 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000525 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000526 break;
527 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000528 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000529 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000530 return Error("Invalid STRUCT type record");
531 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000532 for (unsigned i = 1, e = Record.size(); i != e; ++i)
533 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000534 ResultTy = StructType::get(EltTys, Record[0]);
535 break;
536 }
537 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
538 if (Record.size() < 2)
539 return Error("Invalid ARRAY type record");
540 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
541 break;
542 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
543 if (Record.size() < 2)
544 return Error("Invalid VECTOR type record");
545 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
546 break;
547 }
548
549 if (NumRecords == TypeList.size()) {
550 // If this is a new type slot, just append it.
551 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
552 ++NumRecords;
553 } else if (ResultTy == 0) {
554 // Otherwise, this was forward referenced, so an opaque type was created,
555 // but the result type is actually just an opaque. Leave the one we
556 // created previously.
557 ++NumRecords;
558 } else {
559 // Otherwise, this was forward referenced, so an opaque type was created.
560 // Resolve the opaque type to the real type now.
561 assert(NumRecords < TypeList.size() && "Typelist imbalance");
562 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
563
564 // Don't directly push the new type on the Tab. Instead we want to replace
565 // the opaque type we previously inserted with the new concrete value. The
566 // refinement from the abstract (opaque) type to the new type causes all
567 // uses of the abstract type to use the concrete type (NewTy). This will
568 // also cause the opaque type to be deleted.
569 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
570
571 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000572 // value table... or with a preexisting type that was already in the
573 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000574 assert(TypeList[NumRecords-1].get() != OldTy &&
575 "refineAbstractType didn't work!");
576 }
577 }
578}
579
580
Chris Lattner86697142007-05-01 05:01:34 +0000581bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000582 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 return Error("Malformed block record");
584
585 SmallVector<uint64_t, 64> Record;
586
587 // Read all the records for this type table.
588 std::string TypeName;
589 while (1) {
590 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000591 if (Code == bitc::END_BLOCK) {
592 if (Stream.ReadBlockEnd())
593 return Error("Error at end of type symbol table block");
594 return false;
595 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000596
597 if (Code == bitc::ENTER_SUBBLOCK) {
598 // No known subblocks, always skip them.
599 Stream.ReadSubBlockID();
600 if (Stream.SkipBlock())
601 return Error("Malformed block record");
602 continue;
603 }
604
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000605 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000606 Stream.ReadAbbrevRecord();
607 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000608 }
609
610 // Read a record.
611 Record.clear();
612 switch (Stream.ReadRecord(Code, Record)) {
613 default: // Default behavior: unknown type.
614 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000615 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000616 if (ConvertToString(Record, 1, TypeName))
617 return Error("Invalid TST_ENTRY record");
618 unsigned TypeID = Record[0];
619 if (TypeID >= TypeList.size())
620 return Error("Invalid Type ID in TST_ENTRY record");
621
622 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
623 TypeName.clear();
624 break;
625 }
626 }
627}
628
Chris Lattner86697142007-05-01 05:01:34 +0000629bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000630 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000631 return Error("Malformed block record");
632
633 SmallVector<uint64_t, 64> Record;
634
635 // Read all the records for this value table.
636 SmallString<128> ValueName;
637 while (1) {
638 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000639 if (Code == bitc::END_BLOCK) {
640 if (Stream.ReadBlockEnd())
641 return Error("Error at end of value symbol table block");
642 return false;
643 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000644 if (Code == bitc::ENTER_SUBBLOCK) {
645 // No known subblocks, always skip them.
646 Stream.ReadSubBlockID();
647 if (Stream.SkipBlock())
648 return Error("Malformed block record");
649 continue;
650 }
651
652 if (Code == bitc::DEFINE_ABBREV) {
653 Stream.ReadAbbrevRecord();
654 continue;
655 }
656
657 // Read a record.
658 Record.clear();
659 switch (Stream.ReadRecord(Code, Record)) {
660 default: // Default behavior: unknown type.
661 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000662 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000663 if (ConvertToString(Record, 1, ValueName))
664 return Error("Invalid TST_ENTRY record");
665 unsigned ValueID = Record[0];
666 if (ValueID >= ValueList.size())
667 return Error("Invalid Value ID in VST_ENTRY record");
668 Value *V = ValueList[ValueID];
669
670 V->setName(&ValueName[0], ValueName.size());
671 ValueName.clear();
672 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000673 }
674 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000675 if (ConvertToString(Record, 1, ValueName))
676 return Error("Invalid VST_BBENTRY record");
677 BasicBlock *BB = getBasicBlock(Record[0]);
678 if (BB == 0)
679 return Error("Invalid BB ID in VST_BBENTRY record");
680
681 BB->setName(&ValueName[0], ValueName.size());
682 ValueName.clear();
683 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000684 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000685 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000686 }
687}
688
Chris Lattner0eef0802007-04-24 04:04:35 +0000689/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
690/// the LSB for dense VBR encoding.
691static uint64_t DecodeSignRotatedValue(uint64_t V) {
692 if ((V & 1) == 0)
693 return V >> 1;
694 if (V != 1)
695 return -(V >> 1);
696 // There is no such thing as -0 with integers. "-0" really means MININT.
697 return 1ULL << 63;
698}
699
Chris Lattner07d98b42007-04-26 02:46:40 +0000700/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
701/// values and aliases that we can.
702bool BitcodeReader::ResolveGlobalAndAliasInits() {
703 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
704 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
705
706 GlobalInitWorklist.swap(GlobalInits);
707 AliasInitWorklist.swap(AliasInits);
708
709 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000710 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000711 if (ValID >= ValueList.size()) {
712 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000713 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000714 } else {
715 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
716 GlobalInitWorklist.back().first->setInitializer(C);
717 else
718 return Error("Global variable initializer is not a constant!");
719 }
720 GlobalInitWorklist.pop_back();
721 }
722
723 while (!AliasInitWorklist.empty()) {
724 unsigned ValID = AliasInitWorklist.back().second;
725 if (ValID >= ValueList.size()) {
726 AliasInits.push_back(AliasInitWorklist.back());
727 } else {
728 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000729 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000730 else
731 return Error("Alias initializer is not a constant!");
732 }
733 AliasInitWorklist.pop_back();
734 }
735 return false;
736}
737
738
Chris Lattner86697142007-05-01 05:01:34 +0000739bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000740 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000741 return Error("Malformed block record");
742
743 SmallVector<uint64_t, 64> Record;
744
745 // Read all the records for this value table.
746 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000747 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000748 while (1) {
749 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000750 if (Code == bitc::END_BLOCK)
751 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000752
753 if (Code == bitc::ENTER_SUBBLOCK) {
754 // No known subblocks, always skip them.
755 Stream.ReadSubBlockID();
756 if (Stream.SkipBlock())
757 return Error("Malformed block record");
758 continue;
759 }
760
761 if (Code == bitc::DEFINE_ABBREV) {
762 Stream.ReadAbbrevRecord();
763 continue;
764 }
765
766 // Read a record.
767 Record.clear();
768 Value *V = 0;
769 switch (Stream.ReadRecord(Code, Record)) {
770 default: // Default behavior: unknown constant
771 case bitc::CST_CODE_UNDEF: // UNDEF
772 V = UndefValue::get(CurTy);
773 break;
774 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
775 if (Record.empty())
776 return Error("Malformed CST_SETTYPE record");
777 if (Record[0] >= TypeList.size())
778 return Error("Invalid Type ID in CST_SETTYPE record");
779 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000780 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000781 case bitc::CST_CODE_NULL: // NULL
782 V = Constant::getNullValue(CurTy);
783 break;
784 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000785 if (!isa<IntegerType>(CurTy) || Record.empty())
786 return Error("Invalid CST_INTEGER record");
787 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
788 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000789 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
790 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000791 return Error("Invalid WIDE_INTEGER record");
792
Chris Lattner15e6d172007-05-04 19:11:41 +0000793 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000794 SmallVector<uint64_t, 8> Words;
795 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000796 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000797 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000798 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000799 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000800 break;
801 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000802 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000803 if (Record.empty())
804 return Error("Invalid FLOAT record");
805 if (CurTy == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000806 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000807 else if (CurTy == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000808 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000809 else if (CurTy == Type::X86_FP80Ty) {
810 // Bits are not stored the same way as a normal i80 APInt, compensate.
811 uint64_t Rearrange[2];
812 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
813 Rearrange[1] = Record[0] >> 48;
814 V = ConstantFP::get(APFloat(APInt(80, 2, Rearrange)));
815 } else if (CurTy == Type::FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000816 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000817 else if (CurTy == Type::PPC_FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000818 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000819 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000820 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000821 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000822 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000823
Chris Lattner15e6d172007-05-04 19:11:41 +0000824 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
825 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000826 return Error("Invalid CST_AGGREGATE record");
827
Chris Lattner15e6d172007-05-04 19:11:41 +0000828 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000829 std::vector<Constant*> Elts;
830
831 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
832 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000833 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000834 STy->getElementType(i)));
835 V = ConstantStruct::get(STy, Elts);
836 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
837 const Type *EltTy = ATy->getElementType();
838 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000839 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000840 V = ConstantArray::get(ATy, Elts);
841 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
842 const Type *EltTy = VTy->getElementType();
843 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000844 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000845 V = ConstantVector::get(Elts);
846 } else {
847 V = UndefValue::get(CurTy);
848 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000849 break;
850 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000851 case bitc::CST_CODE_STRING: { // STRING: [values]
852 if (Record.empty())
853 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000854
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000855 const ArrayType *ATy = cast<ArrayType>(CurTy);
856 const Type *EltTy = ATy->getElementType();
857
858 unsigned Size = Record.size();
859 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000860 for (unsigned i = 0; i != Size; ++i)
861 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
862 V = ConstantArray::get(ATy, Elts);
863 break;
864 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000865 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
866 if (Record.empty())
867 return Error("Invalid CST_AGGREGATE record");
868
869 const ArrayType *ATy = cast<ArrayType>(CurTy);
870 const Type *EltTy = ATy->getElementType();
871
872 unsigned Size = Record.size();
873 std::vector<Constant*> Elts;
874 for (unsigned i = 0; i != Size; ++i)
875 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
876 Elts.push_back(Constant::getNullValue(EltTy));
877 V = ConstantArray::get(ATy, Elts);
878 break;
879 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000880 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
881 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
882 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000883 if (Opc < 0) {
884 V = UndefValue::get(CurTy); // Unknown binop.
885 } else {
886 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
887 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
888 V = ConstantExpr::get(Opc, LHS, RHS);
889 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000890 break;
891 }
892 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
893 if (Record.size() < 3) return Error("Invalid CE_CAST record");
894 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000895 if (Opc < 0) {
896 V = UndefValue::get(CurTy); // Unknown cast.
897 } else {
898 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000899 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000900 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
901 V = ConstantExpr::getCast(Opc, Op, CurTy);
902 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000903 break;
904 }
905 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000906 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000907 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000908 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000909 const Type *ElTy = getTypeByID(Record[i]);
910 if (!ElTy) return Error("Invalid CE_GEP record");
911 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
912 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000913 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
914 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000915 }
916 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
917 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
918 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
919 Type::Int1Ty),
920 ValueList.getConstantFwdRef(Record[1],CurTy),
921 ValueList.getConstantFwdRef(Record[2],CurTy));
922 break;
923 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
924 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
925 const VectorType *OpTy =
926 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
927 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
928 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerba120aa2009-02-03 02:11:28 +0000929 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000930 V = ConstantExpr::getExtractElement(Op0, Op1);
931 break;
932 }
933 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
934 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
935 if (Record.size() < 3 || OpTy == 0)
936 return Error("Invalid CE_INSERTELT record");
937 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
938 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
939 OpTy->getElementType());
940 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
941 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
942 break;
943 }
944 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
945 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
946 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +0000947 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000948 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
949 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
950 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
951 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
952 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
953 break;
954 }
Nate Begeman0f123cf2009-02-12 21:28:33 +0000955 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
956 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
957 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
958 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
959 return Error("Invalid CE_SHUFVEC_EX record");
960 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
961 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
962 const Type *ShufTy=VectorType::get(Type::Int32Ty, RTy->getNumElements());
963 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
964 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
965 break;
966 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000967 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
968 if (Record.size() < 4) return Error("Invalid CE_CMP record");
969 const Type *OpTy = getTypeByID(Record[0]);
970 if (OpTy == 0) return Error("Invalid CE_CMP record");
971 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
972 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
973
974 if (OpTy->isFloatingPoint())
975 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanbaa64eb2008-05-12 20:33:52 +0000976 else if (!isa<VectorType>(OpTy))
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000977 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +0000978 else if (OpTy->isFPOrFPVector())
979 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
980 else
981 V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000982 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000983 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000984 case bitc::CST_CODE_INLINEASM: {
985 if (Record.size() < 2) return Error("Invalid INLINEASM record");
986 std::string AsmStr, ConstrStr;
987 bool HasSideEffects = Record[0];
988 unsigned AsmStrSize = Record[1];
989 if (2+AsmStrSize >= Record.size())
990 return Error("Invalid INLINEASM record");
991 unsigned ConstStrSize = Record[2+AsmStrSize];
992 if (3+AsmStrSize+ConstStrSize > Record.size())
993 return Error("Invalid INLINEASM record");
994
995 for (unsigned i = 0; i != AsmStrSize; ++i)
996 AsmStr += (char)Record[2+i];
997 for (unsigned i = 0; i != ConstStrSize; ++i)
998 ConstrStr += (char)Record[3+AsmStrSize+i];
999 const PointerType *PTy = cast<PointerType>(CurTy);
1000 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1001 AsmStr, ConstrStr, HasSideEffects);
1002 break;
1003 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001004 case bitc::CST_CODE_MDSTRING: {
1005 if (Record.size() < 2) return Error("Invalid MDSTRING record");
1006 unsigned MDStringLength = Record.size();
1007 SmallString<8> String;
1008 String.resize(MDStringLength);
1009 for (unsigned i = 0; i != MDStringLength; ++i)
1010 String[i] = Record[i];
1011 V = MDString::get(String.c_str(), String.c_str() + MDStringLength);
1012 break;
1013 }
1014 case bitc::CST_CODE_MDNODE: {
1015 if (Record.empty() || Record.size() % 2 == 1)
1016 return Error("Invalid CST_MDNODE record");
1017
1018 unsigned Size = Record.size();
1019 SmallVector<Constant*, 8> Elts;
1020 for (unsigned i = 0; i != Size; i += 2) {
1021 const Type *Ty = getTypeByID(Record[i], false);
1022 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], Ty));
1023 }
1024 V = MDNode::get(&Elts[0], Elts.size());
1025 break;
1026 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001027 }
1028
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001029 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001030 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001031 }
Chris Lattnerea693df2008-08-21 02:34:16 +00001032
1033 if (NextCstNo != ValueList.size())
1034 return Error("Invalid constant reference!");
1035
1036 if (Stream.ReadBlockEnd())
1037 return Error("Error at end of constants block");
1038
1039 // Once all the constants have been read, go through and resolve forward
1040 // references.
1041 ValueList.ResolveConstantForwardRefs();
1042 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001043}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001044
Chris Lattner980e5aa2007-05-01 05:52:21 +00001045/// RememberAndSkipFunctionBody - When we see the block for a function body,
1046/// remember where it is and then skip it. This lets us lazily deserialize the
1047/// functions.
1048bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001049 // Get the function we are talking about.
1050 if (FunctionsWithBodies.empty())
1051 return Error("Insufficient function protos");
1052
1053 Function *Fn = FunctionsWithBodies.back();
1054 FunctionsWithBodies.pop_back();
1055
1056 // Save the current stream state.
1057 uint64_t CurBit = Stream.GetCurrentBitNo();
1058 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1059
1060 // Set the functions linkage to GhostLinkage so we know it is lazily
1061 // deserialized.
1062 Fn->setLinkage(GlobalValue::GhostLinkage);
1063
1064 // Skip over the function block for now.
1065 if (Stream.SkipBlock())
1066 return Error("Malformed block record");
1067 return false;
1068}
1069
Chris Lattner86697142007-05-01 05:01:34 +00001070bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001071 // Reject multiple MODULE_BLOCK's in a single bitstream.
1072 if (TheModule)
1073 return Error("Multiple MODULE_BLOCKs in same stream");
1074
Chris Lattnere17b6582007-05-05 00:17:00 +00001075 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001076 return Error("Malformed block record");
1077
1078 // Otherwise, create the module.
1079 TheModule = new Module(ModuleID);
1080
1081 SmallVector<uint64_t, 64> Record;
1082 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001083 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001084
1085 // Read all the records for this module.
1086 while (!Stream.AtEndOfStream()) {
1087 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001088 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001089 if (Stream.ReadBlockEnd())
1090 return Error("Error at end of module block");
1091
1092 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001093 ResolveGlobalAndAliasInits();
1094 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001095 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001096 if (!FunctionsWithBodies.empty())
1097 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001098
Chandler Carruth69940402007-08-04 01:51:18 +00001099 // Look for intrinsic functions which need to be upgraded at some point
1100 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1101 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001102 Function* NewFn;
1103 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001104 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1105 }
1106
Chris Lattner980e5aa2007-05-01 05:52:21 +00001107 // Force deallocation of memory for these vectors to favor the client that
1108 // want lazy deserialization.
1109 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1110 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1111 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001112 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001113 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001114
1115 if (Code == bitc::ENTER_SUBBLOCK) {
1116 switch (Stream.ReadSubBlockID()) {
1117 default: // Skip unknown content.
1118 if (Stream.SkipBlock())
1119 return Error("Malformed block record");
1120 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001121 case bitc::BLOCKINFO_BLOCK_ID:
1122 if (Stream.ReadBlockInfoBlock())
1123 return Error("Malformed BlockInfoBlock");
1124 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001125 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001126 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001127 return true;
1128 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001129 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001130 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001131 return true;
1132 break;
1133 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001134 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001135 return true;
1136 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001137 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001138 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001139 return true;
1140 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001141 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001142 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001143 return true;
1144 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001145 case bitc::FUNCTION_BLOCK_ID:
1146 // If this is the first function body we've seen, reverse the
1147 // FunctionsWithBodies list.
1148 if (!HasReversedFunctionsWithBodies) {
1149 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1150 HasReversedFunctionsWithBodies = true;
1151 }
1152
Chris Lattner980e5aa2007-05-01 05:52:21 +00001153 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001154 return true;
1155 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001156 }
1157 continue;
1158 }
1159
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001160 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001161 Stream.ReadAbbrevRecord();
1162 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001163 }
1164
1165 // Read a record.
1166 switch (Stream.ReadRecord(Code, Record)) {
1167 default: break; // Default behavior, ignore unknown content.
1168 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1169 if (Record.size() < 1)
1170 return Error("Malformed MODULE_CODE_VERSION");
1171 // Only version #0 is supported so far.
1172 if (Record[0] != 0)
1173 return Error("Unknown bitstream version!");
1174 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001175 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001176 std::string S;
1177 if (ConvertToString(Record, 0, S))
1178 return Error("Invalid MODULE_CODE_TRIPLE record");
1179 TheModule->setTargetTriple(S);
1180 break;
1181 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001182 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001183 std::string S;
1184 if (ConvertToString(Record, 0, S))
1185 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1186 TheModule->setDataLayout(S);
1187 break;
1188 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001189 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001190 std::string S;
1191 if (ConvertToString(Record, 0, S))
1192 return Error("Invalid MODULE_CODE_ASM record");
1193 TheModule->setModuleInlineAsm(S);
1194 break;
1195 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001196 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001197 std::string S;
1198 if (ConvertToString(Record, 0, S))
1199 return Error("Invalid MODULE_CODE_DEPLIB record");
1200 TheModule->addLibrary(S);
1201 break;
1202 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001203 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001204 std::string S;
1205 if (ConvertToString(Record, 0, S))
1206 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1207 SectionTable.push_back(S);
1208 break;
1209 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001210 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001211 std::string S;
1212 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001213 return Error("Invalid MODULE_CODE_GCNAME record");
1214 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001215 break;
1216 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001217 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001218 // linkage, alignment, section, visibility, threadlocal]
1219 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001220 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001221 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1222 const Type *Ty = getTypeByID(Record[0]);
1223 if (!isa<PointerType>(Ty))
1224 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001225 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001226 Ty = cast<PointerType>(Ty)->getElementType();
1227
1228 bool isConstant = Record[1];
1229 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1230 unsigned Alignment = (1 << Record[4]) >> 1;
1231 std::string Section;
1232 if (Record[5]) {
1233 if (Record[5]-1 >= SectionTable.size())
1234 return Error("Invalid section ID");
1235 Section = SectionTable[Record[5]-1];
1236 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001237 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001238 if (Record.size() > 6)
1239 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001240 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001241 if (Record.size() > 7)
1242 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001243
1244 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001245 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1246 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001247 NewGV->setAlignment(Alignment);
1248 if (!Section.empty())
1249 NewGV->setSection(Section);
1250 NewGV->setVisibility(Visibility);
1251 NewGV->setThreadLocal(isThreadLocal);
1252
Chris Lattner0b2482a2007-04-23 21:26:05 +00001253 ValueList.push_back(NewGV);
1254
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001255 // Remember which value to use for the global initializer.
1256 if (unsigned InitID = Record[2])
1257 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001258 break;
1259 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001260 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001261 // alignment, section, visibility, gc]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001262 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001263 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001264 return Error("Invalid MODULE_CODE_FUNCTION record");
1265 const Type *Ty = getTypeByID(Record[0]);
1266 if (!isa<PointerType>(Ty))
1267 return Error("Function not a pointer type!");
1268 const FunctionType *FTy =
1269 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1270 if (!FTy)
1271 return Error("Function not a pointer to function type!");
1272
Gabor Greif051a9502008-04-06 20:25:17 +00001273 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1274 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001275
1276 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001277 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001278 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001279 Func->setAttributes(getAttributes(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001280
1281 Func->setAlignment((1 << Record[5]) >> 1);
1282 if (Record[6]) {
1283 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001284 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001285 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001286 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001287 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001288 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001289 if (Record[8]-1 > GCTable.size())
1290 return Error("Invalid GC ID");
1291 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001292 }
Chris Lattner0b2482a2007-04-23 21:26:05 +00001293 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001294
1295 // If this is a function with a body, remember the prototype we are
1296 // creating now, so that we can match up the body with them later.
1297 if (!isProto)
1298 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001299 break;
1300 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001301 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001302 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001303 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001304 if (Record.size() < 3)
1305 return Error("Invalid MODULE_ALIAS record");
1306 const Type *Ty = getTypeByID(Record[0]);
1307 if (!isa<PointerType>(Ty))
1308 return Error("Function not a pointer type!");
1309
1310 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1311 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001312 // Old bitcode files didn't have visibility field.
1313 if (Record.size() > 3)
1314 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001315 ValueList.push_back(NewGA);
1316 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1317 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001318 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001319 /// MODULE_CODE_PURGEVALS: [numvals]
1320 case bitc::MODULE_CODE_PURGEVALS:
1321 // Trim down the value list to the specified size.
1322 if (Record.size() < 1 || Record[0] > ValueList.size())
1323 return Error("Invalid MODULE_PURGEVALS record");
1324 ValueList.shrinkTo(Record[0]);
1325 break;
1326 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001327 Record.clear();
1328 }
1329
1330 return Error("Premature end of bitstream");
1331}
1332
Chris Lattnerc453f762007-04-29 07:54:31 +00001333bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001334 TheModule = 0;
1335
Chris Lattnerc453f762007-04-29 07:54:31 +00001336 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001337 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1338
Chris Lattnerc453f762007-04-29 07:54:31 +00001339 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001340 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1341
1342 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1343 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnere2a466b2009-04-06 20:54:32 +00001344 if (isBitcodeWrapper(BufPtr, BufEnd))
1345 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner6fa6a322008-07-09 05:14:23 +00001346 return Error("Invalid bitcode wrapper header");
1347
1348 Stream.init(BufPtr, BufEnd);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001349
1350 // Sniff for the signature.
1351 if (Stream.Read(8) != 'B' ||
1352 Stream.Read(8) != 'C' ||
1353 Stream.Read(4) != 0x0 ||
1354 Stream.Read(4) != 0xC ||
1355 Stream.Read(4) != 0xE ||
1356 Stream.Read(4) != 0xD)
1357 return Error("Invalid bitcode signature");
1358
1359 // We expect a number of well-defined blocks, though we don't necessarily
1360 // need to understand them all.
1361 while (!Stream.AtEndOfStream()) {
1362 unsigned Code = Stream.ReadCode();
1363
1364 if (Code != bitc::ENTER_SUBBLOCK)
1365 return Error("Invalid record at top-level");
1366
1367 unsigned BlockID = Stream.ReadSubBlockID();
1368
1369 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001370 switch (BlockID) {
1371 case bitc::BLOCKINFO_BLOCK_ID:
1372 if (Stream.ReadBlockInfoBlock())
1373 return Error("Malformed BlockInfoBlock");
1374 break;
1375 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001376 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001377 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001378 break;
1379 default:
1380 if (Stream.SkipBlock())
1381 return Error("Malformed block record");
1382 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001383 }
1384 }
1385
1386 return false;
1387}
Chris Lattnerc453f762007-04-29 07:54:31 +00001388
Chris Lattner48f84872007-05-01 04:59:48 +00001389
Chris Lattner980e5aa2007-05-01 05:52:21 +00001390/// ParseFunctionBody - Lazily parse the specified function body block.
1391bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001392 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001393 return Error("Malformed block record");
1394
1395 unsigned ModuleValueListSize = ValueList.size();
1396
1397 // Add all the function arguments to the value table.
1398 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1399 ValueList.push_back(I);
1400
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001401 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001402 BasicBlock *CurBB = 0;
1403 unsigned CurBBNo = 0;
1404
Chris Lattner980e5aa2007-05-01 05:52:21 +00001405 // Read all the records.
1406 SmallVector<uint64_t, 64> Record;
1407 while (1) {
1408 unsigned Code = Stream.ReadCode();
1409 if (Code == bitc::END_BLOCK) {
1410 if (Stream.ReadBlockEnd())
1411 return Error("Error at end of function block");
1412 break;
1413 }
1414
1415 if (Code == bitc::ENTER_SUBBLOCK) {
1416 switch (Stream.ReadSubBlockID()) {
1417 default: // Skip unknown content.
1418 if (Stream.SkipBlock())
1419 return Error("Malformed block record");
1420 break;
1421 case bitc::CONSTANTS_BLOCK_ID:
1422 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001423 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001424 break;
1425 case bitc::VALUE_SYMTAB_BLOCK_ID:
1426 if (ParseValueSymbolTable()) return true;
1427 break;
1428 }
1429 continue;
1430 }
1431
1432 if (Code == bitc::DEFINE_ABBREV) {
1433 Stream.ReadAbbrevRecord();
1434 continue;
1435 }
1436
1437 // Read a record.
1438 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001439 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001440 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001441 default: // Default behavior: reject
1442 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001443 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001444 if (Record.size() < 1 || Record[0] == 0)
1445 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001446 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001447 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001448 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001449 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001450 CurBB = FunctionBBs[0];
1451 continue;
1452
Chris Lattnerabfbf852007-05-06 00:21:25 +00001453 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1454 unsigned OpNum = 0;
1455 Value *LHS, *RHS;
1456 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1457 getValue(Record, OpNum, LHS->getType(), RHS) ||
1458 OpNum+1 != Record.size())
1459 return Error("Invalid BINOP record");
1460
1461 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1462 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001463 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001464 break;
1465 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001466 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1467 unsigned OpNum = 0;
1468 Value *Op;
1469 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1470 OpNum+2 != Record.size())
1471 return Error("Invalid CAST record");
1472
1473 const Type *ResTy = getTypeByID(Record[OpNum]);
1474 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1475 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001476 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001477 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Chris Lattner231cbcb2007-05-02 04:27:25 +00001478 break;
1479 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001480 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001481 unsigned OpNum = 0;
1482 Value *BasePtr;
1483 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001484 return Error("Invalid GEP record");
1485
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001486 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001487 while (OpNum != Record.size()) {
1488 Value *Op;
1489 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001490 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001491 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001492 }
1493
Gabor Greif051a9502008-04-06 20:25:17 +00001494 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001495 break;
1496 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001497
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001498 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1499 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001500 unsigned OpNum = 0;
1501 Value *Agg;
1502 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1503 return Error("Invalid EXTRACTVAL record");
1504
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001505 SmallVector<unsigned, 4> EXTRACTVALIdx;
1506 for (unsigned RecSize = Record.size();
1507 OpNum != RecSize; ++OpNum) {
1508 uint64_t Index = Record[OpNum];
1509 if ((unsigned)Index != Index)
1510 return Error("Invalid EXTRACTVAL index");
1511 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001512 }
1513
1514 I = ExtractValueInst::Create(Agg,
1515 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1516 break;
1517 }
1518
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001519 case bitc::FUNC_CODE_INST_INSERTVAL: {
1520 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001521 unsigned OpNum = 0;
1522 Value *Agg;
1523 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1524 return Error("Invalid INSERTVAL record");
1525 Value *Val;
1526 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1527 return Error("Invalid INSERTVAL record");
1528
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001529 SmallVector<unsigned, 4> INSERTVALIdx;
1530 for (unsigned RecSize = Record.size();
1531 OpNum != RecSize; ++OpNum) {
1532 uint64_t Index = Record[OpNum];
1533 if ((unsigned)Index != Index)
1534 return Error("Invalid INSERTVAL index");
1535 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001536 }
1537
1538 I = InsertValueInst::Create(Agg, Val,
1539 INSERTVALIdx.begin(), INSERTVALIdx.end());
1540 break;
1541 }
1542
Chris Lattnerabfbf852007-05-06 00:21:25 +00001543 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001544 // obsolete form of select
1545 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00001546 unsigned OpNum = 0;
1547 Value *TrueVal, *FalseVal, *Cond;
1548 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1549 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Dan Gohmanbe919402008-09-09 02:08:49 +00001550 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001551 return Error("Invalid SELECT record");
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001552
1553 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1554 break;
1555 }
1556
1557 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1558 // new form of select
1559 // handles select i1 or select [N x i1]
1560 unsigned OpNum = 0;
1561 Value *TrueVal, *FalseVal, *Cond;
1562 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1563 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1564 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1565 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00001566
1567 // select condition can be either i1 or [N x i1]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001568 if (const VectorType* vector_type =
1569 dyn_cast<const VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00001570 // expect <n x i1>
1571 if (vector_type->getElementType() != Type::Int1Ty)
1572 return Error("Invalid SELECT condition type");
1573 } else {
1574 // expect i1
1575 if (Cond->getType() != Type::Int1Ty)
1576 return Error("Invalid SELECT condition type");
1577 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001578
Gabor Greif051a9502008-04-06 20:25:17 +00001579 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001580 break;
1581 }
1582
1583 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001584 unsigned OpNum = 0;
1585 Value *Vec, *Idx;
1586 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1587 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001588 return Error("Invalid EXTRACTELT record");
1589 I = new ExtractElementInst(Vec, Idx);
1590 break;
1591 }
1592
1593 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001594 unsigned OpNum = 0;
1595 Value *Vec, *Elt, *Idx;
1596 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1597 getValue(Record, OpNum,
1598 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1599 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001600 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001601 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001602 break;
1603 }
1604
Chris Lattnerabfbf852007-05-06 00:21:25 +00001605 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1606 unsigned OpNum = 0;
1607 Value *Vec1, *Vec2, *Mask;
1608 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1609 getValue(Record, OpNum, Vec1->getType(), Vec2))
1610 return Error("Invalid SHUFFLEVEC record");
1611
Mon P Wangaeb06d22008-11-10 04:46:22 +00001612 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001613 return Error("Invalid SHUFFLEVEC record");
1614 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1615 break;
1616 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001617
Chris Lattner01ff65f2007-05-02 05:16:49 +00001618 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001619 // VFCmp/VICmp
1620 // or old form of ICmp/FCmp returning bool
Chris Lattner7337ab92007-05-06 00:00:00 +00001621 unsigned OpNum = 0;
1622 Value *LHS, *RHS;
1623 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1624 getValue(Record, OpNum, LHS->getType(), RHS) ||
1625 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001626 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001627
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001628 if (LHS->getType()->isFloatingPoint())
Nate Begemanac80ade2008-05-12 19:01:56 +00001629 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001630 else if (!isa<VectorType>(LHS->getType()))
1631 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanac80ade2008-05-12 19:01:56 +00001632 else if (LHS->getType()->isFPOrFPVector())
1633 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1634 else
1635 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001636 break;
1637 }
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001638 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1639 // Fcmp/ICmp returning bool or vector of bool
Dan Gohmanf72fb672008-09-09 01:02:47 +00001640 unsigned OpNum = 0;
1641 Value *LHS, *RHS;
1642 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1643 getValue(Record, OpNum, LHS->getType(), RHS) ||
1644 OpNum+1 != Record.size())
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001645 return Error("Invalid CMP2 record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00001646
Dan Gohmanf72fb672008-09-09 01:02:47 +00001647 if (LHS->getType()->isFPOrFPVector())
1648 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1649 else
1650 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1651 break;
1652 }
Devang Patel197be3d2008-02-22 02:49:49 +00001653 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1654 if (Record.size() != 2)
1655 return Error("Invalid GETRESULT record");
1656 unsigned OpNum = 0;
1657 Value *Op;
1658 getValueTypePair(Record, OpNum, NextValueNo, Op);
1659 unsigned Index = Record[1];
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001660 I = ExtractValueInst::Create(Op, Index);
Devang Patel197be3d2008-02-22 02:49:49 +00001661 break;
1662 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001663
Chris Lattner231cbcb2007-05-02 04:27:25 +00001664 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001665 {
1666 unsigned Size = Record.size();
1667 if (Size == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00001668 I = ReturnInst::Create();
Devang Pateld9d99ff2008-02-26 01:29:32 +00001669 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001670 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00001671
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001672 unsigned OpNum = 0;
1673 SmallVector<Value *,4> Vs;
1674 do {
1675 Value *Op = NULL;
1676 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1677 return Error("Invalid RET record");
1678 Vs.push_back(Op);
1679 } while(OpNum != Record.size());
1680
1681 const Type *ReturnType = F->getReturnType();
1682 if (Vs.size() > 1 ||
1683 (isa<StructType>(ReturnType) &&
1684 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1685 Value *RV = UndefValue::get(ReturnType);
1686 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1687 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1688 CurBB->getInstList().push_back(I);
1689 ValueList.AssignValue(I, NextValueNo++);
1690 RV = I;
1691 }
1692 I = ReturnInst::Create(RV);
Devang Pateld9d99ff2008-02-26 01:29:32 +00001693 break;
1694 }
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001695
1696 I = ReturnInst::Create(Vs[0]);
1697 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00001698 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001699 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001700 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001701 return Error("Invalid BR record");
1702 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1703 if (TrueDest == 0)
1704 return Error("Invalid BR record");
1705
1706 if (Record.size() == 1)
Gabor Greif051a9502008-04-06 20:25:17 +00001707 I = BranchInst::Create(TrueDest);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001708 else {
1709 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1710 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1711 if (FalseDest == 0 || Cond == 0)
1712 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001713 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001714 }
1715 break;
1716 }
1717 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1718 if (Record.size() < 3 || (Record.size() & 1) == 0)
1719 return Error("Invalid SWITCH record");
1720 const Type *OpTy = getTypeByID(Record[0]);
1721 Value *Cond = getFnValueByID(Record[1], OpTy);
1722 BasicBlock *Default = getBasicBlock(Record[2]);
1723 if (OpTy == 0 || Cond == 0 || Default == 0)
1724 return Error("Invalid SWITCH record");
1725 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001726 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001727 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1728 ConstantInt *CaseVal =
1729 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1730 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1731 if (CaseVal == 0 || DestBB == 0) {
1732 delete SI;
1733 return Error("Invalid SWITCH record!");
1734 }
1735 SI->addCase(CaseVal, DestBB);
1736 }
1737 I = SI;
1738 break;
1739 }
1740
Duncan Sandsdc024672007-11-27 13:23:08 +00001741 case bitc::FUNC_CODE_INST_INVOKE: {
1742 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001743 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00001744 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001745 unsigned CCInfo = Record[1];
1746 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1747 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001748
Chris Lattnera9bb7132007-05-08 05:38:01 +00001749 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001750 Value *Callee;
1751 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001752 return Error("Invalid INVOKE record");
1753
Chris Lattner7337ab92007-05-06 00:00:00 +00001754 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1755 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001756 dyn_cast<FunctionType>(CalleeTy->getElementType());
1757
1758 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001759 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1760 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001761 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001762
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001763 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001764 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1765 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1766 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001767 }
1768
Chris Lattner7337ab92007-05-06 00:00:00 +00001769 if (!FTy->isVarArg()) {
1770 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001771 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001772 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001773 // Read type/value pairs for varargs params.
1774 while (OpNum != Record.size()) {
1775 Value *Op;
1776 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1777 return Error("Invalid INVOKE record");
1778 Ops.push_back(Op);
1779 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001780 }
1781
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001782 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1783 Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001784 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Devang Patel05988662008-09-25 21:00:45 +00001785 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001786 break;
1787 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001788 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1789 I = new UnwindInst();
1790 break;
1791 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1792 I = new UnreachableInst();
1793 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001794 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001795 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001796 return Error("Invalid PHI record");
1797 const Type *Ty = getTypeByID(Record[0]);
1798 if (!Ty) return Error("Invalid PHI record");
1799
Gabor Greif051a9502008-04-06 20:25:17 +00001800 PHINode *PN = PHINode::Create(Ty);
Chris Lattner86941612008-04-13 00:14:42 +00001801 PN->reserveOperandSpace((Record.size()-1)/2);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001802
Chris Lattner15e6d172007-05-04 19:11:41 +00001803 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1804 Value *V = getFnValueByID(Record[1+i], Ty);
1805 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001806 if (!V || !BB) return Error("Invalid PHI record");
1807 PN->addIncoming(V, BB);
1808 }
1809 I = PN;
1810 break;
1811 }
1812
1813 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1814 if (Record.size() < 3)
1815 return Error("Invalid MALLOC record");
1816 const PointerType *Ty =
1817 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1818 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1819 unsigned Align = Record[2];
1820 if (!Ty || !Size) return Error("Invalid MALLOC record");
1821 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1822 break;
1823 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001824 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1825 unsigned OpNum = 0;
1826 Value *Op;
1827 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1828 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001829 return Error("Invalid FREE record");
1830 I = new FreeInst(Op);
1831 break;
1832 }
1833 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1834 if (Record.size() < 3)
1835 return Error("Invalid ALLOCA record");
1836 const PointerType *Ty =
1837 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1838 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1839 unsigned Align = Record[2];
1840 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1841 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1842 break;
1843 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001844 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001845 unsigned OpNum = 0;
1846 Value *Op;
1847 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1848 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001849 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001850
1851 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001852 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001853 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001854 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1855 unsigned OpNum = 0;
1856 Value *Val, *Ptr;
1857 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1858 getValue(Record, OpNum,
1859 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1860 OpNum+2 != Record.size())
1861 return Error("Invalid STORE record");
1862
1863 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1864 break;
1865 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001866 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001867 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001868 unsigned OpNum = 0;
1869 Value *Val, *Ptr;
1870 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001871 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001872 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001873 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001874
1875 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001876 break;
1877 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001878 case bitc::FUNC_CODE_INST_CALL: {
1879 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1880 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001881 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001882
Devang Patel05988662008-09-25 21:00:45 +00001883 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001884 unsigned CCInfo = Record[1];
1885
1886 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001887 Value *Callee;
1888 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1889 return Error("Invalid CALL record");
1890
1891 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001892 const FunctionType *FTy = 0;
1893 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001894 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001895 return Error("Invalid CALL record");
1896
1897 SmallVector<Value*, 16> Args;
1898 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001899 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001900 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1901 Args.push_back(getBasicBlock(Record[OpNum]));
1902 else
1903 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001904 if (Args.back() == 0) return Error("Invalid CALL record");
1905 }
1906
Chris Lattner0579f7f2007-05-03 22:04:19 +00001907 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001908 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001909 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001910 return Error("Invalid CALL record");
1911 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001912 while (OpNum != Record.size()) {
1913 Value *Op;
1914 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1915 return Error("Invalid CALL record");
1916 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001917 }
1918 }
1919
Gabor Greif051a9502008-04-06 20:25:17 +00001920 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001921 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1922 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00001923 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001924 break;
1925 }
1926 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1927 if (Record.size() < 3)
1928 return Error("Invalid VAARG record");
1929 const Type *OpTy = getTypeByID(Record[0]);
1930 Value *Op = getFnValueByID(Record[1], OpTy);
1931 const Type *ResTy = getTypeByID(Record[2]);
1932 if (!OpTy || !Op || !ResTy)
1933 return Error("Invalid VAARG record");
1934 I = new VAArgInst(Op, ResTy);
1935 break;
1936 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001937 }
1938
1939 // Add instruction to end of current BB. If there is no current BB, reject
1940 // this file.
1941 if (CurBB == 0) {
1942 delete I;
1943 return Error("Invalid instruction with no BB");
1944 }
1945 CurBB->getInstList().push_back(I);
1946
1947 // If this was a terminator instruction, move to the next block.
1948 if (isa<TerminatorInst>(I)) {
1949 ++CurBBNo;
1950 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1951 }
1952
1953 // Non-void values get registered in the value table for future use.
1954 if (I && I->getType() != Type::VoidTy)
1955 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001956 }
1957
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001958 // Check the function list for unresolved values.
1959 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1960 if (A->getParent() == 0) {
1961 // We found at least one unresolved value. Nuke them all to avoid leaks.
1962 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1963 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1964 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1965 delete A;
1966 }
1967 }
Chris Lattner35a04702007-05-04 03:50:29 +00001968 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001969 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001970 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001971
1972 // Trim the value list down to the size it was before we parsed this function.
1973 ValueList.shrinkTo(ModuleValueListSize);
1974 std::vector<BasicBlock*>().swap(FunctionBBs);
1975
Chris Lattner48f84872007-05-01 04:59:48 +00001976 return false;
1977}
1978
Chris Lattnerb348bb82007-05-18 04:02:46 +00001979//===----------------------------------------------------------------------===//
1980// ModuleProvider implementation
1981//===----------------------------------------------------------------------===//
1982
1983
1984bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1985 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001986 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001987
1988 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1989 DeferredFunctionInfo.find(F);
1990 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1991
1992 // Move the bit stream to the saved position of the deferred function body and
1993 // restore the real linkage type for the function.
1994 Stream.JumpToBit(DFII->second.first);
1995 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1996
1997 if (ParseFunctionBody(F)) {
1998 if (ErrInfo) *ErrInfo = ErrorString;
1999 return true;
2000 }
Chandler Carruth69940402007-08-04 01:51:18 +00002001
2002 // Upgrade any old intrinsic calls in the function.
2003 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2004 E = UpgradedIntrinsics.end(); I != E; ++I) {
2005 if (I->first != I->second) {
2006 for (Value::use_iterator UI = I->first->use_begin(),
2007 UE = I->first->use_end(); UI != UE; ) {
2008 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2009 UpgradeIntrinsicCall(CI, I->second);
2010 }
2011 }
2012 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00002013
2014 return false;
2015}
2016
2017void BitcodeReader::dematerializeFunction(Function *F) {
2018 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00002019 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00002020 return;
2021
2022 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2023
2024 // Just forget the function body, we can remat it later.
2025 F->deleteBody();
2026 F->setLinkage(GlobalValue::GhostLinkage);
2027}
2028
2029
2030Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2031 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
2032 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
2033 ++I) {
2034 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00002035 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00002036 materializeFunction(F, ErrInfo))
2037 return 0;
2038 }
Chandler Carruth69940402007-08-04 01:51:18 +00002039
2040 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2041 // delete the old functions to clean up. We can't do this unless the entire
2042 // module is materialized because there could always be another function body
2043 // with calls to the old function.
2044 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2045 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2046 if (I->first != I->second) {
2047 for (Value::use_iterator UI = I->first->use_begin(),
2048 UE = I->first->use_end(); UI != UE; ) {
2049 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2050 UpgradeIntrinsicCall(CI, I->second);
2051 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002052 if (!I->first->use_empty())
2053 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002054 I->first->eraseFromParent();
2055 }
2056 }
2057 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2058
Chris Lattnerb348bb82007-05-18 04:02:46 +00002059 return TheModule;
2060}
2061
2062
2063/// This method is provided by the parent ModuleProvde class and overriden
2064/// here. It simply releases the module from its provided and frees up our
2065/// state.
2066/// @brief Release our hold on the generated module
2067Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2068 // Since we're losing control of this Module, we must hand it back complete
2069 Module *M = ModuleProvider::releaseModule(ErrInfo);
2070 FreeState();
2071 return M;
2072}
2073
Chris Lattner48f84872007-05-01 04:59:48 +00002074
Chris Lattnerc453f762007-04-29 07:54:31 +00002075//===----------------------------------------------------------------------===//
2076// External interface
2077//===----------------------------------------------------------------------===//
2078
2079/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2080///
2081ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2082 std::string *ErrMsg) {
2083 BitcodeReader *R = new BitcodeReader(Buffer);
2084 if (R->ParseBitcode()) {
2085 if (ErrMsg)
2086 *ErrMsg = R->getErrorString();
2087
2088 // Don't let the BitcodeReader dtor delete 'Buffer'.
2089 R->releaseMemoryBuffer();
2090 delete R;
2091 return 0;
2092 }
2093 return R;
2094}
2095
2096/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2097/// If an error occurs, return null and fill in *ErrMsg if non-null.
2098Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
2099 BitcodeReader *R;
2100 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
2101 if (!R) return 0;
2102
Chris Lattnerb348bb82007-05-18 04:02:46 +00002103 // Read in the entire module.
2104 Module *M = R->materializeModule(ErrMsg);
2105
2106 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2107 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00002108 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002109
2110 // If there was no error, tell ModuleProvider not to delete it when its dtor
2111 // is run.
2112 if (M)
2113 M = R->releaseModule(ErrMsg);
2114
Chris Lattnerc453f762007-04-29 07:54:31 +00002115 delete R;
2116 return M;
2117}