blob: bc1eba01e2d398876266d6ef9cda1cb43bbe76c2 [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"
Owen Anderson74a77812009-07-07 20:18:58 +000020#include "llvm/LLVMContext.h"
Nick Lewyckycb337992009-05-10 20:57:05 +000021#include "llvm/MDNode.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000022#include "llvm/Module.h"
Chandler Carruth69940402007-08-04 01:51:18 +000023#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000024#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000025#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000026#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000027#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000028#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000029using namespace llvm;
30
Chris Lattnerb348bb82007-05-18 04:02:46 +000031void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000032 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000033 Buffer = 0;
34 std::vector<PATypeHolder>().swap(TypeList);
35 ValueList.clear();
Chris Lattner461edd92008-03-12 02:25:52 +000036
Devang Patel19c87462008-09-26 22:53:05 +000037 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000038 std::vector<BasicBlock*>().swap(FunctionBBs);
39 std::vector<Function*>().swap(FunctionsWithBodies);
40 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000041}
42
Chris Lattner48c85b82007-05-04 03:30:17 +000043//===----------------------------------------------------------------------===//
44// Helper functions to implement forward reference resolution, etc.
45//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000046
Chris Lattnercaee0dc2007-04-22 06:23:29 +000047/// ConvertToString - Convert a string from a record into an std::string, return
48/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000049template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000050static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000051 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000052 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000053 return true;
54
Chris Lattner15e6d172007-05-04 19:11:41 +000055 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
56 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000057 return false;
58}
59
60static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
61 switch (Val) {
62 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000063 case 0: return GlobalValue::ExternalLinkage;
64 case 1: return GlobalValue::WeakAnyLinkage;
65 case 2: return GlobalValue::AppendingLinkage;
66 case 3: return GlobalValue::InternalLinkage;
67 case 4: return GlobalValue::LinkOnceAnyLinkage;
68 case 5: return GlobalValue::DLLImportLinkage;
69 case 6: return GlobalValue::DLLExportLinkage;
70 case 7: return GlobalValue::ExternalWeakLinkage;
71 case 8: return GlobalValue::CommonLinkage;
72 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000073 case 10: return GlobalValue::WeakODRLinkage;
74 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000075 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000076 case 13: return GlobalValue::LinkerPrivateLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000077 }
78}
79
80static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
81 switch (Val) {
82 default: // Map unknown visibilities to default.
83 case 0: return GlobalValue::DefaultVisibility;
84 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000085 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000086 }
87}
88
Chris Lattnerf581c3b2007-04-24 07:07:11 +000089static int GetDecodedCastOpcode(unsigned Val) {
90 switch (Val) {
91 default: return -1;
92 case bitc::CAST_TRUNC : return Instruction::Trunc;
93 case bitc::CAST_ZEXT : return Instruction::ZExt;
94 case bitc::CAST_SEXT : return Instruction::SExt;
95 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
96 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
97 case bitc::CAST_UITOFP : return Instruction::UIToFP;
98 case bitc::CAST_SITOFP : return Instruction::SIToFP;
99 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
100 case bitc::CAST_FPEXT : return Instruction::FPExt;
101 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
102 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
103 case bitc::CAST_BITCAST : return Instruction::BitCast;
104 }
105}
106static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
107 switch (Val) {
108 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000109 case bitc::BINOP_ADD:
110 return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add;
111 case bitc::BINOP_SUB:
112 return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub;
113 case bitc::BINOP_MUL:
114 return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000115 case bitc::BINOP_UDIV: return Instruction::UDiv;
116 case bitc::BINOP_SDIV:
117 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
118 case bitc::BINOP_UREM: return Instruction::URem;
119 case bitc::BINOP_SREM:
120 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
121 case bitc::BINOP_SHL: return Instruction::Shl;
122 case bitc::BINOP_LSHR: return Instruction::LShr;
123 case bitc::BINOP_ASHR: return Instruction::AShr;
124 case bitc::BINOP_AND: return Instruction::And;
125 case bitc::BINOP_OR: return Instruction::Or;
126 case bitc::BINOP_XOR: return Instruction::Xor;
127 }
128}
129
Gabor Greifefe65362008-05-10 08:32:32 +0000130namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000131namespace {
132 /// @brief A class for maintaining the slot number definition
133 /// as a placeholder for the actual definition for forward constants defs.
134 class ConstantPlaceHolder : public ConstantExpr {
135 ConstantPlaceHolder(); // DO NOT IMPLEMENT
136 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000137 public:
138 // allocate space for exactly one operand
139 void *operator new(size_t s) {
140 return User::operator new(s, 1);
141 }
Owen Anderson74a77812009-07-07 20:18:58 +0000142 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000143 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson74a77812009-07-07 20:18:58 +0000144 Op<0>() = Context.getUndef(Type::Int32Ty);
Chris Lattner522b7b12007-04-24 05:48:56 +0000145 }
Chris Lattnerea693df2008-08-21 02:34:16 +0000146
147 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
148 static inline bool classof(const ConstantPlaceHolder *) { return true; }
149 static bool classof(const Value *V) {
150 return isa<ConstantExpr>(V) &&
151 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
152 }
153
154
Gabor Greifefe65362008-05-10 08:32:32 +0000155 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000156 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000157 };
158}
159
Chris Lattner46e77402009-03-31 22:55:09 +0000160// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000161template <>
162struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
163};
Gabor Greifefe65362008-05-10 08:32:32 +0000164}
165
Chris Lattner46e77402009-03-31 22:55:09 +0000166
167void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
168 if (Idx == size()) {
169 push_back(V);
170 return;
171 }
172
173 if (Idx >= size())
174 resize(Idx+1);
175
176 WeakVH &OldV = ValuePtrs[Idx];
177 if (OldV == 0) {
178 OldV = V;
179 return;
180 }
181
182 // Handle constants and non-constants (e.g. instrs) differently for
183 // efficiency.
184 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
185 ResolveConstants.push_back(std::make_pair(PHC, Idx));
186 OldV = V;
187 } else {
188 // If there was a forward reference to this value, replace it.
189 Value *PrevVal = OldV;
190 OldV->replaceAllUsesWith(V);
191 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000192 }
193}
Chris Lattner46e77402009-03-31 22:55:09 +0000194
Gabor Greifefe65362008-05-10 08:32:32 +0000195
Chris Lattner522b7b12007-04-24 05:48:56 +0000196Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
197 const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000198 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000199 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000200
Chris Lattner46e77402009-03-31 22:55:09 +0000201 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000202 assert(Ty == V->getType() && "Type mismatch in constant table!");
203 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000204 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000205
206 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000207 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000208 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000209 return C;
210}
211
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000212Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000213 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000214 resize(Idx + 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000215
Chris Lattner46e77402009-03-31 22:55:09 +0000216 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000217 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
218 return V;
219 }
220
Chris Lattner01ff65f2007-05-02 05:16:49 +0000221 // No type specified, must be invalid reference.
222 if (Ty == 0) return 0;
223
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000224 // Create and return a placeholder, which will later be RAUW'd.
225 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000226 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000227 return V;
228}
229
Chris Lattnerea693df2008-08-21 02:34:16 +0000230/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
231/// resolves any forward references. The idea behind this is that we sometimes
232/// get constants (such as large arrays) which reference *many* forward ref
233/// constants. Replacing each of these causes a lot of thrashing when
234/// building/reuniquing the constant. Instead of doing this, we look at all the
235/// uses and rewrite all the place holders at once for any constant that uses
236/// a placeholder.
237void BitcodeReaderValueList::ResolveConstantForwardRefs() {
238 // Sort the values by-pointer so that they are efficient to look up with a
239 // binary search.
240 std::sort(ResolveConstants.begin(), ResolveConstants.end());
241
242 SmallVector<Constant*, 64> NewOps;
243
244 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000245 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000246 Constant *Placeholder = ResolveConstants.back().first;
247 ResolveConstants.pop_back();
248
249 // Loop over all users of the placeholder, updating them to reference the
250 // new value. If they reference more than one placeholder, update them all
251 // at once.
252 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000253 Value::use_iterator UI = Placeholder->use_begin();
254
Chris Lattnerea693df2008-08-21 02:34:16 +0000255 // If the using object isn't uniqued, just update the operands. This
256 // handles instructions and initializers for global variables.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000257 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
258 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000259 continue;
260 }
261
262 // Otherwise, we have a constant that uses the placeholder. Replace that
263 // constant with a new constant that has *all* placeholder uses updated.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000264 Constant *UserC = cast<Constant>(*UI);
Chris Lattnerea693df2008-08-21 02:34:16 +0000265 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
266 I != E; ++I) {
267 Value *NewOp;
268 if (!isa<ConstantPlaceHolder>(*I)) {
269 // Not a placeholder reference.
270 NewOp = *I;
271 } else if (*I == Placeholder) {
272 // Common case is that it just references this one placeholder.
273 NewOp = RealVal;
274 } else {
275 // Otherwise, look up the placeholder in ResolveConstants.
276 ResolveConstantsTy::iterator It =
277 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
278 std::pair<Constant*, unsigned>(cast<Constant>(*I),
279 0));
280 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000281 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000282 }
283
284 NewOps.push_back(cast<Constant>(NewOp));
285 }
286
287 // Make the new constant.
288 Constant *NewC;
289 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Owen Anderson74a77812009-07-07 20:18:58 +0000290 NewC = Context.getConstantArray(UserCA->getType(), &NewOps[0],
291 NewOps.size());
Chris Lattnerea693df2008-08-21 02:34:16 +0000292 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Owen Anderson74a77812009-07-07 20:18:58 +0000293 NewC = Context.getConstantStruct(&NewOps[0], NewOps.size(),
294 UserCS->getType()->isPacked());
Chris Lattnerea693df2008-08-21 02:34:16 +0000295 } else if (isa<ConstantVector>(UserC)) {
Owen Anderson74a77812009-07-07 20:18:58 +0000296 NewC = Context.getConstantVector(&NewOps[0], NewOps.size());
Nick Lewyckycb337992009-05-10 20:57:05 +0000297 } else {
298 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Chris Lattnerea693df2008-08-21 02:34:16 +0000299 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
300 NewOps.size());
301 }
302
303 UserC->replaceAllUsesWith(NewC);
304 UserC->destroyConstant();
305 NewOps.clear();
306 }
307
Nick Lewyckycb337992009-05-10 20:57:05 +0000308 // Update all ValueHandles, they should be the only users at this point.
309 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000310 delete Placeholder;
311 }
312}
313
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000314
315const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
316 // If the TypeID is in range, return it.
317 if (ID < TypeList.size())
318 return TypeList[ID].get();
319 if (!isTypeTable) return 0;
320
321 // The type table allows forward references. Push as many Opaque types as
322 // needed to get up to ID.
323 while (TypeList.size() <= ID)
Owen Anderson74a77812009-07-07 20:18:58 +0000324 TypeList.push_back(Context.getOpaqueType());
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000325 return TypeList.back().get();
326}
327
Chris Lattner48c85b82007-05-04 03:30:17 +0000328//===----------------------------------------------------------------------===//
329// Functions for parsing blocks from the bitcode file
330//===----------------------------------------------------------------------===//
331
Devang Patel05988662008-09-25 21:00:45 +0000332bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000333 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000334 return Error("Malformed block record");
335
Devang Patel19c87462008-09-26 22:53:05 +0000336 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000337 return Error("Multiple PARAMATTR blocks found!");
338
339 SmallVector<uint64_t, 64> Record;
340
Devang Patel05988662008-09-25 21:00:45 +0000341 SmallVector<AttributeWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000342
343 // Read all the records.
344 while (1) {
345 unsigned Code = Stream.ReadCode();
346 if (Code == bitc::END_BLOCK) {
347 if (Stream.ReadBlockEnd())
348 return Error("Error at end of PARAMATTR block");
349 return false;
350 }
351
352 if (Code == bitc::ENTER_SUBBLOCK) {
353 // No known subblocks, always skip them.
354 Stream.ReadSubBlockID();
355 if (Stream.SkipBlock())
356 return Error("Malformed block record");
357 continue;
358 }
359
360 if (Code == bitc::DEFINE_ABBREV) {
361 Stream.ReadAbbrevRecord();
362 continue;
363 }
364
365 // Read a record.
366 Record.clear();
367 switch (Stream.ReadRecord(Code, Record)) {
368 default: // Default behavior: ignore.
369 break;
370 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
371 if (Record.size() & 1)
372 return Error("Invalid ENTRY record");
373
Chris Lattner9a6cb152008-10-05 18:22:09 +0000374 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000375 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000376 // to index ~0. Index 0 is used for return value attributes but used to be
377 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000378 Attributes RetAttribute = Attribute::None;
379 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000380 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000381 // FIXME: remove in LLVM 3.0
382 // The alignment is stored as a 16-bit raw value from bits 31--16.
383 // We shift the bits above 31 down by 11 bits.
384
385 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
386 if (Alignment && !isPowerOf2_32(Alignment))
387 return Error("Alignment is not a power of two.");
388
389 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
390 if (Alignment)
391 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
392 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
393 Record[i+1] = ReconstitutedAttr;
394
Devang Patel19c87462008-09-26 22:53:05 +0000395 if (Record[i] == 0)
396 RetAttribute = Record[i+1];
397 else if (Record[i] == ~0U)
398 FnAttribute = Record[i+1];
399 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000400
401 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
402 Attribute::ReadOnly|Attribute::ReadNone);
403
404 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
405 (RetAttribute & OldRetAttrs) != 0) {
406 if (FnAttribute == Attribute::None) { // add a slot so they get added.
407 Record.push_back(~0U);
408 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000409 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000410
411 FnAttribute |= RetAttribute & OldRetAttrs;
412 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000413 }
Chris Lattner461edd92008-03-12 02:25:52 +0000414
Devang Patel19c87462008-09-26 22:53:05 +0000415 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000416 if (Record[i] == 0) {
417 if (RetAttribute != Attribute::None)
418 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
419 } else if (Record[i] == ~0U) {
420 if (FnAttribute != Attribute::None)
421 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
422 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000423 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
424 }
Devang Patel19c87462008-09-26 22:53:05 +0000425
426 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000427 Attrs.clear();
428 break;
429 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000430 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000431 }
432}
433
434
Chris Lattner86697142007-05-01 05:01:34 +0000435bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000436 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000437 return Error("Malformed block record");
438
439 if (!TypeList.empty())
440 return Error("Multiple TYPE_BLOCKs found!");
441
442 SmallVector<uint64_t, 64> Record;
443 unsigned NumRecords = 0;
444
445 // Read all the records for this type table.
446 while (1) {
447 unsigned Code = Stream.ReadCode();
448 if (Code == bitc::END_BLOCK) {
449 if (NumRecords != TypeList.size())
450 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000451 if (Stream.ReadBlockEnd())
452 return Error("Error at end of type table block");
453 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000454 }
455
456 if (Code == bitc::ENTER_SUBBLOCK) {
457 // No known subblocks, always skip them.
458 Stream.ReadSubBlockID();
459 if (Stream.SkipBlock())
460 return Error("Malformed block record");
461 continue;
462 }
463
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000464 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000465 Stream.ReadAbbrevRecord();
466 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000467 }
468
469 // Read a record.
470 Record.clear();
471 const Type *ResultTy = 0;
472 switch (Stream.ReadRecord(Code, Record)) {
473 default: // Default behavior: unknown type.
474 ResultTy = 0;
475 break;
476 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
477 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
478 // type list. This allows us to reserve space.
479 if (Record.size() < 1)
480 return Error("Invalid TYPE_CODE_NUMENTRY record");
481 TypeList.reserve(Record[0]);
482 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000483 case bitc::TYPE_CODE_VOID: // VOID
484 ResultTy = Type::VoidTy;
485 break;
486 case bitc::TYPE_CODE_FLOAT: // FLOAT
487 ResultTy = Type::FloatTy;
488 break;
489 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
490 ResultTy = Type::DoubleTy;
491 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000492 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
493 ResultTy = Type::X86_FP80Ty;
494 break;
495 case bitc::TYPE_CODE_FP128: // FP128
496 ResultTy = Type::FP128Ty;
497 break;
498 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
499 ResultTy = Type::PPC_FP128Ty;
500 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000501 case bitc::TYPE_CODE_LABEL: // LABEL
502 ResultTy = Type::LabelTy;
503 break;
504 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
505 ResultTy = 0;
506 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000507 case bitc::TYPE_CODE_METADATA: // METADATA
508 ResultTy = Type::MetadataTy;
509 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000510 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
511 if (Record.size() < 1)
512 return Error("Invalid Integer type record");
513
Owen Anderson74a77812009-07-07 20:18:58 +0000514 ResultTy = Context.getIntegerType(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000515 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000516 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
517 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000518 if (Record.size() < 1)
519 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000520 unsigned AddressSpace = 0;
521 if (Record.size() == 2)
522 AddressSpace = Record[1];
Owen Anderson74a77812009-07-07 20:18:58 +0000523 ResultTy = Context.getPointerType(getTypeByID(Record[0], true),
524 AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000525 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000526 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000527 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000528 // FIXME: attrid is dead, remove it in LLVM 3.0
529 // FUNCTION: [vararg, attrid, retty, paramty x N]
530 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000531 return Error("Invalid FUNCTION type record");
532 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000533 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000534 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000535
Owen Anderson74a77812009-07-07 20:18:58 +0000536 ResultTy = Context.getFunctionType(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000537 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000538 break;
539 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000540 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000541 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000542 return Error("Invalid STRUCT type record");
543 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000544 for (unsigned i = 1, e = Record.size(); i != e; ++i)
545 EltTys.push_back(getTypeByID(Record[i], true));
Owen Anderson74a77812009-07-07 20:18:58 +0000546 ResultTy = Context.getStructType(EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000547 break;
548 }
549 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
550 if (Record.size() < 2)
551 return Error("Invalid ARRAY type record");
Owen Anderson74a77812009-07-07 20:18:58 +0000552 ResultTy = Context.getArrayType(getTypeByID(Record[1], true), Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000553 break;
554 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
555 if (Record.size() < 2)
556 return Error("Invalid VECTOR type record");
Owen Anderson74a77812009-07-07 20:18:58 +0000557 ResultTy = Context.getVectorType(getTypeByID(Record[1], true), Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000558 break;
559 }
560
561 if (NumRecords == TypeList.size()) {
562 // If this is a new type slot, just append it.
Owen Anderson74a77812009-07-07 20:18:58 +0000563 TypeList.push_back(ResultTy ? ResultTy : Context.getOpaqueType());
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000564 ++NumRecords;
565 } else if (ResultTy == 0) {
566 // Otherwise, this was forward referenced, so an opaque type was created,
567 // but the result type is actually just an opaque. Leave the one we
568 // created previously.
569 ++NumRecords;
570 } else {
571 // Otherwise, this was forward referenced, so an opaque type was created.
572 // Resolve the opaque type to the real type now.
573 assert(NumRecords < TypeList.size() && "Typelist imbalance");
574 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
575
576 // Don't directly push the new type on the Tab. Instead we want to replace
577 // the opaque type we previously inserted with the new concrete value. The
578 // refinement from the abstract (opaque) type to the new type causes all
579 // uses of the abstract type to use the concrete type (NewTy). This will
580 // also cause the opaque type to be deleted.
581 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
582
583 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000584 // value table... or with a preexisting type that was already in the
585 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000586 assert(TypeList[NumRecords-1].get() != OldTy &&
587 "refineAbstractType didn't work!");
588 }
589 }
590}
591
592
Chris Lattner86697142007-05-01 05:01:34 +0000593bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000594 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000595 return Error("Malformed block record");
596
597 SmallVector<uint64_t, 64> Record;
598
599 // Read all the records for this type table.
600 std::string TypeName;
601 while (1) {
602 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000603 if (Code == bitc::END_BLOCK) {
604 if (Stream.ReadBlockEnd())
605 return Error("Error at end of type symbol table block");
606 return false;
607 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000608
609 if (Code == bitc::ENTER_SUBBLOCK) {
610 // No known subblocks, always skip them.
611 Stream.ReadSubBlockID();
612 if (Stream.SkipBlock())
613 return Error("Malformed block record");
614 continue;
615 }
616
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000617 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000618 Stream.ReadAbbrevRecord();
619 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000620 }
621
622 // Read a record.
623 Record.clear();
624 switch (Stream.ReadRecord(Code, Record)) {
625 default: // Default behavior: unknown type.
626 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000627 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000628 if (ConvertToString(Record, 1, TypeName))
629 return Error("Invalid TST_ENTRY record");
630 unsigned TypeID = Record[0];
631 if (TypeID >= TypeList.size())
632 return Error("Invalid Type ID in TST_ENTRY record");
633
634 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
635 TypeName.clear();
636 break;
637 }
638 }
639}
640
Chris Lattner86697142007-05-01 05:01:34 +0000641bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000642 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000643 return Error("Malformed block record");
644
645 SmallVector<uint64_t, 64> Record;
646
647 // Read all the records for this value table.
648 SmallString<128> ValueName;
649 while (1) {
650 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000651 if (Code == bitc::END_BLOCK) {
652 if (Stream.ReadBlockEnd())
653 return Error("Error at end of value symbol table block");
654 return false;
655 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000656 if (Code == bitc::ENTER_SUBBLOCK) {
657 // No known subblocks, always skip them.
658 Stream.ReadSubBlockID();
659 if (Stream.SkipBlock())
660 return Error("Malformed block record");
661 continue;
662 }
663
664 if (Code == bitc::DEFINE_ABBREV) {
665 Stream.ReadAbbrevRecord();
666 continue;
667 }
668
669 // Read a record.
670 Record.clear();
671 switch (Stream.ReadRecord(Code, Record)) {
672 default: // Default behavior: unknown type.
673 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000674 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000675 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000676 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000677 unsigned ValueID = Record[0];
678 if (ValueID >= ValueList.size())
679 return Error("Invalid Value ID in VST_ENTRY record");
680 Value *V = ValueList[ValueID];
681
682 V->setName(&ValueName[0], ValueName.size());
683 ValueName.clear();
684 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000685 }
686 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000687 if (ConvertToString(Record, 1, ValueName))
688 return Error("Invalid VST_BBENTRY record");
689 BasicBlock *BB = getBasicBlock(Record[0]);
690 if (BB == 0)
691 return Error("Invalid BB ID in VST_BBENTRY record");
692
693 BB->setName(&ValueName[0], ValueName.size());
694 ValueName.clear();
695 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000696 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000697 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000698 }
699}
700
Chris Lattner0eef0802007-04-24 04:04:35 +0000701/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
702/// the LSB for dense VBR encoding.
703static uint64_t DecodeSignRotatedValue(uint64_t V) {
704 if ((V & 1) == 0)
705 return V >> 1;
706 if (V != 1)
707 return -(V >> 1);
708 // There is no such thing as -0 with integers. "-0" really means MININT.
709 return 1ULL << 63;
710}
711
Chris Lattner07d98b42007-04-26 02:46:40 +0000712/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
713/// values and aliases that we can.
714bool BitcodeReader::ResolveGlobalAndAliasInits() {
715 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
716 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
717
718 GlobalInitWorklist.swap(GlobalInits);
719 AliasInitWorklist.swap(AliasInits);
720
721 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000722 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000723 if (ValID >= ValueList.size()) {
724 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000725 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000726 } else {
727 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
728 GlobalInitWorklist.back().first->setInitializer(C);
729 else
730 return Error("Global variable initializer is not a constant!");
731 }
732 GlobalInitWorklist.pop_back();
733 }
734
735 while (!AliasInitWorklist.empty()) {
736 unsigned ValID = AliasInitWorklist.back().second;
737 if (ValID >= ValueList.size()) {
738 AliasInits.push_back(AliasInitWorklist.back());
739 } else {
740 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000741 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000742 else
743 return Error("Alias initializer is not a constant!");
744 }
745 AliasInitWorklist.pop_back();
746 }
747 return false;
748}
749
750
Chris Lattner86697142007-05-01 05:01:34 +0000751bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000752 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000753 return Error("Malformed block record");
754
755 SmallVector<uint64_t, 64> Record;
756
757 // Read all the records for this value table.
758 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000759 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000760 while (1) {
761 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000762 if (Code == bitc::END_BLOCK)
763 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000764
765 if (Code == bitc::ENTER_SUBBLOCK) {
766 // No known subblocks, always skip them.
767 Stream.ReadSubBlockID();
768 if (Stream.SkipBlock())
769 return Error("Malformed block record");
770 continue;
771 }
772
773 if (Code == bitc::DEFINE_ABBREV) {
774 Stream.ReadAbbrevRecord();
775 continue;
776 }
777
778 // Read a record.
779 Record.clear();
780 Value *V = 0;
781 switch (Stream.ReadRecord(Code, Record)) {
782 default: // Default behavior: unknown constant
783 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson74a77812009-07-07 20:18:58 +0000784 V = Context.getUndef(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000785 break;
786 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
787 if (Record.empty())
788 return Error("Malformed CST_SETTYPE record");
789 if (Record[0] >= TypeList.size())
790 return Error("Invalid Type ID in CST_SETTYPE record");
791 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000792 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000793 case bitc::CST_CODE_NULL: // NULL
Owen Anderson74a77812009-07-07 20:18:58 +0000794 V = Context.getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000795 break;
796 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000797 if (!isa<IntegerType>(CurTy) || Record.empty())
798 return Error("Invalid CST_INTEGER record");
Owen Anderson74a77812009-07-07 20:18:58 +0000799 V = Context.getConstantInt(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000800 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000801 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
802 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000803 return Error("Invalid WIDE_INTEGER record");
804
Chris Lattner15e6d172007-05-04 19:11:41 +0000805 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000806 SmallVector<uint64_t, 8> Words;
807 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000808 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000809 Words[i] = DecodeSignRotatedValue(Record[i]);
Owen Anderson74a77812009-07-07 20:18:58 +0000810 V = Context.getConstantInt(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000811 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000812 break;
813 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000814 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000815 if (Record.empty())
816 return Error("Invalid FLOAT record");
817 if (CurTy == Type::FloatTy)
Owen Anderson74a77812009-07-07 20:18:58 +0000818 V = Context.getConstantFP(APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000819 else if (CurTy == Type::DoubleTy)
Owen Anderson74a77812009-07-07 20:18:58 +0000820 V = Context.getConstantFP(APFloat(APInt(64, Record[0])));
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000821 else if (CurTy == Type::X86_FP80Ty) {
822 // Bits are not stored the same way as a normal i80 APInt, compensate.
823 uint64_t Rearrange[2];
824 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
825 Rearrange[1] = Record[0] >> 48;
Owen Anderson74a77812009-07-07 20:18:58 +0000826 V = Context.getConstantFP(APFloat(APInt(80, 2, Rearrange)));
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000827 } else if (CurTy == Type::FP128Ty)
Owen Anderson74a77812009-07-07 20:18:58 +0000828 V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000829 else if (CurTy == Type::PPC_FP128Ty)
Owen Anderson74a77812009-07-07 20:18:58 +0000830 V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000831 else
Owen Anderson74a77812009-07-07 20:18:58 +0000832 V = Context.getUndef(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000833 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000834 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000835
Chris Lattner15e6d172007-05-04 19:11:41 +0000836 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
837 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000838 return Error("Invalid CST_AGGREGATE record");
839
Chris Lattner15e6d172007-05-04 19:11:41 +0000840 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000841 std::vector<Constant*> Elts;
842
843 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
844 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000845 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000846 STy->getElementType(i)));
Owen Anderson74a77812009-07-07 20:18:58 +0000847 V = Context.getConstantStruct(STy, Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +0000848 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
849 const Type *EltTy = ATy->getElementType();
850 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000851 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson74a77812009-07-07 20:18:58 +0000852 V = Context.getConstantArray(ATy, Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +0000853 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
854 const Type *EltTy = VTy->getElementType();
855 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000856 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson74a77812009-07-07 20:18:58 +0000857 V = Context.getConstantVector(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +0000858 } else {
Owen Anderson74a77812009-07-07 20:18:58 +0000859 V = Context.getUndef(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +0000860 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000861 break;
862 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000863 case bitc::CST_CODE_STRING: { // STRING: [values]
864 if (Record.empty())
865 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000866
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000867 const ArrayType *ATy = cast<ArrayType>(CurTy);
868 const Type *EltTy = ATy->getElementType();
869
870 unsigned Size = Record.size();
871 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000872 for (unsigned i = 0; i != Size; ++i)
Owen Anderson74a77812009-07-07 20:18:58 +0000873 Elts.push_back(Context.getConstantInt(EltTy, Record[i]));
874 V = Context.getConstantArray(ATy, Elts);
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000875 break;
876 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000877 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
878 if (Record.empty())
879 return Error("Invalid CST_AGGREGATE record");
880
881 const ArrayType *ATy = cast<ArrayType>(CurTy);
882 const Type *EltTy = ATy->getElementType();
883
884 unsigned Size = Record.size();
885 std::vector<Constant*> Elts;
886 for (unsigned i = 0; i != Size; ++i)
Owen Anderson74a77812009-07-07 20:18:58 +0000887 Elts.push_back(Context.getConstantInt(EltTy, Record[i]));
888 Elts.push_back(Context.getNullValue(EltTy));
889 V = Context.getConstantArray(ATy, Elts);
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000890 break;
891 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000892 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
893 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
894 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000895 if (Opc < 0) {
Owen Anderson74a77812009-07-07 20:18:58 +0000896 V = Context.getUndef(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000897 } else {
898 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
899 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Owen Anderson74a77812009-07-07 20:18:58 +0000900 V = Context.getConstantExpr(Opc, LHS, RHS);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000901 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000902 break;
903 }
904 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
905 if (Record.size() < 3) return Error("Invalid CE_CAST record");
906 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000907 if (Opc < 0) {
Owen Anderson74a77812009-07-07 20:18:58 +0000908 V = Context.getUndef(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000909 } else {
910 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000911 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000912 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Anderson74a77812009-07-07 20:18:58 +0000913 V = Context.getConstantExprCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000914 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000915 break;
916 }
917 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000918 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000919 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000920 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000921 const Type *ElTy = getTypeByID(Record[i]);
922 if (!ElTy) return Error("Invalid CE_GEP record");
923 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
924 }
Owen Anderson74a77812009-07-07 20:18:58 +0000925 V = Context.getConstantExprGetElementPtr(Elts[0], &Elts[1],
926 Elts.size()-1);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000927 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000928 }
929 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
930 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Anderson74a77812009-07-07 20:18:58 +0000931 V = Context.getConstantExprSelect(ValueList.getConstantFwdRef(Record[0],
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000932 Type::Int1Ty),
933 ValueList.getConstantFwdRef(Record[1],CurTy),
934 ValueList.getConstantFwdRef(Record[2],CurTy));
935 break;
936 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
937 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
938 const VectorType *OpTy =
939 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
940 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
941 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerba120aa2009-02-03 02:11:28 +0000942 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Owen Anderson74a77812009-07-07 20:18:58 +0000943 V = Context.getConstantExprExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000944 break;
945 }
946 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
947 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
948 if (Record.size() < 3 || OpTy == 0)
949 return Error("Invalid CE_INSERTELT record");
950 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
951 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
952 OpTy->getElementType());
953 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Owen Anderson74a77812009-07-07 20:18:58 +0000954 V = Context.getConstantExprInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000955 break;
956 }
957 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
958 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
959 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +0000960 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000961 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
962 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson74a77812009-07-07 20:18:58 +0000963 const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
964 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000965 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson74a77812009-07-07 20:18:58 +0000966 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000967 break;
968 }
Nate Begeman0f123cf2009-02-12 21:28:33 +0000969 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
970 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
971 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
972 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
973 return Error("Invalid CE_SHUFVEC_EX record");
974 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
975 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Anderson74a77812009-07-07 20:18:58 +0000976 const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
977 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +0000978 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson74a77812009-07-07 20:18:58 +0000979 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +0000980 break;
981 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000982 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
983 if (Record.size() < 4) return Error("Invalid CE_CMP record");
984 const Type *OpTy = getTypeByID(Record[0]);
985 if (OpTy == 0) return Error("Invalid CE_CMP record");
986 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
987 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
988
989 if (OpTy->isFloatingPoint())
Owen Anderson74a77812009-07-07 20:18:58 +0000990 V = Context.getConstantExprFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +0000991 else
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +0000992 V = Context.getConstantExprICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000993 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000994 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000995 case bitc::CST_CODE_INLINEASM: {
996 if (Record.size() < 2) return Error("Invalid INLINEASM record");
997 std::string AsmStr, ConstrStr;
998 bool HasSideEffects = Record[0];
999 unsigned AsmStrSize = Record[1];
1000 if (2+AsmStrSize >= Record.size())
1001 return Error("Invalid INLINEASM record");
1002 unsigned ConstStrSize = Record[2+AsmStrSize];
1003 if (3+AsmStrSize+ConstStrSize > Record.size())
1004 return Error("Invalid INLINEASM record");
1005
1006 for (unsigned i = 0; i != AsmStrSize; ++i)
1007 AsmStr += (char)Record[2+i];
1008 for (unsigned i = 0; i != ConstStrSize; ++i)
1009 ConstrStr += (char)Record[3+AsmStrSize+i];
1010 const PointerType *PTy = cast<PointerType>(CurTy);
1011 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1012 AsmStr, ConstrStr, HasSideEffects);
1013 break;
1014 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001015 case bitc::CST_CODE_MDSTRING: {
Nick Lewycky21cc4462009-04-04 07:22:01 +00001016 unsigned MDStringLength = Record.size();
1017 SmallString<8> String;
1018 String.resize(MDStringLength);
1019 for (unsigned i = 0; i != MDStringLength; ++i)
1020 String[i] = Record[i];
Owen Anderson74a77812009-07-07 20:18:58 +00001021 V = Context.getMDString(String.c_str(), String.c_str() + MDStringLength);
Nick Lewycky21cc4462009-04-04 07:22:01 +00001022 break;
1023 }
1024 case bitc::CST_CODE_MDNODE: {
1025 if (Record.empty() || Record.size() % 2 == 1)
1026 return Error("Invalid CST_MDNODE record");
1027
1028 unsigned Size = Record.size();
Nick Lewyckycb337992009-05-10 20:57:05 +00001029 SmallVector<Value*, 8> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001030 for (unsigned i = 0; i != Size; i += 2) {
1031 const Type *Ty = getTypeByID(Record[i], false);
Nick Lewyckycb337992009-05-10 20:57:05 +00001032 if (Ty != Type::VoidTy)
Nick Lewycky3728a022009-06-01 04:42:10 +00001033 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
Nick Lewyckycb337992009-05-10 20:57:05 +00001034 else
1035 Elts.push_back(NULL);
Nick Lewycky21cc4462009-04-04 07:22:01 +00001036 }
Owen Anderson74a77812009-07-07 20:18:58 +00001037 V = Context.getMDNode(&Elts[0], Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001038 break;
1039 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001040 }
1041
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001042 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001043 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001044 }
Chris Lattnerea693df2008-08-21 02:34:16 +00001045
1046 if (NextCstNo != ValueList.size())
1047 return Error("Invalid constant reference!");
1048
1049 if (Stream.ReadBlockEnd())
1050 return Error("Error at end of constants block");
1051
1052 // Once all the constants have been read, go through and resolve forward
1053 // references.
1054 ValueList.ResolveConstantForwardRefs();
1055 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001056}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001057
Chris Lattner980e5aa2007-05-01 05:52:21 +00001058/// RememberAndSkipFunctionBody - When we see the block for a function body,
1059/// remember where it is and then skip it. This lets us lazily deserialize the
1060/// functions.
1061bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001062 // Get the function we are talking about.
1063 if (FunctionsWithBodies.empty())
1064 return Error("Insufficient function protos");
1065
1066 Function *Fn = FunctionsWithBodies.back();
1067 FunctionsWithBodies.pop_back();
1068
1069 // Save the current stream state.
1070 uint64_t CurBit = Stream.GetCurrentBitNo();
1071 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1072
1073 // Set the functions linkage to GhostLinkage so we know it is lazily
1074 // deserialized.
1075 Fn->setLinkage(GlobalValue::GhostLinkage);
1076
1077 // Skip over the function block for now.
1078 if (Stream.SkipBlock())
1079 return Error("Malformed block record");
1080 return false;
1081}
1082
Chris Lattner86697142007-05-01 05:01:34 +00001083bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001084 // Reject multiple MODULE_BLOCK's in a single bitstream.
1085 if (TheModule)
1086 return Error("Multiple MODULE_BLOCKs in same stream");
1087
Chris Lattnere17b6582007-05-05 00:17:00 +00001088 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001089 return Error("Malformed block record");
1090
1091 // Otherwise, create the module.
Owen Anderson8b477ed2009-07-01 16:58:40 +00001092 TheModule = new Module(ModuleID, Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001093
1094 SmallVector<uint64_t, 64> Record;
1095 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001096 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001097
1098 // Read all the records for this module.
1099 while (!Stream.AtEndOfStream()) {
1100 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001101 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001102 if (Stream.ReadBlockEnd())
1103 return Error("Error at end of module block");
1104
1105 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001106 ResolveGlobalAndAliasInits();
1107 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001108 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001109 if (!FunctionsWithBodies.empty())
1110 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001111
Chandler Carruth69940402007-08-04 01:51:18 +00001112 // Look for intrinsic functions which need to be upgraded at some point
1113 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1114 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001115 Function* NewFn;
1116 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001117 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1118 }
1119
Chris Lattner980e5aa2007-05-01 05:52:21 +00001120 // Force deallocation of memory for these vectors to favor the client that
1121 // want lazy deserialization.
1122 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1123 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1124 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001125 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001126 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001127
1128 if (Code == bitc::ENTER_SUBBLOCK) {
1129 switch (Stream.ReadSubBlockID()) {
1130 default: // Skip unknown content.
1131 if (Stream.SkipBlock())
1132 return Error("Malformed block record");
1133 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001134 case bitc::BLOCKINFO_BLOCK_ID:
1135 if (Stream.ReadBlockInfoBlock())
1136 return Error("Malformed BlockInfoBlock");
1137 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001138 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001139 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001140 return true;
1141 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001142 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001143 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001144 return true;
1145 break;
1146 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001147 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001148 return true;
1149 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001150 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001151 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001152 return true;
1153 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001154 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001155 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001156 return true;
1157 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001158 case bitc::FUNCTION_BLOCK_ID:
1159 // If this is the first function body we've seen, reverse the
1160 // FunctionsWithBodies list.
1161 if (!HasReversedFunctionsWithBodies) {
1162 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1163 HasReversedFunctionsWithBodies = true;
1164 }
1165
Chris Lattner980e5aa2007-05-01 05:52:21 +00001166 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001167 return true;
1168 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001169 }
1170 continue;
1171 }
1172
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001173 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001174 Stream.ReadAbbrevRecord();
1175 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001176 }
1177
1178 // Read a record.
1179 switch (Stream.ReadRecord(Code, Record)) {
1180 default: break; // Default behavior, ignore unknown content.
1181 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1182 if (Record.size() < 1)
1183 return Error("Malformed MODULE_CODE_VERSION");
1184 // Only version #0 is supported so far.
1185 if (Record[0] != 0)
1186 return Error("Unknown bitstream version!");
1187 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001188 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001189 std::string S;
1190 if (ConvertToString(Record, 0, S))
1191 return Error("Invalid MODULE_CODE_TRIPLE record");
1192 TheModule->setTargetTriple(S);
1193 break;
1194 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001195 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001196 std::string S;
1197 if (ConvertToString(Record, 0, S))
1198 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1199 TheModule->setDataLayout(S);
1200 break;
1201 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001202 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001203 std::string S;
1204 if (ConvertToString(Record, 0, S))
1205 return Error("Invalid MODULE_CODE_ASM record");
1206 TheModule->setModuleInlineAsm(S);
1207 break;
1208 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001209 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001210 std::string S;
1211 if (ConvertToString(Record, 0, S))
1212 return Error("Invalid MODULE_CODE_DEPLIB record");
1213 TheModule->addLibrary(S);
1214 break;
1215 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001216 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001217 std::string S;
1218 if (ConvertToString(Record, 0, S))
1219 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1220 SectionTable.push_back(S);
1221 break;
1222 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001223 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001224 std::string S;
1225 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001226 return Error("Invalid MODULE_CODE_GCNAME record");
1227 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001228 break;
1229 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001230 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001231 // linkage, alignment, section, visibility, threadlocal]
1232 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001233 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001234 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1235 const Type *Ty = getTypeByID(Record[0]);
1236 if (!isa<PointerType>(Ty))
1237 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001238 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001239 Ty = cast<PointerType>(Ty)->getElementType();
1240
1241 bool isConstant = Record[1];
1242 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1243 unsigned Alignment = (1 << Record[4]) >> 1;
1244 std::string Section;
1245 if (Record[5]) {
1246 if (Record[5]-1 >= SectionTable.size())
1247 return Error("Invalid section ID");
1248 Section = SectionTable[Record[5]-1];
1249 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001250 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001251 if (Record.size() > 6)
1252 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001253 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001254 if (Record.size() > 7)
1255 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001256
1257 GlobalVariable *NewGV =
Owen Andersone9b11b42009-07-08 19:03:57 +00001258 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001259 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001260 NewGV->setAlignment(Alignment);
1261 if (!Section.empty())
1262 NewGV->setSection(Section);
1263 NewGV->setVisibility(Visibility);
1264 NewGV->setThreadLocal(isThreadLocal);
1265
Chris Lattner0b2482a2007-04-23 21:26:05 +00001266 ValueList.push_back(NewGV);
1267
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001268 // Remember which value to use for the global initializer.
1269 if (unsigned InitID = Record[2])
1270 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001271 break;
1272 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001273 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001274 // alignment, section, visibility, gc]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001275 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001276 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001277 return Error("Invalid MODULE_CODE_FUNCTION record");
1278 const Type *Ty = getTypeByID(Record[0]);
1279 if (!isa<PointerType>(Ty))
1280 return Error("Function not a pointer type!");
1281 const FunctionType *FTy =
1282 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1283 if (!FTy)
1284 return Error("Function not a pointer to function type!");
1285
Gabor Greif051a9502008-04-06 20:25:17 +00001286 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1287 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001288
1289 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001290 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001291 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001292 Func->setAttributes(getAttributes(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001293
1294 Func->setAlignment((1 << Record[5]) >> 1);
1295 if (Record[6]) {
1296 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001297 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001298 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001299 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001300 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001301 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001302 if (Record[8]-1 > GCTable.size())
1303 return Error("Invalid GC ID");
1304 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001305 }
Chris Lattner0b2482a2007-04-23 21:26:05 +00001306 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001307
1308 // If this is a function with a body, remember the prototype we are
1309 // creating now, so that we can match up the body with them later.
1310 if (!isProto)
1311 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001312 break;
1313 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001314 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001315 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001316 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001317 if (Record.size() < 3)
1318 return Error("Invalid MODULE_ALIAS record");
1319 const Type *Ty = getTypeByID(Record[0]);
1320 if (!isa<PointerType>(Ty))
1321 return Error("Function not a pointer type!");
1322
1323 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1324 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001325 // Old bitcode files didn't have visibility field.
1326 if (Record.size() > 3)
1327 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001328 ValueList.push_back(NewGA);
1329 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1330 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001331 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001332 /// MODULE_CODE_PURGEVALS: [numvals]
1333 case bitc::MODULE_CODE_PURGEVALS:
1334 // Trim down the value list to the specified size.
1335 if (Record.size() < 1 || Record[0] > ValueList.size())
1336 return Error("Invalid MODULE_PURGEVALS record");
1337 ValueList.shrinkTo(Record[0]);
1338 break;
1339 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001340 Record.clear();
1341 }
1342
1343 return Error("Premature end of bitstream");
1344}
1345
Chris Lattnerc453f762007-04-29 07:54:31 +00001346bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001347 TheModule = 0;
1348
Chris Lattnerc453f762007-04-29 07:54:31 +00001349 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001350 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1351
Chris Lattnerc453f762007-04-29 07:54:31 +00001352 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001353 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1354
1355 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1356 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnere2a466b2009-04-06 20:54:32 +00001357 if (isBitcodeWrapper(BufPtr, BufEnd))
1358 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner6fa6a322008-07-09 05:14:23 +00001359 return Error("Invalid bitcode wrapper header");
1360
Chris Lattner962dde32009-04-26 20:59:02 +00001361 StreamFile.init(BufPtr, BufEnd);
1362 Stream.init(StreamFile);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001363
1364 // Sniff for the signature.
1365 if (Stream.Read(8) != 'B' ||
1366 Stream.Read(8) != 'C' ||
1367 Stream.Read(4) != 0x0 ||
1368 Stream.Read(4) != 0xC ||
1369 Stream.Read(4) != 0xE ||
1370 Stream.Read(4) != 0xD)
1371 return Error("Invalid bitcode signature");
1372
1373 // We expect a number of well-defined blocks, though we don't necessarily
1374 // need to understand them all.
1375 while (!Stream.AtEndOfStream()) {
1376 unsigned Code = Stream.ReadCode();
1377
1378 if (Code != bitc::ENTER_SUBBLOCK)
1379 return Error("Invalid record at top-level");
1380
1381 unsigned BlockID = Stream.ReadSubBlockID();
1382
1383 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001384 switch (BlockID) {
1385 case bitc::BLOCKINFO_BLOCK_ID:
1386 if (Stream.ReadBlockInfoBlock())
1387 return Error("Malformed BlockInfoBlock");
1388 break;
1389 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001390 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001391 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001392 break;
1393 default:
1394 if (Stream.SkipBlock())
1395 return Error("Malformed block record");
1396 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001397 }
1398 }
1399
1400 return false;
1401}
Chris Lattnerc453f762007-04-29 07:54:31 +00001402
Chris Lattner48f84872007-05-01 04:59:48 +00001403
Chris Lattner980e5aa2007-05-01 05:52:21 +00001404/// ParseFunctionBody - Lazily parse the specified function body block.
1405bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001406 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001407 return Error("Malformed block record");
1408
1409 unsigned ModuleValueListSize = ValueList.size();
1410
1411 // Add all the function arguments to the value table.
1412 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1413 ValueList.push_back(I);
1414
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001415 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001416 BasicBlock *CurBB = 0;
1417 unsigned CurBBNo = 0;
1418
Chris Lattner980e5aa2007-05-01 05:52:21 +00001419 // Read all the records.
1420 SmallVector<uint64_t, 64> Record;
1421 while (1) {
1422 unsigned Code = Stream.ReadCode();
1423 if (Code == bitc::END_BLOCK) {
1424 if (Stream.ReadBlockEnd())
1425 return Error("Error at end of function block");
1426 break;
1427 }
1428
1429 if (Code == bitc::ENTER_SUBBLOCK) {
1430 switch (Stream.ReadSubBlockID()) {
1431 default: // Skip unknown content.
1432 if (Stream.SkipBlock())
1433 return Error("Malformed block record");
1434 break;
1435 case bitc::CONSTANTS_BLOCK_ID:
1436 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001437 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001438 break;
1439 case bitc::VALUE_SYMTAB_BLOCK_ID:
1440 if (ParseValueSymbolTable()) return true;
1441 break;
1442 }
1443 continue;
1444 }
1445
1446 if (Code == bitc::DEFINE_ABBREV) {
1447 Stream.ReadAbbrevRecord();
1448 continue;
1449 }
1450
1451 // Read a record.
1452 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001453 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001454 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001455 default: // Default behavior: reject
1456 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001457 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001458 if (Record.size() < 1 || Record[0] == 0)
1459 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001460 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001461 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001462 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001463 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001464 CurBB = FunctionBBs[0];
1465 continue;
1466
Chris Lattnerabfbf852007-05-06 00:21:25 +00001467 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1468 unsigned OpNum = 0;
1469 Value *LHS, *RHS;
1470 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1471 getValue(Record, OpNum, LHS->getType(), RHS) ||
1472 OpNum+1 != Record.size())
1473 return Error("Invalid BINOP record");
1474
1475 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1476 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001477 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001478 break;
1479 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001480 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1481 unsigned OpNum = 0;
1482 Value *Op;
1483 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1484 OpNum+2 != Record.size())
1485 return Error("Invalid CAST record");
1486
1487 const Type *ResTy = getTypeByID(Record[OpNum]);
1488 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1489 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001490 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001491 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Chris Lattner231cbcb2007-05-02 04:27:25 +00001492 break;
1493 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001494 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001495 unsigned OpNum = 0;
1496 Value *BasePtr;
1497 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001498 return Error("Invalid GEP record");
1499
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001500 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001501 while (OpNum != Record.size()) {
1502 Value *Op;
1503 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001504 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001505 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001506 }
1507
Gabor Greif051a9502008-04-06 20:25:17 +00001508 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001509 break;
1510 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001511
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001512 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1513 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001514 unsigned OpNum = 0;
1515 Value *Agg;
1516 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1517 return Error("Invalid EXTRACTVAL record");
1518
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001519 SmallVector<unsigned, 4> EXTRACTVALIdx;
1520 for (unsigned RecSize = Record.size();
1521 OpNum != RecSize; ++OpNum) {
1522 uint64_t Index = Record[OpNum];
1523 if ((unsigned)Index != Index)
1524 return Error("Invalid EXTRACTVAL index");
1525 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001526 }
1527
1528 I = ExtractValueInst::Create(Agg,
1529 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1530 break;
1531 }
1532
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001533 case bitc::FUNC_CODE_INST_INSERTVAL: {
1534 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001535 unsigned OpNum = 0;
1536 Value *Agg;
1537 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1538 return Error("Invalid INSERTVAL record");
1539 Value *Val;
1540 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1541 return Error("Invalid INSERTVAL record");
1542
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001543 SmallVector<unsigned, 4> INSERTVALIdx;
1544 for (unsigned RecSize = Record.size();
1545 OpNum != RecSize; ++OpNum) {
1546 uint64_t Index = Record[OpNum];
1547 if ((unsigned)Index != Index)
1548 return Error("Invalid INSERTVAL index");
1549 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001550 }
1551
1552 I = InsertValueInst::Create(Agg, Val,
1553 INSERTVALIdx.begin(), INSERTVALIdx.end());
1554 break;
1555 }
1556
Chris Lattnerabfbf852007-05-06 00:21:25 +00001557 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001558 // obsolete form of select
1559 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00001560 unsigned OpNum = 0;
1561 Value *TrueVal, *FalseVal, *Cond;
1562 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1563 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Dan Gohmanbe919402008-09-09 02:08:49 +00001564 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001565 return Error("Invalid SELECT record");
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001566
1567 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1568 break;
1569 }
1570
1571 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1572 // new form of select
1573 // handles select i1 or select [N x i1]
1574 unsigned OpNum = 0;
1575 Value *TrueVal, *FalseVal, *Cond;
1576 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1577 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1578 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1579 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00001580
1581 // select condition can be either i1 or [N x i1]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001582 if (const VectorType* vector_type =
1583 dyn_cast<const VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00001584 // expect <n x i1>
1585 if (vector_type->getElementType() != Type::Int1Ty)
1586 return Error("Invalid SELECT condition type");
1587 } else {
1588 // expect i1
1589 if (Cond->getType() != Type::Int1Ty)
1590 return Error("Invalid SELECT condition type");
1591 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001592
Gabor Greif051a9502008-04-06 20:25:17 +00001593 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001594 break;
1595 }
1596
1597 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001598 unsigned OpNum = 0;
1599 Value *Vec, *Idx;
1600 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1601 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001602 return Error("Invalid EXTRACTELT record");
1603 I = new ExtractElementInst(Vec, Idx);
1604 break;
1605 }
1606
1607 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001608 unsigned OpNum = 0;
1609 Value *Vec, *Elt, *Idx;
1610 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1611 getValue(Record, OpNum,
1612 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1613 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001614 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001615 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001616 break;
1617 }
1618
Chris Lattnerabfbf852007-05-06 00:21:25 +00001619 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1620 unsigned OpNum = 0;
1621 Value *Vec1, *Vec2, *Mask;
1622 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1623 getValue(Record, OpNum, Vec1->getType(), Vec2))
1624 return Error("Invalid SHUFFLEVEC record");
1625
Mon P Wangaeb06d22008-11-10 04:46:22 +00001626 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001627 return Error("Invalid SHUFFLEVEC record");
1628 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1629 break;
1630 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001631
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001632 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
1633 // Old form of ICmp/FCmp returning bool
1634 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1635 // both legal on vectors but had different behaviour.
1636 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1637 // FCmp/ICmp returning bool or vector of bool
1638
Chris Lattner7337ab92007-05-06 00:00:00 +00001639 unsigned OpNum = 0;
1640 Value *LHS, *RHS;
1641 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1642 getValue(Record, OpNum, LHS->getType(), RHS) ||
1643 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001644 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001645
Dan Gohmanf72fb672008-09-09 01:02:47 +00001646 if (LHS->getType()->isFPOrFPVector())
Owen Anderson333c4002009-07-09 23:48:35 +00001647 I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001648 else
Owen Anderson333c4002009-07-09 23:48:35 +00001649 I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Dan Gohmanf72fb672008-09-09 01:02:47 +00001650 break;
1651 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001652
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))) {
Owen Anderson74a77812009-07-07 20:18:58 +00001685 Value *RV = Context.getUndef(ReturnType);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001686 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");
Owen Anderson50dead02009-07-15 23:53:25 +00001821 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001822 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");
Owen Anderson50dead02009-07-15 23:53:25 +00001841 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001842 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) ||
Owen Anderson74a77812009-07-07 20:18:58 +00001871 getValue(Record, OpNum,
1872 Context.getPointerTypeUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001873 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001874 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001875
1876 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001877 break;
1878 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001879 case bitc::FUNC_CODE_INST_CALL: {
1880 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1881 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001882 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001883
Devang Patel05988662008-09-25 21:00:45 +00001884 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001885 unsigned CCInfo = Record[1];
1886
1887 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001888 Value *Callee;
1889 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1890 return Error("Invalid CALL record");
1891
1892 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001893 const FunctionType *FTy = 0;
1894 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001895 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001896 return Error("Invalid CALL record");
1897
1898 SmallVector<Value*, 16> Args;
1899 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001900 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001901 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1902 Args.push_back(getBasicBlock(Record[OpNum]));
1903 else
1904 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001905 if (Args.back() == 0) return Error("Invalid CALL record");
1906 }
1907
Chris Lattner0579f7f2007-05-03 22:04:19 +00001908 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001909 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001910 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001911 return Error("Invalid CALL record");
1912 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001913 while (OpNum != Record.size()) {
1914 Value *Op;
1915 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1916 return Error("Invalid CALL record");
1917 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001918 }
1919 }
1920
Gabor Greif051a9502008-04-06 20:25:17 +00001921 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001922 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1923 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00001924 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001925 break;
1926 }
1927 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1928 if (Record.size() < 3)
1929 return Error("Invalid VAARG record");
1930 const Type *OpTy = getTypeByID(Record[0]);
1931 Value *Op = getFnValueByID(Record[1], OpTy);
1932 const Type *ResTy = getTypeByID(Record[2]);
1933 if (!OpTy || !Op || !ResTy)
1934 return Error("Invalid VAARG record");
1935 I = new VAArgInst(Op, ResTy);
1936 break;
1937 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001938 }
1939
1940 // Add instruction to end of current BB. If there is no current BB, reject
1941 // this file.
1942 if (CurBB == 0) {
1943 delete I;
1944 return Error("Invalid instruction with no BB");
1945 }
1946 CurBB->getInstList().push_back(I);
1947
1948 // If this was a terminator instruction, move to the next block.
1949 if (isa<TerminatorInst>(I)) {
1950 ++CurBBNo;
1951 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1952 }
1953
1954 // Non-void values get registered in the value table for future use.
1955 if (I && I->getType() != Type::VoidTy)
1956 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001957 }
1958
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001959 // Check the function list for unresolved values.
1960 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1961 if (A->getParent() == 0) {
1962 // We found at least one unresolved value. Nuke them all to avoid leaks.
1963 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1964 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
Owen Anderson74a77812009-07-07 20:18:58 +00001965 A->replaceAllUsesWith(Context.getUndef(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001966 delete A;
1967 }
1968 }
Chris Lattner35a04702007-05-04 03:50:29 +00001969 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001970 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001971 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001972
1973 // Trim the value list down to the size it was before we parsed this function.
1974 ValueList.shrinkTo(ModuleValueListSize);
1975 std::vector<BasicBlock*>().swap(FunctionBBs);
1976
Chris Lattner48f84872007-05-01 04:59:48 +00001977 return false;
1978}
1979
Chris Lattnerb348bb82007-05-18 04:02:46 +00001980//===----------------------------------------------------------------------===//
1981// ModuleProvider implementation
1982//===----------------------------------------------------------------------===//
1983
1984
1985bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1986 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001987 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001988
1989 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1990 DeferredFunctionInfo.find(F);
1991 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1992
1993 // Move the bit stream to the saved position of the deferred function body and
1994 // restore the real linkage type for the function.
1995 Stream.JumpToBit(DFII->second.first);
1996 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1997
1998 if (ParseFunctionBody(F)) {
1999 if (ErrInfo) *ErrInfo = ErrorString;
2000 return true;
2001 }
Chandler Carruth69940402007-08-04 01:51:18 +00002002
2003 // Upgrade any old intrinsic calls in the function.
2004 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2005 E = UpgradedIntrinsics.end(); I != E; ++I) {
2006 if (I->first != I->second) {
2007 for (Value::use_iterator UI = I->first->use_begin(),
2008 UE = I->first->use_end(); UI != UE; ) {
2009 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2010 UpgradeIntrinsicCall(CI, I->second);
2011 }
2012 }
2013 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00002014
2015 return false;
2016}
2017
2018void BitcodeReader::dematerializeFunction(Function *F) {
2019 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00002020 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00002021 return;
2022
2023 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2024
2025 // Just forget the function body, we can remat it later.
2026 F->deleteBody();
2027 F->setLinkage(GlobalValue::GhostLinkage);
2028}
2029
2030
2031Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
Chris Lattner714fa952009-06-16 05:15:21 +00002032 // Iterate over the module, deserializing any functions that are still on
2033 // disk.
2034 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2035 F != E; ++F)
Gabor Greifa99be512007-07-05 17:07:56 +00002036 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00002037 materializeFunction(F, ErrInfo))
2038 return 0;
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,
Owen Anderson4434ed42009-07-01 23:13:44 +00002082 LLVMContext& Context,
Chris Lattnerc453f762007-04-29 07:54:31 +00002083 std::string *ErrMsg) {
Owen Anderson8b477ed2009-07-01 16:58:40 +00002084 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Chris Lattnerc453f762007-04-29 07:54:31 +00002085 if (R->ParseBitcode()) {
2086 if (ErrMsg)
2087 *ErrMsg = R->getErrorString();
2088
2089 // Don't let the BitcodeReader dtor delete 'Buffer'.
2090 R->releaseMemoryBuffer();
2091 delete R;
2092 return 0;
2093 }
2094 return R;
2095}
2096
2097/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2098/// If an error occurs, return null and fill in *ErrMsg if non-null.
Owen Anderson4434ed42009-07-01 23:13:44 +00002099Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002100 std::string *ErrMsg){
Chris Lattnerc453f762007-04-29 07:54:31 +00002101 BitcodeReader *R;
Owen Anderson8b477ed2009-07-01 16:58:40 +00002102 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
2103 ErrMsg));
Chris Lattnerc453f762007-04-29 07:54:31 +00002104 if (!R) return 0;
2105
Chris Lattnerb348bb82007-05-18 04:02:46 +00002106 // Read in the entire module.
2107 Module *M = R->materializeModule(ErrMsg);
2108
2109 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2110 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00002111 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002112
2113 // If there was no error, tell ModuleProvider not to delete it when its dtor
2114 // is run.
2115 if (M)
2116 M = R->releaseModule(ErrMsg);
Chris Lattner714fa952009-06-16 05:15:21 +00002117
Chris Lattnerc453f762007-04-29 07:54:31 +00002118 delete R;
2119 return M;
2120}