blob: 76d112e045a3fd6b4cf6090559be70ae44bfb859 [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"
Devang Patele4b27562009-08-28 23:24:31 +000019#include "llvm/IntrinsicInst.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000021#include "llvm/Operator.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000024#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000025#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000026#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000027#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000028using namespace llvm;
29
Chris Lattnerb348bb82007-05-18 04:02:46 +000030void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000031 if (BufferOwned)
32 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000033 Buffer = 0;
34 std::vector<PATypeHolder>().swap(TypeList);
35 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000036 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000037
Devang Patel19c87462008-09-26 22:53:05 +000038 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000039 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000042}
43
Chris Lattner48c85b82007-05-04 03:30:17 +000044//===----------------------------------------------------------------------===//
45// Helper functions to implement forward reference resolution, etc.
46//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000047
Chris Lattnercaee0dc2007-04-22 06:23:29 +000048/// ConvertToString - Convert a string from a record into an std::string, return
49/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000050template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000051static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000052 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000053 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000054 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000055
Chris Lattner15e6d172007-05-04 19:11:41 +000056 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
57 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000058 return false;
59}
60
61static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
62 switch (Val) {
63 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000064 case 0: return GlobalValue::ExternalLinkage;
65 case 1: return GlobalValue::WeakAnyLinkage;
66 case 2: return GlobalValue::AppendingLinkage;
67 case 3: return GlobalValue::InternalLinkage;
68 case 4: return GlobalValue::LinkOnceAnyLinkage;
69 case 5: return GlobalValue::DLLImportLinkage;
70 case 6: return GlobalValue::DLLExportLinkage;
71 case 7: return GlobalValue::ExternalWeakLinkage;
72 case 8: return GlobalValue::CommonLinkage;
73 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000074 case 10: return GlobalValue::WeakODRLinkage;
75 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000076 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000077 case 13: return GlobalValue::LinkerPrivateLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000078 }
79}
80
81static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
82 switch (Val) {
83 default: // Map unknown visibilities to default.
84 case 0: return GlobalValue::DefaultVisibility;
85 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000086 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000087 }
88}
89
Chris Lattnerf581c3b2007-04-24 07:07:11 +000090static int GetDecodedCastOpcode(unsigned Val) {
91 switch (Val) {
92 default: return -1;
93 case bitc::CAST_TRUNC : return Instruction::Trunc;
94 case bitc::CAST_ZEXT : return Instruction::ZExt;
95 case bitc::CAST_SEXT : return Instruction::SExt;
96 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
97 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
98 case bitc::CAST_UITOFP : return Instruction::UIToFP;
99 case bitc::CAST_SITOFP : return Instruction::SIToFP;
100 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
101 case bitc::CAST_FPEXT : return Instruction::FPExt;
102 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
103 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
104 case bitc::CAST_BITCAST : return Instruction::BitCast;
105 }
106}
107static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
108 switch (Val) {
109 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000110 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000111 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000112 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000113 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000114 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000115 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000116 case bitc::BINOP_UDIV: return Instruction::UDiv;
117 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000118 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000119 case bitc::BINOP_UREM: return Instruction::URem;
120 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000121 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000122 case bitc::BINOP_SHL: return Instruction::Shl;
123 case bitc::BINOP_LSHR: return Instruction::LShr;
124 case bitc::BINOP_ASHR: return Instruction::AShr;
125 case bitc::BINOP_AND: return Instruction::And;
126 case bitc::BINOP_OR: return Instruction::Or;
127 case bitc::BINOP_XOR: return Instruction::Xor;
128 }
129}
130
Gabor Greifefe65362008-05-10 08:32:32 +0000131namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000132namespace {
133 /// @brief A class for maintaining the slot number definition
134 /// as a placeholder for the actual definition for forward constants defs.
135 class ConstantPlaceHolder : public ConstantExpr {
136 ConstantPlaceHolder(); // DO NOT IMPLEMENT
137 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000138 public:
139 // allocate space for exactly one operand
140 void *operator new(size_t s) {
141 return User::operator new(s, 1);
142 }
Owen Anderson74a77812009-07-07 20:18:58 +0000143 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000144 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000145 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000146 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000147
Chris Lattnerea693df2008-08-21 02:34:16 +0000148 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
149 static inline bool classof(const ConstantPlaceHolder *) { return true; }
150 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000151 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000152 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
153 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000154
155
Gabor Greifefe65362008-05-10 08:32:32 +0000156 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000157 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000158 };
159}
160
Chris Lattner46e77402009-03-31 22:55:09 +0000161// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000162template <>
Duncan Sands59bf4fc2009-09-06 08:55:57 +0000163struct OperandTraits<ConstantPlaceHolder> : public FixedNumOperandTraits<1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000164};
Gabor Greifefe65362008-05-10 08:32:32 +0000165}
166
Chris Lattner46e77402009-03-31 22:55:09 +0000167
168void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
169 if (Idx == size()) {
170 push_back(V);
171 return;
172 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000173
Chris Lattner46e77402009-03-31 22:55:09 +0000174 if (Idx >= size())
175 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000176
Chris Lattner46e77402009-03-31 22:55:09 +0000177 WeakVH &OldV = ValuePtrs[Idx];
178 if (OldV == 0) {
179 OldV = V;
180 return;
181 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000182
Chris Lattner46e77402009-03-31 22:55:09 +0000183 // Handle constants and non-constants (e.g. instrs) differently for
184 // efficiency.
185 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
186 ResolveConstants.push_back(std::make_pair(PHC, Idx));
187 OldV = V;
188 } else {
189 // If there was a forward reference to this value, replace it.
190 Value *PrevVal = OldV;
191 OldV->replaceAllUsesWith(V);
192 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000193 }
194}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000195
Gabor Greifefe65362008-05-10 08:32:32 +0000196
Chris Lattner522b7b12007-04-24 05:48:56 +0000197Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
198 const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000199 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000200 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000201
Chris Lattner46e77402009-03-31 22:55:09 +0000202 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000203 assert(Ty == V->getType() && "Type mismatch in constant table!");
204 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000205 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000206
207 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000208 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000209 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000210 return C;
211}
212
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000213Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000214 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000215 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000216
Chris Lattner46e77402009-03-31 22:55:09 +0000217 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000218 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
219 return V;
220 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000221
Chris Lattner01ff65f2007-05-02 05:16:49 +0000222 // No type specified, must be invalid reference.
223 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000224
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000225 // Create and return a placeholder, which will later be RAUW'd.
226 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000227 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000228 return V;
229}
230
Chris Lattnerea693df2008-08-21 02:34:16 +0000231/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
232/// resolves any forward references. The idea behind this is that we sometimes
233/// get constants (such as large arrays) which reference *many* forward ref
234/// constants. Replacing each of these causes a lot of thrashing when
235/// building/reuniquing the constant. Instead of doing this, we look at all the
236/// uses and rewrite all the place holders at once for any constant that uses
237/// a placeholder.
238void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000239 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000240 // binary search.
241 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000242
Chris Lattnerea693df2008-08-21 02:34:16 +0000243 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000244
Chris Lattnerea693df2008-08-21 02:34:16 +0000245 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000246 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000247 Constant *Placeholder = ResolveConstants.back().first;
248 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000249
Chris Lattnerea693df2008-08-21 02:34:16 +0000250 // Loop over all users of the placeholder, updating them to reference the
251 // new value. If they reference more than one placeholder, update them all
252 // at once.
253 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000254 Value::use_iterator UI = Placeholder->use_begin();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000255
Chris Lattnerea693df2008-08-21 02:34:16 +0000256 // If the using object isn't uniqued, just update the operands. This
257 // handles instructions and initializers for global variables.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000258 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
259 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000260 continue;
261 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000262
Chris Lattnerea693df2008-08-21 02:34:16 +0000263 // Otherwise, we have a constant that uses the placeholder. Replace that
264 // constant with a new constant that has *all* placeholder uses updated.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000265 Constant *UserC = cast<Constant>(*UI);
Chris Lattnerea693df2008-08-21 02:34:16 +0000266 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
267 I != E; ++I) {
268 Value *NewOp;
269 if (!isa<ConstantPlaceHolder>(*I)) {
270 // Not a placeholder reference.
271 NewOp = *I;
272 } else if (*I == Placeholder) {
273 // Common case is that it just references this one placeholder.
274 NewOp = RealVal;
275 } else {
276 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000277 ResolveConstantsTy::iterator It =
278 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000279 std::pair<Constant*, unsigned>(cast<Constant>(*I),
280 0));
281 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000282 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000283 }
284
285 NewOps.push_back(cast<Constant>(NewOp));
286 }
287
288 // Make the new constant.
289 Constant *NewC;
290 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Owen Anderson1fd70962009-07-28 18:32:17 +0000291 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
Owen Anderson74a77812009-07-07 20:18:58 +0000292 NewOps.size());
Chris Lattnerea693df2008-08-21 02:34:16 +0000293 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000294 NewC = ConstantStruct::get(Context, &NewOps[0], NewOps.size(),
Owen Anderson74a77812009-07-07 20:18:58 +0000295 UserCS->getType()->isPacked());
Chris Lattner93b122d2010-03-16 21:25:55 +0000296 } else if (ConstantUnion *UserCU = dyn_cast<ConstantUnion>(UserC)) {
297 NewC = ConstantUnion::get(UserCU->getType(), NewOps[0]);
Chris Lattnerea693df2008-08-21 02:34:16 +0000298 } else if (isa<ConstantVector>(UserC)) {
Owen Andersonaf7ec972009-07-28 21:19:26 +0000299 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
Nick Lewyckycb337992009-05-10 20:57:05 +0000300 } else {
301 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Chris Lattnerea693df2008-08-21 02:34:16 +0000302 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
303 NewOps.size());
304 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 UserC->replaceAllUsesWith(NewC);
307 UserC->destroyConstant();
308 NewOps.clear();
309 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000310
Nick Lewyckycb337992009-05-10 20:57:05 +0000311 // Update all ValueHandles, they should be the only users at this point.
312 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000313 delete Placeholder;
314 }
315}
316
Devang Pateld5ac4042009-08-04 06:00:18 +0000317void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
318 if (Idx == size()) {
319 push_back(V);
320 return;
321 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000322
Devang Pateld5ac4042009-08-04 06:00:18 +0000323 if (Idx >= size())
324 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000325
Devang Pateld5ac4042009-08-04 06:00:18 +0000326 WeakVH &OldV = MDValuePtrs[Idx];
327 if (OldV == 0) {
328 OldV = V;
329 return;
330 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331
Devang Pateld5ac4042009-08-04 06:00:18 +0000332 // If there was a forward reference to this value, replace it.
333 Value *PrevVal = OldV;
334 OldV->replaceAllUsesWith(V);
335 delete PrevVal;
Devang Patelc0ff8c82009-09-03 01:38:02 +0000336 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
337 // value for Idx.
338 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000339}
340
341Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
342 if (Idx >= size())
343 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000344
Devang Pateld5ac4042009-08-04 06:00:18 +0000345 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000346 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000347 return V;
348 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000349
Devang Pateld5ac4042009-08-04 06:00:18 +0000350 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson1d0be152009-08-13 21:58:54 +0000351 Value *V = new Argument(Type::getMetadataTy(Context));
Devang Pateld5ac4042009-08-04 06:00:18 +0000352 MDValuePtrs[Idx] = V;
353 return V;
354}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000355
356const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
357 // If the TypeID is in range, return it.
358 if (ID < TypeList.size())
359 return TypeList[ID].get();
360 if (!isTypeTable) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000361
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000362 // The type table allows forward references. Push as many Opaque types as
363 // needed to get up to ID.
364 while (TypeList.size() <= ID)
Owen Anderson0e275dc2009-08-13 23:27:32 +0000365 TypeList.push_back(OpaqueType::get(Context));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000366 return TypeList.back().get();
367}
368
Chris Lattner48c85b82007-05-04 03:30:17 +0000369//===----------------------------------------------------------------------===//
370// Functions for parsing blocks from the bitcode file
371//===----------------------------------------------------------------------===//
372
Devang Patel05988662008-09-25 21:00:45 +0000373bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000374 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000375 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000376
Devang Patel19c87462008-09-26 22:53:05 +0000377 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000378 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Chris Lattner48c85b82007-05-04 03:30:17 +0000380 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000381
Devang Patel05988662008-09-25 21:00:45 +0000382 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000383
Chris Lattner48c85b82007-05-04 03:30:17 +0000384 // Read all the records.
385 while (1) {
386 unsigned Code = Stream.ReadCode();
387 if (Code == bitc::END_BLOCK) {
388 if (Stream.ReadBlockEnd())
389 return Error("Error at end of PARAMATTR block");
390 return false;
391 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000392
Chris Lattner48c85b82007-05-04 03:30:17 +0000393 if (Code == bitc::ENTER_SUBBLOCK) {
394 // No known subblocks, always skip them.
395 Stream.ReadSubBlockID();
396 if (Stream.SkipBlock())
397 return Error("Malformed block record");
398 continue;
399 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000400
Chris Lattner48c85b82007-05-04 03:30:17 +0000401 if (Code == bitc::DEFINE_ABBREV) {
402 Stream.ReadAbbrevRecord();
403 continue;
404 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000405
Chris Lattner48c85b82007-05-04 03:30:17 +0000406 // Read a record.
407 Record.clear();
408 switch (Stream.ReadRecord(Code, Record)) {
409 default: // Default behavior: ignore.
410 break;
411 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
412 if (Record.size() & 1)
413 return Error("Invalid ENTRY record");
414
Chris Lattner9a6cb152008-10-05 18:22:09 +0000415 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000416 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000417 // to index ~0. Index 0 is used for return value attributes but used to be
418 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000419 Attributes RetAttribute = Attribute::None;
420 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000421 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000422 // FIXME: remove in LLVM 3.0
423 // The alignment is stored as a 16-bit raw value from bits 31--16.
424 // We shift the bits above 31 down by 11 bits.
425
426 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
427 if (Alignment && !isPowerOf2_32(Alignment))
428 return Error("Alignment is not a power of two.");
429
430 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
431 if (Alignment)
432 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
433 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
434 Record[i+1] = ReconstitutedAttr;
435
Devang Patel19c87462008-09-26 22:53:05 +0000436 if (Record[i] == 0)
437 RetAttribute = Record[i+1];
438 else if (Record[i] == ~0U)
439 FnAttribute = Record[i+1];
440 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000441
442 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
443 Attribute::ReadOnly|Attribute::ReadNone);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000444
Chris Lattner9a6cb152008-10-05 18:22:09 +0000445 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
446 (RetAttribute & OldRetAttrs) != 0) {
447 if (FnAttribute == Attribute::None) { // add a slot so they get added.
448 Record.push_back(~0U);
449 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000450 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000451
Chris Lattner9a6cb152008-10-05 18:22:09 +0000452 FnAttribute |= RetAttribute & OldRetAttrs;
453 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000454 }
Chris Lattner461edd92008-03-12 02:25:52 +0000455
Devang Patel19c87462008-09-26 22:53:05 +0000456 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000457 if (Record[i] == 0) {
458 if (RetAttribute != Attribute::None)
459 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
460 } else if (Record[i] == ~0U) {
461 if (FnAttribute != Attribute::None)
462 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
463 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000464 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
465 }
Devang Patel19c87462008-09-26 22:53:05 +0000466
467 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000468 Attrs.clear();
469 break;
470 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000471 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000472 }
473}
474
475
Chris Lattner86697142007-05-01 05:01:34 +0000476bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000477 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000478 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000480 if (!TypeList.empty())
481 return Error("Multiple TYPE_BLOCKs found!");
482
483 SmallVector<uint64_t, 64> Record;
484 unsigned NumRecords = 0;
485
486 // Read all the records for this type table.
487 while (1) {
488 unsigned Code = Stream.ReadCode();
489 if (Code == bitc::END_BLOCK) {
490 if (NumRecords != TypeList.size())
491 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000492 if (Stream.ReadBlockEnd())
493 return Error("Error at end of type table block");
494 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000495 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000496
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000497 if (Code == bitc::ENTER_SUBBLOCK) {
498 // No known subblocks, always skip them.
499 Stream.ReadSubBlockID();
500 if (Stream.SkipBlock())
501 return Error("Malformed block record");
502 continue;
503 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000504
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000505 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000506 Stream.ReadAbbrevRecord();
507 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000508 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000509
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000510 // Read a record.
511 Record.clear();
512 const Type *ResultTy = 0;
513 switch (Stream.ReadRecord(Code, Record)) {
514 default: // Default behavior: unknown type.
515 ResultTy = 0;
516 break;
517 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
518 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
519 // type list. This allows us to reserve space.
520 if (Record.size() < 1)
521 return Error("Invalid TYPE_CODE_NUMENTRY record");
522 TypeList.reserve(Record[0]);
523 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000524 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000525 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000526 break;
527 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000528 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000529 break;
530 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000531 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000532 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000533 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000534 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000535 break;
536 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000537 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000538 break;
539 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000540 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000541 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000542 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000543 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000544 break;
545 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
546 ResultTy = 0;
547 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000548 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000549 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000550 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000551 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
552 if (Record.size() < 1)
553 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000554
Owen Anderson1d0be152009-08-13 21:58:54 +0000555 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000556 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000557 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000558 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000559 if (Record.size() < 1)
560 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000561 unsigned AddressSpace = 0;
562 if (Record.size() == 2)
563 AddressSpace = Record[1];
Owen Andersondebcb012009-07-29 22:17:13 +0000564 ResultTy = PointerType::get(getTypeByID(Record[0], true),
Owen Anderson74a77812009-07-07 20:18:58 +0000565 AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000566 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000567 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000568 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000569 // FIXME: attrid is dead, remove it in LLVM 3.0
570 // FUNCTION: [vararg, attrid, retty, paramty x N]
571 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000572 return Error("Invalid FUNCTION type record");
573 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000574 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000575 ArgTys.push_back(getTypeByID(Record[i], true));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000576
Owen Andersondebcb012009-07-29 22:17:13 +0000577 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000578 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000579 break;
580 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000581 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000582 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 return Error("Invalid STRUCT type record");
584 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000585 for (unsigned i = 1, e = Record.size(); i != e; ++i)
586 EltTys.push_back(getTypeByID(Record[i], true));
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000587 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000588 break;
589 }
Chris Lattnerfdfeb692010-02-12 20:49:41 +0000590 case bitc::TYPE_CODE_UNION: { // UNION: [eltty x N]
591 SmallVector<const Type*, 8> EltTys;
592 for (unsigned i = 0, e = Record.size(); i != e; ++i)
593 EltTys.push_back(getTypeByID(Record[i], true));
594 ResultTy = UnionType::get(&EltTys[0], EltTys.size());
595 break;
596 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000597 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
598 if (Record.size() < 2)
599 return Error("Invalid ARRAY type record");
Owen Andersondebcb012009-07-29 22:17:13 +0000600 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000601 break;
602 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
603 if (Record.size() < 2)
604 return Error("Invalid VECTOR type record");
Owen Andersondebcb012009-07-29 22:17:13 +0000605 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000606 break;
607 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000608
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000609 if (NumRecords == TypeList.size()) {
610 // If this is a new type slot, just append it.
Owen Anderson0e275dc2009-08-13 23:27:32 +0000611 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000612 ++NumRecords;
613 } else if (ResultTy == 0) {
614 // Otherwise, this was forward referenced, so an opaque type was created,
615 // but the result type is actually just an opaque. Leave the one we
616 // created previously.
617 ++NumRecords;
618 } else {
619 // Otherwise, this was forward referenced, so an opaque type was created.
620 // Resolve the opaque type to the real type now.
621 assert(NumRecords < TypeList.size() && "Typelist imbalance");
622 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000623
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000624 // Don't directly push the new type on the Tab. Instead we want to replace
625 // the opaque type we previously inserted with the new concrete value. The
626 // refinement from the abstract (opaque) type to the new type causes all
627 // uses of the abstract type to use the concrete type (NewTy). This will
628 // also cause the opaque type to be deleted.
629 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000630
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000631 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000632 // value table... or with a preexisting type that was already in the
633 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000634 assert(TypeList[NumRecords-1].get() != OldTy &&
635 "refineAbstractType didn't work!");
636 }
637 }
638}
639
640
Chris Lattner86697142007-05-01 05:01:34 +0000641bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000642 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000643 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000644
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000645 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000646
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000647 // Read all the records for this type table.
648 std::string TypeName;
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 type symbol table block");
654 return false;
655 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000656
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000657 if (Code == bitc::ENTER_SUBBLOCK) {
658 // No known subblocks, always skip them.
659 Stream.ReadSubBlockID();
660 if (Stream.SkipBlock())
661 return Error("Malformed block record");
662 continue;
663 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000664
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000665 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000666 Stream.ReadAbbrevRecord();
667 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000668 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000669
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000670 // Read a record.
671 Record.clear();
672 switch (Stream.ReadRecord(Code, Record)) {
673 default: // Default behavior: unknown type.
674 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000675 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000676 if (ConvertToString(Record, 1, TypeName))
677 return Error("Invalid TST_ENTRY record");
678 unsigned TypeID = Record[0];
679 if (TypeID >= TypeList.size())
680 return Error("Invalid Type ID in TST_ENTRY record");
681
682 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
683 TypeName.clear();
684 break;
685 }
686 }
687}
688
Chris Lattner86697142007-05-01 05:01:34 +0000689bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000690 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000691 return Error("Malformed block record");
692
693 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000694
Chris Lattner0b2482a2007-04-23 21:26:05 +0000695 // Read all the records for this value table.
696 SmallString<128> ValueName;
697 while (1) {
698 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000699 if (Code == bitc::END_BLOCK) {
700 if (Stream.ReadBlockEnd())
701 return Error("Error at end of value symbol table block");
702 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000703 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000704 if (Code == bitc::ENTER_SUBBLOCK) {
705 // No known subblocks, always skip them.
706 Stream.ReadSubBlockID();
707 if (Stream.SkipBlock())
708 return Error("Malformed block record");
709 continue;
710 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000711
Chris Lattner0b2482a2007-04-23 21:26:05 +0000712 if (Code == bitc::DEFINE_ABBREV) {
713 Stream.ReadAbbrevRecord();
714 continue;
715 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000716
Chris Lattner0b2482a2007-04-23 21:26:05 +0000717 // Read a record.
718 Record.clear();
719 switch (Stream.ReadRecord(Code, Record)) {
720 default: // Default behavior: unknown type.
721 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000722 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000723 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000724 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000725 unsigned ValueID = Record[0];
726 if (ValueID >= ValueList.size())
727 return Error("Invalid Value ID in VST_ENTRY record");
728 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000729
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000730 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000731 ValueName.clear();
732 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000733 }
734 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000735 if (ConvertToString(Record, 1, ValueName))
736 return Error("Invalid VST_BBENTRY record");
737 BasicBlock *BB = getBasicBlock(Record[0]);
738 if (BB == 0)
739 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000740
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000741 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000742 ValueName.clear();
743 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000744 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000745 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000746 }
747}
748
Devang Patele54abc92009-07-22 17:43:22 +0000749bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000750 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000751
752 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
753 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000754
Devang Patele54abc92009-07-22 17:43:22 +0000755 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000756
Devang Patele54abc92009-07-22 17:43:22 +0000757 // Read all the records.
758 while (1) {
759 unsigned Code = Stream.ReadCode();
760 if (Code == bitc::END_BLOCK) {
761 if (Stream.ReadBlockEnd())
762 return Error("Error at end of PARAMATTR block");
763 return false;
764 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000765
Devang Patele54abc92009-07-22 17:43:22 +0000766 if (Code == bitc::ENTER_SUBBLOCK) {
767 // No known subblocks, always skip them.
768 Stream.ReadSubBlockID();
769 if (Stream.SkipBlock())
770 return Error("Malformed block record");
771 continue;
772 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000773
Devang Patele54abc92009-07-22 17:43:22 +0000774 if (Code == bitc::DEFINE_ABBREV) {
775 Stream.ReadAbbrevRecord();
776 continue;
777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000778
Victor Hernandez24e64df2010-01-10 07:14:18 +0000779 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000780 // Read a record.
781 Record.clear();
782 switch (Stream.ReadRecord(Code, Record)) {
783 default: // Default behavior: ignore.
784 break;
Devang Patelaa993142009-07-29 22:34:41 +0000785 case bitc::METADATA_NAME: {
786 // Read named of the named metadata.
787 unsigned NameLength = Record.size();
788 SmallString<8> Name;
789 Name.resize(NameLength);
790 for (unsigned i = 0; i != NameLength; ++i)
791 Name[i] = Record[i];
792 Record.clear();
793 Code = Stream.ReadCode();
794
795 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
796 if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
797 assert ( 0 && "Inavlid Named Metadata record");
798
799 // Read named metadata elements.
800 unsigned Size = Record.size();
Devang Patel3e30c2a2010-01-05 20:41:31 +0000801 SmallVector<MDNode *, 8> Elts;
Devang Patelaa993142009-07-29 22:34:41 +0000802 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000803 if (Record[i] == ~0U) {
Devang Patel69d02e02010-01-05 21:47:32 +0000804 Elts.push_back(NULL);
Chris Lattner70644e92010-01-09 02:02:37 +0000805 continue;
Devang Patel69d02e02010-01-05 21:47:32 +0000806 }
Chris Lattner70644e92010-01-09 02:02:37 +0000807 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
808 if (MD == 0)
809 return Error("Malformed metadata record");
810 Elts.push_back(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000811 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000812 Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(),
Owen Anderson1d0be152009-08-13 21:58:54 +0000813 Elts.size(), TheModule);
Devang Patel23598502010-01-11 18:52:33 +0000814 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patelaa993142009-07-29 22:34:41 +0000815 break;
816 }
Victor Hernandez24e64df2010-01-10 07:14:18 +0000817 case bitc::METADATA_FN_NODE:
818 IsFunctionLocal = true;
819 // fall-through
Devang Patel104cf9e2009-07-23 01:07:34 +0000820 case bitc::METADATA_NODE: {
821 if (Record.empty() || Record.size() % 2 == 1)
822 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000823
Devang Patel104cf9e2009-07-23 01:07:34 +0000824 unsigned Size = Record.size();
825 SmallVector<Value*, 8> Elts;
826 for (unsigned i = 0; i != Size; i += 2) {
827 const Type *Ty = getTypeByID(Record[i], false);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000828 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000829 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000830 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000831 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
832 else
833 Elts.push_back(NULL);
834 }
Victor Hernandez24e64df2010-01-10 07:14:18 +0000835 Value *V = MDNode::getWhenValsUnresolved(Context, &Elts[0], Elts.size(),
836 IsFunctionLocal);
837 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000838 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000839 break;
840 }
Devang Patele54abc92009-07-22 17:43:22 +0000841 case bitc::METADATA_STRING: {
842 unsigned MDStringLength = Record.size();
843 SmallString<8> String;
844 String.resize(MDStringLength);
845 for (unsigned i = 0; i != MDStringLength; ++i)
846 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000847 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +0000848 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +0000849 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000850 break;
851 }
Devang Patele8e02132009-09-18 19:26:43 +0000852 case bitc::METADATA_KIND: {
853 unsigned RecordLength = Record.size();
854 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000855 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +0000856 SmallString<8> Name;
857 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +0000858 unsigned Kind = Record[0];
Daniel Dunbar22bbd9b2009-10-25 23:11:06 +0000859 (void) Kind;
Devang Patele8e02132009-09-18 19:26:43 +0000860 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000861 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +0000862
Chris Lattner08113472009-12-29 09:01:33 +0000863 unsigned NewKind = TheModule->getMDKindID(Name.str());
Chris Lattner0eb41982009-12-28 20:45:51 +0000864 assert(Kind == NewKind &&
865 "FIXME: Unable to handle custom metadata mismatch!");(void)NewKind;
Devang Patele8e02132009-09-18 19:26:43 +0000866 break;
867 }
Devang Patele54abc92009-07-22 17:43:22 +0000868 }
869 }
870}
871
Chris Lattner0eef0802007-04-24 04:04:35 +0000872/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
873/// the LSB for dense VBR encoding.
874static uint64_t DecodeSignRotatedValue(uint64_t V) {
875 if ((V & 1) == 0)
876 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000877 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000878 return -(V >> 1);
879 // There is no such thing as -0 with integers. "-0" really means MININT.
880 return 1ULL << 63;
881}
882
Chris Lattner07d98b42007-04-26 02:46:40 +0000883/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
884/// values and aliases that we can.
885bool BitcodeReader::ResolveGlobalAndAliasInits() {
886 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
887 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000888
Chris Lattner07d98b42007-04-26 02:46:40 +0000889 GlobalInitWorklist.swap(GlobalInits);
890 AliasInitWorklist.swap(AliasInits);
891
892 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000893 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000894 if (ValID >= ValueList.size()) {
895 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000896 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000897 } else {
898 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
899 GlobalInitWorklist.back().first->setInitializer(C);
900 else
901 return Error("Global variable initializer is not a constant!");
902 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000903 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000904 }
905
906 while (!AliasInitWorklist.empty()) {
907 unsigned ValID = AliasInitWorklist.back().second;
908 if (ValID >= ValueList.size()) {
909 AliasInits.push_back(AliasInitWorklist.back());
910 } else {
911 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000912 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000913 else
914 return Error("Alias initializer is not a constant!");
915 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000916 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000917 }
918 return false;
919}
920
Chris Lattner86697142007-05-01 05:01:34 +0000921bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000922 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000923 return Error("Malformed block record");
924
925 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000926
Chris Lattnere16504e2007-04-24 03:30:34 +0000927 // Read all the records for this value table.
Owen Anderson1d0be152009-08-13 21:58:54 +0000928 const Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000929 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000930 while (1) {
931 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000932 if (Code == bitc::END_BLOCK)
933 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000934
Chris Lattnere16504e2007-04-24 03:30:34 +0000935 if (Code == bitc::ENTER_SUBBLOCK) {
936 // No known subblocks, always skip them.
937 Stream.ReadSubBlockID();
938 if (Stream.SkipBlock())
939 return Error("Malformed block record");
940 continue;
941 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000942
Chris Lattnere16504e2007-04-24 03:30:34 +0000943 if (Code == bitc::DEFINE_ABBREV) {
944 Stream.ReadAbbrevRecord();
945 continue;
946 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000947
Chris Lattnere16504e2007-04-24 03:30:34 +0000948 // Read a record.
949 Record.clear();
950 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000951 unsigned BitCode = Stream.ReadRecord(Code, Record);
952 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000953 default: // Default behavior: unknown constant
954 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000955 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000956 break;
957 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
958 if (Record.empty())
959 return Error("Malformed CST_SETTYPE record");
960 if (Record[0] >= TypeList.size())
961 return Error("Invalid Type ID in CST_SETTYPE record");
962 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000963 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000964 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000965 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000966 break;
967 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000968 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000969 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +0000970 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000971 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000972 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000973 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000974 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000975
Chris Lattner15e6d172007-05-04 19:11:41 +0000976 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000977 SmallVector<uint64_t, 8> Words;
978 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000979 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000980 Words[i] = DecodeSignRotatedValue(Record[i]);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000981 V = ConstantInt::get(Context,
Owen Andersoneed707b2009-07-24 23:12:02 +0000982 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
983 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000984 break;
985 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000986 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000987 if (Record.empty())
988 return Error("Invalid FLOAT record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000989 if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000990 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000991 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000992 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000993 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000994 // Bits are not stored the same way as a normal i80 APInt, compensate.
995 uint64_t Rearrange[2];
996 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
997 Rearrange[1] = Record[0] >> 48;
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000998 V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000999 } else if (CurTy->isFP128Ty())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001000 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001001 else if (CurTy->isPPC_FP128Ty())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001002 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +00001003 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001004 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001005 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001006 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001007
Chris Lattner15e6d172007-05-04 19:11:41 +00001008 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1009 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001010 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001011
Chris Lattner15e6d172007-05-04 19:11:41 +00001012 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +00001013 std::vector<Constant*> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001014
Chris Lattner522b7b12007-04-24 05:48:56 +00001015 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
1016 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001017 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001018 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001019 V = ConstantStruct::get(STy, Elts);
Chris Lattner93b122d2010-03-16 21:25:55 +00001020 } else if (const UnionType *UnTy = dyn_cast<UnionType>(CurTy)) {
1021 uint64_t Index = Record[0];
1022 Constant *Val = ValueList.getConstantFwdRef(Record[1],
1023 UnTy->getElementType(Index));
1024 V = ConstantUnion::get(UnTy, Val);
Chris Lattner522b7b12007-04-24 05:48:56 +00001025 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1026 const Type *EltTy = ATy->getElementType();
1027 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001028 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001029 V = ConstantArray::get(ATy, Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001030 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1031 const Type *EltTy = VTy->getElementType();
1032 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001033 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001034 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001035 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001036 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001037 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001038 break;
1039 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001040 case bitc::CST_CODE_STRING: { // STRING: [values]
1041 if (Record.empty())
1042 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001043
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001044 const ArrayType *ATy = cast<ArrayType>(CurTy);
1045 const Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001046
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001047 unsigned Size = Record.size();
1048 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001049 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001050 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Anderson1fd70962009-07-28 18:32:17 +00001051 V = ConstantArray::get(ATy, Elts);
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001052 break;
1053 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001054 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1055 if (Record.empty())
1056 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001057
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001058 const ArrayType *ATy = cast<ArrayType>(CurTy);
1059 const Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001060
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001061 unsigned Size = Record.size();
1062 std::vector<Constant*> Elts;
1063 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001064 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Andersona7235ea2009-07-31 20:28:14 +00001065 Elts.push_back(Constant::getNullValue(EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001066 V = ConstantArray::get(ATy, Elts);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001067 break;
1068 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001069 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1070 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1071 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001072 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001073 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001074 } else {
1075 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1076 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001077 unsigned Flags = 0;
1078 if (Record.size() >= 4) {
1079 if (Opc == Instruction::Add ||
1080 Opc == Instruction::Sub ||
1081 Opc == Instruction::Mul) {
1082 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1083 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1084 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1085 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1086 } else if (Opc == Instruction::SDiv) {
1087 if (Record[3] & (1 << bitc::SDIV_EXACT))
1088 Flags |= SDivOperator::IsExact;
1089 }
1090 }
1091 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001092 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001093 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001094 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001095 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1096 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1097 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001098 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001099 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001100 } else {
1101 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001102 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001103 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001104 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001105 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001106 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001107 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001108 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001109 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001110 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001111 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001112 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001113 const Type *ElTy = getTypeByID(Record[i]);
1114 if (!ElTy) return Error("Invalid CE_GEP record");
1115 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1116 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001117 if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001118 V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
1119 Elts.size()-1);
1120 else
1121 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
1122 Elts.size()-1);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001123 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001124 }
1125 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1126 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001127 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001128 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001129 ValueList.getConstantFwdRef(Record[1],CurTy),
1130 ValueList.getConstantFwdRef(Record[2],CurTy));
1131 break;
1132 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1133 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001134 const VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001135 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1136 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1137 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001138 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001139 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001140 break;
1141 }
1142 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1143 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1144 if (Record.size() < 3 || OpTy == 0)
1145 return Error("Invalid CE_INSERTELT record");
1146 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1147 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1148 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001149 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001150 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001151 break;
1152 }
1153 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1154 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1155 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001156 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001157 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1158 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001159 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001160 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001161 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001162 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001163 break;
1164 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001165 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1166 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1167 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
1168 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1169 return Error("Invalid CE_SHUFVEC_EX record");
1170 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1171 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001172 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001173 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001174 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001175 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001176 break;
1177 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001178 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1179 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1180 const Type *OpTy = getTypeByID(Record[0]);
1181 if (OpTy == 0) return Error("Invalid CE_CMP record");
1182 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1183 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1184
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001185 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001186 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001187 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001188 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001189 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001190 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001191 case bitc::CST_CODE_INLINEASM: {
1192 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1193 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001194 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001195 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001196 unsigned AsmStrSize = Record[1];
1197 if (2+AsmStrSize >= Record.size())
1198 return Error("Invalid INLINEASM record");
1199 unsigned ConstStrSize = Record[2+AsmStrSize];
1200 if (3+AsmStrSize+ConstStrSize > Record.size())
1201 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001202
Chris Lattner2bce93a2007-05-06 01:58:20 +00001203 for (unsigned i = 0; i != AsmStrSize; ++i)
1204 AsmStr += (char)Record[2+i];
1205 for (unsigned i = 0; i != ConstStrSize; ++i)
1206 ConstrStr += (char)Record[3+AsmStrSize+i];
1207 const PointerType *PTy = cast<PointerType>(CurTy);
1208 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001209 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001210 break;
1211 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001212 case bitc::CST_CODE_BLOCKADDRESS:{
1213 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1214 const Type *FnTy = getTypeByID(Record[0]);
1215 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1216 Function *Fn =
1217 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1218 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1219
1220 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1221 Type::getInt8Ty(Context),
1222 false, GlobalValue::InternalLinkage,
1223 0, "");
1224 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1225 V = FwdRef;
1226 break;
1227 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001228 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001229
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001230 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001231 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001232 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001233
Chris Lattnerea693df2008-08-21 02:34:16 +00001234 if (NextCstNo != ValueList.size())
1235 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001236
Chris Lattnerea693df2008-08-21 02:34:16 +00001237 if (Stream.ReadBlockEnd())
1238 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001239
Chris Lattnerea693df2008-08-21 02:34:16 +00001240 // Once all the constants have been read, go through and resolve forward
1241 // references.
1242 ValueList.ResolveConstantForwardRefs();
1243 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001244}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001245
Chris Lattner980e5aa2007-05-01 05:52:21 +00001246/// RememberAndSkipFunctionBody - When we see the block for a function body,
1247/// remember where it is and then skip it. This lets us lazily deserialize the
1248/// functions.
1249bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001250 // Get the function we are talking about.
1251 if (FunctionsWithBodies.empty())
1252 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001253
Chris Lattner48f84872007-05-01 04:59:48 +00001254 Function *Fn = FunctionsWithBodies.back();
1255 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001256
Chris Lattner48f84872007-05-01 04:59:48 +00001257 // Save the current stream state.
1258 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001259 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001260
Chris Lattner48f84872007-05-01 04:59:48 +00001261 // Skip over the function block for now.
1262 if (Stream.SkipBlock())
1263 return Error("Malformed block record");
1264 return false;
1265}
1266
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001267bool BitcodeReader::ParseModule() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001268 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001269 return Error("Malformed block record");
1270
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001271 SmallVector<uint64_t, 64> Record;
1272 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001273 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001274
1275 // Read all the records for this module.
1276 while (!Stream.AtEndOfStream()) {
1277 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001278 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001279 if (Stream.ReadBlockEnd())
1280 return Error("Error at end of module block");
1281
1282 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001283 ResolveGlobalAndAliasInits();
1284 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001285 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001286 if (!FunctionsWithBodies.empty())
1287 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001288
Chandler Carruth69940402007-08-04 01:51:18 +00001289 // Look for intrinsic functions which need to be upgraded at some point
1290 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1291 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001292 Function* NewFn;
1293 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001294 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1295 }
1296
Chris Lattner980e5aa2007-05-01 05:52:21 +00001297 // Force deallocation of memory for these vectors to favor the client that
1298 // want lazy deserialization.
1299 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1300 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1301 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001302 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001303 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001304
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001305 if (Code == bitc::ENTER_SUBBLOCK) {
1306 switch (Stream.ReadSubBlockID()) {
1307 default: // Skip unknown content.
1308 if (Stream.SkipBlock())
1309 return Error("Malformed block record");
1310 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001311 case bitc::BLOCKINFO_BLOCK_ID:
1312 if (Stream.ReadBlockInfoBlock())
1313 return Error("Malformed BlockInfoBlock");
1314 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001315 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001316 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001317 return true;
1318 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001319 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001320 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001321 return true;
1322 break;
1323 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001324 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001325 return true;
1326 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001327 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001328 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001329 return true;
1330 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001331 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001332 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001333 return true;
1334 break;
Devang Patele54abc92009-07-22 17:43:22 +00001335 case bitc::METADATA_BLOCK_ID:
1336 if (ParseMetadata())
1337 return true;
1338 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001339 case bitc::FUNCTION_BLOCK_ID:
1340 // If this is the first function body we've seen, reverse the
1341 // FunctionsWithBodies list.
1342 if (!HasReversedFunctionsWithBodies) {
1343 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1344 HasReversedFunctionsWithBodies = true;
1345 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001346
Chris Lattner980e5aa2007-05-01 05:52:21 +00001347 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001348 return true;
1349 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001350 }
1351 continue;
1352 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001353
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001354 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001355 Stream.ReadAbbrevRecord();
1356 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001357 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001358
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001359 // Read a record.
1360 switch (Stream.ReadRecord(Code, Record)) {
1361 default: break; // Default behavior, ignore unknown content.
1362 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1363 if (Record.size() < 1)
1364 return Error("Malformed MODULE_CODE_VERSION");
1365 // Only version #0 is supported so far.
1366 if (Record[0] != 0)
1367 return Error("Unknown bitstream version!");
1368 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001369 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001370 std::string S;
1371 if (ConvertToString(Record, 0, S))
1372 return Error("Invalid MODULE_CODE_TRIPLE record");
1373 TheModule->setTargetTriple(S);
1374 break;
1375 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001376 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001377 std::string S;
1378 if (ConvertToString(Record, 0, S))
1379 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1380 TheModule->setDataLayout(S);
1381 break;
1382 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001383 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001384 std::string S;
1385 if (ConvertToString(Record, 0, S))
1386 return Error("Invalid MODULE_CODE_ASM record");
1387 TheModule->setModuleInlineAsm(S);
1388 break;
1389 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001390 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001391 std::string S;
1392 if (ConvertToString(Record, 0, S))
1393 return Error("Invalid MODULE_CODE_DEPLIB record");
1394 TheModule->addLibrary(S);
1395 break;
1396 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001397 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001398 std::string S;
1399 if (ConvertToString(Record, 0, S))
1400 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1401 SectionTable.push_back(S);
1402 break;
1403 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001404 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001405 std::string S;
1406 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001407 return Error("Invalid MODULE_CODE_GCNAME record");
1408 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001409 break;
1410 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001411 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001412 // linkage, alignment, section, visibility, threadlocal]
1413 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001414 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001415 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1416 const Type *Ty = getTypeByID(Record[0]);
Duncan Sands1df98592010-02-16 11:11:14 +00001417 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001418 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001419 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001420 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001421
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001422 bool isConstant = Record[1];
1423 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1424 unsigned Alignment = (1 << Record[4]) >> 1;
1425 std::string Section;
1426 if (Record[5]) {
1427 if (Record[5]-1 >= SectionTable.size())
1428 return Error("Invalid section ID");
1429 Section = SectionTable[Record[5]-1];
1430 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001431 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001432 if (Record.size() > 6)
1433 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001434 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001435 if (Record.size() > 7)
1436 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001437
1438 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001439 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001440 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001441 NewGV->setAlignment(Alignment);
1442 if (!Section.empty())
1443 NewGV->setSection(Section);
1444 NewGV->setVisibility(Visibility);
1445 NewGV->setThreadLocal(isThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001446
Chris Lattner0b2482a2007-04-23 21:26:05 +00001447 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001448
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001449 // Remember which value to use for the global initializer.
1450 if (unsigned InitID = Record[2])
1451 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001452 break;
1453 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001454 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001455 // alignment, section, visibility, gc]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001456 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001457 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001458 return Error("Invalid MODULE_CODE_FUNCTION record");
1459 const Type *Ty = getTypeByID(Record[0]);
Duncan Sands1df98592010-02-16 11:11:14 +00001460 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001461 return Error("Function not a pointer type!");
1462 const FunctionType *FTy =
1463 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1464 if (!FTy)
1465 return Error("Function not a pointer to function type!");
1466
Gabor Greif051a9502008-04-06 20:25:17 +00001467 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1468 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001469
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001470 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001471 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001472 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001473 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001474
Chris Lattnera9bb7132007-05-08 05:38:01 +00001475 Func->setAlignment((1 << Record[5]) >> 1);
1476 if (Record[6]) {
1477 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001478 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001479 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001480 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001481 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001482 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001483 if (Record[8]-1 > GCTable.size())
1484 return Error("Invalid GC ID");
1485 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001486 }
Chris Lattner0b2482a2007-04-23 21:26:05 +00001487 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001488
Chris Lattner48f84872007-05-01 04:59:48 +00001489 // If this is a function with a body, remember the prototype we are
1490 // creating now, so that we can match up the body with them later.
1491 if (!isProto)
1492 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001493 break;
1494 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001495 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001496 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001497 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001498 if (Record.size() < 3)
1499 return Error("Invalid MODULE_ALIAS record");
1500 const Type *Ty = getTypeByID(Record[0]);
Duncan Sands1df98592010-02-16 11:11:14 +00001501 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001502 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001503
Chris Lattner07d98b42007-04-26 02:46:40 +00001504 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1505 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001506 // Old bitcode files didn't have visibility field.
1507 if (Record.size() > 3)
1508 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001509 ValueList.push_back(NewGA);
1510 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1511 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001512 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001513 /// MODULE_CODE_PURGEVALS: [numvals]
1514 case bitc::MODULE_CODE_PURGEVALS:
1515 // Trim down the value list to the specified size.
1516 if (Record.size() < 1 || Record[0] > ValueList.size())
1517 return Error("Invalid MODULE_PURGEVALS record");
1518 ValueList.shrinkTo(Record[0]);
1519 break;
1520 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001521 Record.clear();
1522 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001524 return Error("Premature end of bitstream");
1525}
1526
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001527bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001528 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001529
Chris Lattnerc453f762007-04-29 07:54:31 +00001530 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001531 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001532
Dan Gohmana4ae3a12010-04-02 00:03:51 +00001533 if (Buffer->getBufferSize() & 3) {
1534 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1535 return Error("Invalid bitcode signature");
1536 else
1537 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1538 }
1539
Chris Lattner6fa6a322008-07-09 05:14:23 +00001540 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1541 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnere2a466b2009-04-06 20:54:32 +00001542 if (isBitcodeWrapper(BufPtr, BufEnd))
1543 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner6fa6a322008-07-09 05:14:23 +00001544 return Error("Invalid bitcode wrapper header");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001545
Chris Lattner962dde32009-04-26 20:59:02 +00001546 StreamFile.init(BufPtr, BufEnd);
1547 Stream.init(StreamFile);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001548
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001549 // Sniff for the signature.
1550 if (Stream.Read(8) != 'B' ||
1551 Stream.Read(8) != 'C' ||
1552 Stream.Read(4) != 0x0 ||
1553 Stream.Read(4) != 0xC ||
1554 Stream.Read(4) != 0xE ||
1555 Stream.Read(4) != 0xD)
1556 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001557
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001558 // We expect a number of well-defined blocks, though we don't necessarily
1559 // need to understand them all.
1560 while (!Stream.AtEndOfStream()) {
1561 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001562
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001563 if (Code != bitc::ENTER_SUBBLOCK)
1564 return Error("Invalid record at top-level");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001565
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001566 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001567
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001568 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001569 switch (BlockID) {
1570 case bitc::BLOCKINFO_BLOCK_ID:
1571 if (Stream.ReadBlockInfoBlock())
1572 return Error("Malformed BlockInfoBlock");
1573 break;
1574 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001575 // Reject multiple MODULE_BLOCK's in a single bitstream.
1576 if (TheModule)
1577 return Error("Multiple MODULE_BLOCKs in same stream");
1578 TheModule = M;
1579 if (ParseModule())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001580 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001581 break;
1582 default:
1583 if (Stream.SkipBlock())
1584 return Error("Malformed block record");
1585 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001586 }
1587 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001588
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001589 return false;
1590}
Chris Lattnerc453f762007-04-29 07:54:31 +00001591
Devang Patele8e02132009-09-18 19:26:43 +00001592/// ParseMetadataAttachment - Parse metadata attachments.
1593bool BitcodeReader::ParseMetadataAttachment() {
1594 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1595 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001596
Devang Patele8e02132009-09-18 19:26:43 +00001597 SmallVector<uint64_t, 64> Record;
1598 while(1) {
1599 unsigned Code = Stream.ReadCode();
1600 if (Code == bitc::END_BLOCK) {
1601 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001602 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001603 break;
1604 }
1605 if (Code == bitc::DEFINE_ABBREV) {
1606 Stream.ReadAbbrevRecord();
1607 continue;
1608 }
1609 // Read a metadata attachment record.
1610 Record.clear();
1611 switch (Stream.ReadRecord(Code, Record)) {
1612 default: // Default behavior: ignore.
1613 break;
1614 case bitc::METADATA_ATTACHMENT: {
1615 unsigned RecordLength = Record.size();
1616 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001617 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001618 Instruction *Inst = InstructionList[Record[0]];
1619 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001620 unsigned Kind = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +00001621 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Chris Lattner3990b122009-12-28 23:41:32 +00001622 Inst->setMetadata(Kind, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001623 }
1624 break;
1625 }
1626 }
1627 }
1628 return false;
1629}
Chris Lattner48f84872007-05-01 04:59:48 +00001630
Chris Lattner980e5aa2007-05-01 05:52:21 +00001631/// ParseFunctionBody - Lazily parse the specified function body block.
1632bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001633 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001634 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001635
Nick Lewycky9a49f152010-02-25 08:30:17 +00001636 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001637 unsigned ModuleValueListSize = ValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001638
Chris Lattner980e5aa2007-05-01 05:52:21 +00001639 // Add all the function arguments to the value table.
1640 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1641 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001642
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001643 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001644 BasicBlock *CurBB = 0;
1645 unsigned CurBBNo = 0;
1646
Chris Lattner980e5aa2007-05-01 05:52:21 +00001647 // Read all the records.
1648 SmallVector<uint64_t, 64> Record;
1649 while (1) {
1650 unsigned Code = Stream.ReadCode();
1651 if (Code == bitc::END_BLOCK) {
1652 if (Stream.ReadBlockEnd())
1653 return Error("Error at end of function block");
1654 break;
1655 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattner980e5aa2007-05-01 05:52:21 +00001657 if (Code == bitc::ENTER_SUBBLOCK) {
1658 switch (Stream.ReadSubBlockID()) {
1659 default: // Skip unknown content.
1660 if (Stream.SkipBlock())
1661 return Error("Malformed block record");
1662 break;
1663 case bitc::CONSTANTS_BLOCK_ID:
1664 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001665 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001666 break;
1667 case bitc::VALUE_SYMTAB_BLOCK_ID:
1668 if (ParseValueSymbolTable()) return true;
1669 break;
Devang Patele8e02132009-09-18 19:26:43 +00001670 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001671 if (ParseMetadataAttachment()) return true;
1672 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001673 case bitc::METADATA_BLOCK_ID:
1674 if (ParseMetadata()) return true;
1675 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001676 }
1677 continue;
1678 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001679
Chris Lattner980e5aa2007-05-01 05:52:21 +00001680 if (Code == bitc::DEFINE_ABBREV) {
1681 Stream.ReadAbbrevRecord();
1682 continue;
1683 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684
Chris Lattner980e5aa2007-05-01 05:52:21 +00001685 // Read a record.
1686 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001687 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001688 unsigned BitCode = Stream.ReadRecord(Code, Record);
1689 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001690 default: // Default behavior: reject
1691 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001692 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001693 if (Record.size() < 1 || Record[0] == 0)
1694 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001695 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001696 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001697 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001698 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001699 CurBB = FunctionBBs[0];
1700 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001701
Chris Lattnerabfbf852007-05-06 00:21:25 +00001702 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1703 unsigned OpNum = 0;
1704 Value *LHS, *RHS;
1705 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1706 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001707 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001708 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001709
Dan Gohman1224c382009-07-20 21:19:07 +00001710 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001711 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001712 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001713 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001714 if (OpNum < Record.size()) {
1715 if (Opc == Instruction::Add ||
1716 Opc == Instruction::Sub ||
1717 Opc == Instruction::Mul) {
Dan Gohman26793ed2010-01-25 21:55:39 +00001718 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001719 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00001720 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001721 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1722 } else if (Opc == Instruction::SDiv) {
Dan Gohman26793ed2010-01-25 21:55:39 +00001723 if (Record[OpNum] & (1 << bitc::SDIV_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001724 cast<BinaryOperator>(I)->setIsExact(true);
1725 }
1726 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001727 break;
1728 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001729 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1730 unsigned OpNum = 0;
1731 Value *Op;
1732 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1733 OpNum+2 != Record.size())
1734 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001735
Chris Lattnerabfbf852007-05-06 00:21:25 +00001736 const Type *ResTy = getTypeByID(Record[OpNum]);
1737 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1738 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001739 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001740 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00001741 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00001742 break;
1743 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001744 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00001745 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001746 unsigned OpNum = 0;
1747 Value *BasePtr;
1748 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001749 return Error("Invalid GEP record");
1750
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001751 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001752 while (OpNum != Record.size()) {
1753 Value *Op;
1754 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001755 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001756 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001757 }
1758
Gabor Greif051a9502008-04-06 20:25:17 +00001759 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Devang Patele8e02132009-09-18 19:26:43 +00001760 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00001761 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001762 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001763 break;
1764 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001765
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001766 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1767 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001768 unsigned OpNum = 0;
1769 Value *Agg;
1770 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1771 return Error("Invalid EXTRACTVAL record");
1772
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001773 SmallVector<unsigned, 4> EXTRACTVALIdx;
1774 for (unsigned RecSize = Record.size();
1775 OpNum != RecSize; ++OpNum) {
1776 uint64_t Index = Record[OpNum];
1777 if ((unsigned)Index != Index)
1778 return Error("Invalid EXTRACTVAL index");
1779 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001780 }
1781
1782 I = ExtractValueInst::Create(Agg,
1783 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
Devang Patele8e02132009-09-18 19:26:43 +00001784 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001785 break;
1786 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001787
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001788 case bitc::FUNC_CODE_INST_INSERTVAL: {
1789 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001790 unsigned OpNum = 0;
1791 Value *Agg;
1792 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1793 return Error("Invalid INSERTVAL record");
1794 Value *Val;
1795 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1796 return Error("Invalid INSERTVAL record");
1797
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001798 SmallVector<unsigned, 4> INSERTVALIdx;
1799 for (unsigned RecSize = Record.size();
1800 OpNum != RecSize; ++OpNum) {
1801 uint64_t Index = Record[OpNum];
1802 if ((unsigned)Index != Index)
1803 return Error("Invalid INSERTVAL index");
1804 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001805 }
1806
1807 I = InsertValueInst::Create(Agg, Val,
1808 INSERTVALIdx.begin(), INSERTVALIdx.end());
Devang Patele8e02132009-09-18 19:26:43 +00001809 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001810 break;
1811 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001812
Chris Lattnerabfbf852007-05-06 00:21:25 +00001813 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001814 // obsolete form of select
1815 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00001816 unsigned OpNum = 0;
1817 Value *TrueVal, *FalseVal, *Cond;
1818 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1819 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001820 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001821 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001822
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001823 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00001824 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001825 break;
1826 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001827
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001828 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1829 // new form of select
1830 // handles select i1 or select [N x i1]
1831 unsigned OpNum = 0;
1832 Value *TrueVal, *FalseVal, *Cond;
1833 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1834 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1835 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1836 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00001837
1838 // select condition can be either i1 or [N x i1]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001839 if (const VectorType* vector_type =
1840 dyn_cast<const VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00001841 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00001842 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00001843 return Error("Invalid SELECT condition type");
1844 } else {
1845 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00001846 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00001847 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848 }
1849
Gabor Greif051a9502008-04-06 20:25:17 +00001850 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00001851 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001852 break;
1853 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001854
Chris Lattner01ff65f2007-05-02 05:16:49 +00001855 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001856 unsigned OpNum = 0;
1857 Value *Vec, *Idx;
1858 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001859 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001860 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00001861 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00001862 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001863 break;
1864 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001865
Chris Lattner01ff65f2007-05-02 05:16:49 +00001866 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001867 unsigned OpNum = 0;
1868 Value *Vec, *Elt, *Idx;
1869 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00001870 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00001871 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001872 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001873 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001874 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00001875 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001876 break;
1877 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001878
Chris Lattnerabfbf852007-05-06 00:21:25 +00001879 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1880 unsigned OpNum = 0;
1881 Value *Vec1, *Vec2, *Mask;
1882 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1883 getValue(Record, OpNum, Vec1->getType(), Vec2))
1884 return Error("Invalid SHUFFLEVEC record");
1885
Mon P Wangaeb06d22008-11-10 04:46:22 +00001886 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001887 return Error("Invalid SHUFFLEVEC record");
1888 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00001889 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001890 break;
1891 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001892
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001893 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
1894 // Old form of ICmp/FCmp returning bool
1895 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1896 // both legal on vectors but had different behaviour.
1897 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1898 // FCmp/ICmp returning bool or vector of bool
1899
Chris Lattner7337ab92007-05-06 00:00:00 +00001900 unsigned OpNum = 0;
1901 Value *LHS, *RHS;
1902 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1903 getValue(Record, OpNum, LHS->getType(), RHS) ||
1904 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001905 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001906
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001907 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001908 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001909 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001910 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001911 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00001912 break;
1913 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001914
Devang Patel197be3d2008-02-22 02:49:49 +00001915 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1916 if (Record.size() != 2)
1917 return Error("Invalid GETRESULT record");
1918 unsigned OpNum = 0;
1919 Value *Op;
1920 getValueTypePair(Record, OpNum, NextValueNo, Op);
1921 unsigned Index = Record[1];
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001922 I = ExtractValueInst::Create(Op, Index);
Devang Patele8e02132009-09-18 19:26:43 +00001923 InstructionList.push_back(I);
Devang Patel197be3d2008-02-22 02:49:49 +00001924 break;
1925 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001926
Chris Lattner231cbcb2007-05-02 04:27:25 +00001927 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001928 {
1929 unsigned Size = Record.size();
1930 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001931 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001932 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00001933 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001934 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00001935
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001936 unsigned OpNum = 0;
1937 SmallVector<Value *,4> Vs;
1938 do {
1939 Value *Op = NULL;
1940 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1941 return Error("Invalid RET record");
1942 Vs.push_back(Op);
1943 } while(OpNum != Record.size());
1944
1945 const Type *ReturnType = F->getReturnType();
1946 if (Vs.size() > 1 ||
Duncan Sands1df98592010-02-16 11:11:14 +00001947 (ReturnType->isStructTy() &&
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001948 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001949 Value *RV = UndefValue::get(ReturnType);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001950 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1951 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001952 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001953 CurBB->getInstList().push_back(I);
1954 ValueList.AssignValue(I, NextValueNo++);
1955 RV = I;
1956 }
Owen Anderson1d0be152009-08-13 21:58:54 +00001957 I = ReturnInst::Create(Context, RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001958 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00001959 break;
1960 }
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001961
Owen Anderson1d0be152009-08-13 21:58:54 +00001962 I = ReturnInst::Create(Context, Vs[0]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001963 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001964 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00001965 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001966 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001967 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001968 return Error("Invalid BR record");
1969 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1970 if (TrueDest == 0)
1971 return Error("Invalid BR record");
1972
Devang Patele8e02132009-09-18 19:26:43 +00001973 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00001974 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001975 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00001976 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001977 else {
1978 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00001979 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001980 if (FalseDest == 0 || Cond == 0)
1981 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001982 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001983 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001984 }
1985 break;
1986 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00001987 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001988 if (Record.size() < 3 || (Record.size() & 1) == 0)
1989 return Error("Invalid SWITCH record");
1990 const Type *OpTy = getTypeByID(Record[0]);
1991 Value *Cond = getFnValueByID(Record[1], OpTy);
1992 BasicBlock *Default = getBasicBlock(Record[2]);
1993 if (OpTy == 0 || Cond == 0 || Default == 0)
1994 return Error("Invalid SWITCH record");
1995 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001996 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00001997 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001998 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00001999 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002000 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2001 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2002 if (CaseVal == 0 || DestBB == 0) {
2003 delete SI;
2004 return Error("Invalid SWITCH record!");
2005 }
2006 SI->addCase(CaseVal, DestBB);
2007 }
2008 I = SI;
2009 break;
2010 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002011 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002012 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002013 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002014 const Type *OpTy = getTypeByID(Record[0]);
2015 Value *Address = getFnValueByID(Record[1], OpTy);
2016 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002017 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002018 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002019 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002020 InstructionList.push_back(IBI);
2021 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2022 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2023 IBI->addDestination(DestBB);
2024 } else {
2025 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002026 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002027 }
2028 }
2029 I = IBI;
2030 break;
2031 }
2032
Duncan Sandsdc024672007-11-27 13:23:08 +00002033 case bitc::FUNC_CODE_INST_INVOKE: {
2034 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002035 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002036 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002037 unsigned CCInfo = Record[1];
2038 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2039 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002040
Chris Lattnera9bb7132007-05-08 05:38:01 +00002041 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002042 Value *Callee;
2043 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002044 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002045
Chris Lattner7337ab92007-05-06 00:00:00 +00002046 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2047 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002048 dyn_cast<FunctionType>(CalleeTy->getElementType());
2049
2050 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002051 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2052 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002053 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002054
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002055 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002056 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2057 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2058 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002059 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002060
Chris Lattner7337ab92007-05-06 00:00:00 +00002061 if (!FTy->isVarArg()) {
2062 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002063 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002064 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002065 // Read type/value pairs for varargs params.
2066 while (OpNum != Record.size()) {
2067 Value *Op;
2068 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2069 return Error("Invalid INVOKE record");
2070 Ops.push_back(Op);
2071 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002072 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002073
Gabor Greifb1dbcd82008-05-15 10:04:30 +00002074 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
2075 Ops.begin(), Ops.end());
Devang Patele8e02132009-09-18 19:26:43 +00002076 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002077 cast<InvokeInst>(I)->setCallingConv(
2078 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002079 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002080 break;
2081 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002082 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
Owen Anderson1d0be152009-08-13 21:58:54 +00002083 I = new UnwindInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002084 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002085 break;
2086 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002087 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002088 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002089 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002090 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002091 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002092 return Error("Invalid PHI record");
2093 const Type *Ty = getTypeByID(Record[0]);
2094 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002095
Gabor Greif051a9502008-04-06 20:25:17 +00002096 PHINode *PN = PHINode::Create(Ty);
Devang Patele8e02132009-09-18 19:26:43 +00002097 InstructionList.push_back(PN);
Chris Lattner86941612008-04-13 00:14:42 +00002098 PN->reserveOperandSpace((Record.size()-1)/2);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002099
Chris Lattner15e6d172007-05-04 19:11:41 +00002100 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2101 Value *V = getFnValueByID(Record[1+i], Ty);
2102 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002103 if (!V || !BB) return Error("Invalid PHI record");
2104 PN->addIncoming(V, BB);
2105 }
2106 I = PN;
2107 break;
2108 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002109
Chris Lattner2a98cca2007-05-03 18:58:09 +00002110 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002111 // Autoupgrade malloc instruction to malloc call.
Victor Hernandez68afa542009-10-21 19:11:40 +00002112 // FIXME: Remove in LLVM 3.0.
Chris Lattner2a98cca2007-05-03 18:58:09 +00002113 if (Record.size() < 3)
2114 return Error("Invalid MALLOC record");
2115 const PointerType *Ty =
2116 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Owen Anderson1d0be152009-08-13 21:58:54 +00002117 Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
Chris Lattner2a98cca2007-05-03 18:58:09 +00002118 if (!Ty || !Size) return Error("Invalid MALLOC record");
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002119 if (!CurBB) return Error("Invalid malloc instruction with no BB");
Victor Hernandez68afa542009-10-21 19:11:40 +00002120 const Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00002121 Constant *AllocSize = ConstantExpr::getSizeOf(Ty->getElementType());
2122 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, Int32Ty);
Victor Hernandez68afa542009-10-21 19:11:40 +00002123 I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(),
Victor Hernandez9d0b7042009-11-07 00:16:28 +00002124 AllocSize, Size, NULL);
Devang Patele8e02132009-09-18 19:26:43 +00002125 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002126 break;
2127 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002128 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
2129 unsigned OpNum = 0;
2130 Value *Op;
2131 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2132 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00002133 return Error("Invalid FREE record");
Victor Hernandez66284e02009-10-24 04:23:03 +00002134 if (!CurBB) return Error("Invalid free instruction with no BB");
2135 I = CallInst::CreateFree(Op, CurBB);
Devang Patele8e02132009-09-18 19:26:43 +00002136 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002137 break;
2138 }
2139 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
2140 if (Record.size() < 3)
2141 return Error("Invalid ALLOCA record");
2142 const PointerType *Ty =
2143 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Owen Anderson1d0be152009-08-13 21:58:54 +00002144 Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
Chris Lattner2a98cca2007-05-03 18:58:09 +00002145 unsigned Align = Record[2];
2146 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002147 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002148 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002149 break;
2150 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002151 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002152 unsigned OpNum = 0;
2153 Value *Op;
2154 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2155 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002156 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002157
Chris Lattner7337ab92007-05-06 00:00:00 +00002158 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002159 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002160 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002161 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00002162 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
2163 unsigned OpNum = 0;
2164 Value *Val, *Ptr;
2165 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002166 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002167 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2168 OpNum+2 != Record.size())
2169 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002170
Christopher Lambfe63fb92007-12-11 08:59:05 +00002171 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002172 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002173 break;
2174 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002175 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002176 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00002177 unsigned OpNum = 0;
2178 Value *Val, *Ptr;
2179 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002180 getValue(Record, OpNum,
Owen Andersondebcb012009-07-29 22:17:13 +00002181 PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00002182 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002183 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002184
Chris Lattnerabfbf852007-05-06 00:21:25 +00002185 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002186 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002187 break;
2188 }
Duncan Sandsdc024672007-11-27 13:23:08 +00002189 case bitc::FUNC_CODE_INST_CALL: {
2190 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2191 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002192 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002193
Devang Patel05988662008-09-25 21:00:45 +00002194 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002195 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002196
Chris Lattnera9bb7132007-05-08 05:38:01 +00002197 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002198 Value *Callee;
2199 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2200 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002201
Chris Lattner7337ab92007-05-06 00:00:00 +00002202 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00002203 const FunctionType *FTy = 0;
2204 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002205 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002206 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002207
Chris Lattner0579f7f2007-05-03 22:04:19 +00002208 SmallVector<Value*, 16> Args;
2209 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002210 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002211 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2212 Args.push_back(getBasicBlock(Record[OpNum]));
2213 else
2214 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002215 if (Args.back() == 0) return Error("Invalid CALL record");
2216 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002217
Chris Lattner0579f7f2007-05-03 22:04:19 +00002218 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002219 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002220 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002221 return Error("Invalid CALL record");
2222 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002223 while (OpNum != Record.size()) {
2224 Value *Op;
2225 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2226 return Error("Invalid CALL record");
2227 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002228 }
2229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002230
Gabor Greif051a9502008-04-06 20:25:17 +00002231 I = CallInst::Create(Callee, Args.begin(), Args.end());
Devang Patele8e02132009-09-18 19:26:43 +00002232 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002233 cast<CallInst>(I)->setCallingConv(
2234 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002235 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002236 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002237 break;
2238 }
2239 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2240 if (Record.size() < 3)
2241 return Error("Invalid VAARG record");
2242 const Type *OpTy = getTypeByID(Record[0]);
2243 Value *Op = getFnValueByID(Record[1], OpTy);
2244 const Type *ResTy = getTypeByID(Record[2]);
2245 if (!OpTy || !Op || !ResTy)
2246 return Error("Invalid VAARG record");
2247 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002248 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002249 break;
2250 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002251 }
2252
2253 // Add instruction to end of current BB. If there is no current BB, reject
2254 // this file.
2255 if (CurBB == 0) {
2256 delete I;
2257 return Error("Invalid instruction with no BB");
2258 }
2259 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002260
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002261 // If this was a terminator instruction, move to the next block.
2262 if (isa<TerminatorInst>(I)) {
2263 ++CurBBNo;
2264 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2265 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002266
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002267 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002268 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002269 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002270 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002271
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002272 // Check the function list for unresolved values.
2273 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2274 if (A->getParent() == 0) {
2275 // We found at least one unresolved value. Nuke them all to avoid leaks.
2276 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2277 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002278 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002279 delete A;
2280 }
2281 }
Chris Lattner35a04702007-05-04 03:50:29 +00002282 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002283 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002284 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002285
Chris Lattner50b136d2009-10-28 05:53:48 +00002286 // See if anything took the address of blocks in this function. If so,
2287 // resolve them now.
2288 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
2289 /// are resolved lazily when functions are loaded.
2290 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2291 BlockAddrFwdRefs.find(F);
2292 if (BAFRI != BlockAddrFwdRefs.end()) {
2293 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2294 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2295 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002296 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002297 return Error("Invalid blockaddress block #");
2298
2299 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002300 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002301 FwdRef->eraseFromParent();
2302 }
2303
2304 BlockAddrFwdRefs.erase(BAFRI);
2305 }
2306
Chris Lattner980e5aa2007-05-01 05:52:21 +00002307 // Trim the value list down to the size it was before we parsed this function.
2308 ValueList.shrinkTo(ModuleValueListSize);
2309 std::vector<BasicBlock*>().swap(FunctionBBs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002310
Chris Lattner48f84872007-05-01 04:59:48 +00002311 return false;
2312}
2313
Chris Lattnerb348bb82007-05-18 04:02:46 +00002314//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002315// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002316//===----------------------------------------------------------------------===//
2317
2318
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002319bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2320 if (const Function *F = dyn_cast<Function>(GV)) {
2321 return F->isDeclaration() &&
2322 DeferredFunctionInfo.count(const_cast<Function*>(F));
2323 }
2324 return false;
2325}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002326
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002327bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2328 Function *F = dyn_cast<Function>(GV);
2329 // If it's not a function or is already material, ignore the request.
2330 if (!F || !F->isMaterializable()) return false;
2331
2332 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002333 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002334
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002335 // Move the bit stream to the saved position of the deferred function body.
2336 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002337
Chris Lattnerb348bb82007-05-18 04:02:46 +00002338 if (ParseFunctionBody(F)) {
2339 if (ErrInfo) *ErrInfo = ErrorString;
2340 return true;
2341 }
Chandler Carruth69940402007-08-04 01:51:18 +00002342
2343 // Upgrade any old intrinsic calls in the function.
2344 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2345 E = UpgradedIntrinsics.end(); I != E; ++I) {
2346 if (I->first != I->second) {
2347 for (Value::use_iterator UI = I->first->use_begin(),
2348 UE = I->first->use_end(); UI != UE; ) {
2349 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2350 UpgradeIntrinsicCall(CI, I->second);
2351 }
2352 }
2353 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002354
Chris Lattnerb348bb82007-05-18 04:02:46 +00002355 return false;
2356}
2357
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002358bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2359 const Function *F = dyn_cast<Function>(GV);
2360 if (!F || F->isDeclaration())
2361 return false;
2362 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2363}
2364
2365void BitcodeReader::Dematerialize(GlobalValue *GV) {
2366 Function *F = dyn_cast<Function>(GV);
2367 // If this function isn't dematerializable, this is a noop.
2368 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002369 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002370
Chris Lattnerb348bb82007-05-18 04:02:46 +00002371 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002372
Chris Lattnerb348bb82007-05-18 04:02:46 +00002373 // Just forget the function body, we can remat it later.
2374 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002375}
2376
2377
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002378bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2379 assert(M == TheModule &&
2380 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002381 // Iterate over the module, deserializing any functions that are still on
2382 // disk.
2383 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2384 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002385 if (F->isMaterializable() &&
2386 Materialize(F, ErrInfo))
2387 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002388
Daniel Dunbara279bc32009-09-20 02:20:51 +00002389 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2390 // delete the old functions to clean up. We can't do this unless the entire
2391 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002392 // with calls to the old function.
2393 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2394 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2395 if (I->first != I->second) {
2396 for (Value::use_iterator UI = I->first->use_begin(),
2397 UE = I->first->use_end(); UI != UE; ) {
2398 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2399 UpgradeIntrinsicCall(CI, I->second);
2400 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002401 if (!I->first->use_empty())
2402 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002403 I->first->eraseFromParent();
2404 }
2405 }
2406 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002407
2408 // Check debug info intrinsics.
2409 CheckDebugInfoIntrinsics(TheModule);
2410
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002411 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002412}
2413
Chris Lattner48f84872007-05-01 04:59:48 +00002414
Chris Lattnerc453f762007-04-29 07:54:31 +00002415//===----------------------------------------------------------------------===//
2416// External interface
2417//===----------------------------------------------------------------------===//
2418
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002419/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002420///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002421Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2422 LLVMContext& Context,
2423 std::string *ErrMsg) {
2424 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002425 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002426 M->setMaterializer(R);
2427 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002428 if (ErrMsg)
2429 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002430
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002431 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002432 return 0;
2433 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002434 // Have the BitcodeReader dtor delete 'Buffer'.
2435 R->setBufferOwned(true);
2436 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002437}
2438
2439/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2440/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002441Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002442 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002443 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2444 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002445
2446 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2447 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002448 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002449
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002450 // Read in the entire module, and destroy the BitcodeReader.
2451 if (M->MaterializeAllPermanently(ErrMsg)) {
2452 delete M;
2453 return NULL;
2454 }
Chris Lattnerc453f762007-04-29 07:54:31 +00002455 return M;
2456}