blob: 37cc7949afe3be4cd8d3c48a552b7e654f42f88a [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;
Chris Lattner1afcace2011-07-09 17:41:24 +000034 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000035 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();
Dan Gohman19538d12010-07-20 21:42:28 +000042 MDKindMap.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000043}
44
Chris Lattner48c85b82007-05-04 03:30:17 +000045//===----------------------------------------------------------------------===//
46// Helper functions to implement forward reference resolution, etc.
47//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000048
Chris Lattnercaee0dc2007-04-22 06:23:29 +000049/// ConvertToString - Convert a string from a record into an std::string, return
50/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000051template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000052static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000053 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000054 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000055 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000056
Chris Lattner15e6d172007-05-04 19:11:41 +000057 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000059 return false;
60}
61
62static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
63 switch (Val) {
64 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000065 case 0: return GlobalValue::ExternalLinkage;
66 case 1: return GlobalValue::WeakAnyLinkage;
67 case 2: return GlobalValue::AppendingLinkage;
68 case 3: return GlobalValue::InternalLinkage;
69 case 4: return GlobalValue::LinkOnceAnyLinkage;
70 case 5: return GlobalValue::DLLImportLinkage;
71 case 6: return GlobalValue::DLLExportLinkage;
72 case 7: return GlobalValue::ExternalWeakLinkage;
73 case 8: return GlobalValue::CommonLinkage;
74 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000075 case 10: return GlobalValue::WeakODRLinkage;
76 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000077 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000078 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000079 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling55ae5152010-08-20 22:05:50 +000080 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000081 }
82}
83
84static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
85 switch (Val) {
86 default: // Map unknown visibilities to default.
87 case 0: return GlobalValue::DefaultVisibility;
88 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000089 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000090 }
91}
92
Chris Lattnerf581c3b2007-04-24 07:07:11 +000093static int GetDecodedCastOpcode(unsigned Val) {
94 switch (Val) {
95 default: return -1;
96 case bitc::CAST_TRUNC : return Instruction::Trunc;
97 case bitc::CAST_ZEXT : return Instruction::ZExt;
98 case bitc::CAST_SEXT : return Instruction::SExt;
99 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
100 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
101 case bitc::CAST_UITOFP : return Instruction::UIToFP;
102 case bitc::CAST_SITOFP : return Instruction::SIToFP;
103 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
104 case bitc::CAST_FPEXT : return Instruction::FPExt;
105 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
106 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
107 case bitc::CAST_BITCAST : return Instruction::BitCast;
108 }
109}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000110static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000111 switch (Val) {
112 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000113 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000114 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000115 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000116 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000117 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000118 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000119 case bitc::BINOP_UDIV: return Instruction::UDiv;
120 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000121 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000122 case bitc::BINOP_UREM: return Instruction::URem;
123 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000124 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000125 case bitc::BINOP_SHL: return Instruction::Shl;
126 case bitc::BINOP_LSHR: return Instruction::LShr;
127 case bitc::BINOP_ASHR: return Instruction::AShr;
128 case bitc::BINOP_AND: return Instruction::And;
129 case bitc::BINOP_OR: return Instruction::Or;
130 case bitc::BINOP_XOR: return Instruction::Xor;
131 }
132}
133
Eli Friedman47f35132011-07-25 23:16:38 +0000134static AtomicOrdering GetDecodedOrdering(unsigned Val) {
135 switch (Val) {
136 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
137 case bitc::ORDERING_UNORDERED: return Unordered;
138 case bitc::ORDERING_MONOTONIC: return Monotonic;
139 case bitc::ORDERING_ACQUIRE: return Acquire;
140 case bitc::ORDERING_RELEASE: return Release;
141 case bitc::ORDERING_ACQREL: return AcquireRelease;
142 default: // Map unknown orderings to sequentially-consistent.
143 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
144 }
145}
146
147static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
148 switch (Val) {
149 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
150 default: // Map unknown scopes to cross-thread.
151 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
152 }
153}
154
Gabor Greifefe65362008-05-10 08:32:32 +0000155namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000156namespace {
157 /// @brief A class for maintaining the slot number definition
158 /// as a placeholder for the actual definition for forward constants defs.
159 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000160 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000161 public:
162 // allocate space for exactly one operand
163 void *operator new(size_t s) {
164 return User::operator new(s, 1);
165 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000166 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000167 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000168 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000169 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000170
Chris Lattnerea693df2008-08-21 02:34:16 +0000171 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000172 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000173 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000174 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000175 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
176 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000177
178
Gabor Greifefe65362008-05-10 08:32:32 +0000179 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000180 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000181 };
182}
183
Chris Lattner46e77402009-03-31 22:55:09 +0000184// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000185template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000186struct OperandTraits<ConstantPlaceHolder> :
187 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000188};
Gabor Greifefe65362008-05-10 08:32:32 +0000189}
190
Chris Lattner46e77402009-03-31 22:55:09 +0000191
192void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
193 if (Idx == size()) {
194 push_back(V);
195 return;
196 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000197
Chris Lattner46e77402009-03-31 22:55:09 +0000198 if (Idx >= size())
199 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000200
Chris Lattner46e77402009-03-31 22:55:09 +0000201 WeakVH &OldV = ValuePtrs[Idx];
202 if (OldV == 0) {
203 OldV = V;
204 return;
205 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000206
Chris Lattner46e77402009-03-31 22:55:09 +0000207 // Handle constants and non-constants (e.g. instrs) differently for
208 // efficiency.
209 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
210 ResolveConstants.push_back(std::make_pair(PHC, Idx));
211 OldV = V;
212 } else {
213 // If there was a forward reference to this value, replace it.
214 Value *PrevVal = OldV;
215 OldV->replaceAllUsesWith(V);
216 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000217 }
218}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000219
Gabor Greifefe65362008-05-10 08:32:32 +0000220
Chris Lattner522b7b12007-04-24 05:48:56 +0000221Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000222 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000223 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000224 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000225
Chris Lattner46e77402009-03-31 22:55:09 +0000226 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000227 assert(Ty == V->getType() && "Type mismatch in constant table!");
228 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000229 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000230
231 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000232 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000233 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000234 return C;
235}
236
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000238 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000239 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000240
Chris Lattner46e77402009-03-31 22:55:09 +0000241 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000242 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
243 return V;
244 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000245
Chris Lattner01ff65f2007-05-02 05:16:49 +0000246 // No type specified, must be invalid reference.
247 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000248
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000249 // Create and return a placeholder, which will later be RAUW'd.
250 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000251 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000252 return V;
253}
254
Chris Lattnerea693df2008-08-21 02:34:16 +0000255/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
256/// resolves any forward references. The idea behind this is that we sometimes
257/// get constants (such as large arrays) which reference *many* forward ref
258/// constants. Replacing each of these causes a lot of thrashing when
259/// building/reuniquing the constant. Instead of doing this, we look at all the
260/// uses and rewrite all the place holders at once for any constant that uses
261/// a placeholder.
262void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000263 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000264 // binary search.
265 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000266
Chris Lattnerea693df2008-08-21 02:34:16 +0000267 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000268
Chris Lattnerea693df2008-08-21 02:34:16 +0000269 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000270 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000271 Constant *Placeholder = ResolveConstants.back().first;
272 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000273
Chris Lattnerea693df2008-08-21 02:34:16 +0000274 // Loop over all users of the placeholder, updating them to reference the
275 // new value. If they reference more than one placeholder, update them all
276 // at once.
277 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000278 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000279 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000280
Chris Lattnerea693df2008-08-21 02:34:16 +0000281 // If the using object isn't uniqued, just update the operands. This
282 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000283 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000284 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000285 continue;
286 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000287
Chris Lattnerea693df2008-08-21 02:34:16 +0000288 // Otherwise, we have a constant that uses the placeholder. Replace that
289 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000290 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000291 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
292 I != E; ++I) {
293 Value *NewOp;
294 if (!isa<ConstantPlaceHolder>(*I)) {
295 // Not a placeholder reference.
296 NewOp = *I;
297 } else if (*I == Placeholder) {
298 // Common case is that it just references this one placeholder.
299 NewOp = RealVal;
300 } else {
301 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000302 ResolveConstantsTy::iterator It =
303 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000304 std::pair<Constant*, unsigned>(cast<Constant>(*I),
305 0));
306 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000307 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000308 }
309
310 NewOps.push_back(cast<Constant>(NewOp));
311 }
312
313 // Make the new constant.
314 Constant *NewC;
315 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000316 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000317 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000318 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000319 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000320 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000321 } else {
322 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000323 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000324 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000325
Chris Lattnerea693df2008-08-21 02:34:16 +0000326 UserC->replaceAllUsesWith(NewC);
327 UserC->destroyConstant();
328 NewOps.clear();
329 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000330
Nick Lewyckycb337992009-05-10 20:57:05 +0000331 // Update all ValueHandles, they should be the only users at this point.
332 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000333 delete Placeholder;
334 }
335}
336
Devang Pateld5ac4042009-08-04 06:00:18 +0000337void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
338 if (Idx == size()) {
339 push_back(V);
340 return;
341 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000342
Devang Pateld5ac4042009-08-04 06:00:18 +0000343 if (Idx >= size())
344 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000345
Devang Pateld5ac4042009-08-04 06:00:18 +0000346 WeakVH &OldV = MDValuePtrs[Idx];
347 if (OldV == 0) {
348 OldV = V;
349 return;
350 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000351
Devang Pateld5ac4042009-08-04 06:00:18 +0000352 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000353 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000354 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000355 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000356 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
357 // value for Idx.
358 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000359}
360
361Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
362 if (Idx >= size())
363 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000364
Devang Pateld5ac4042009-08-04 06:00:18 +0000365 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000366 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000367 return V;
368 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000369
Devang Pateld5ac4042009-08-04 06:00:18 +0000370 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000371 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000372 MDValuePtrs[Idx] = V;
373 return V;
374}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000375
Chris Lattner1afcace2011-07-09 17:41:24 +0000376Type *BitcodeReader::getTypeByID(unsigned ID) {
377 // The type table size is always specified correctly.
378 if (ID >= TypeList.size())
379 return 0;
380
381 if (Type *Ty = TypeList[ID])
382 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000383
Chris Lattner1afcace2011-07-09 17:41:24 +0000384 // If we have a forward reference, the only possible case is when it is to a
385 // named struct. Just create a placeholder for now.
386 return TypeList[ID] = StructType::createNamed(Context, "");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000387}
388
Chris Lattner1afcace2011-07-09 17:41:24 +0000389/// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable.
390Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) {
391 if (ID >= TypeList.size())
392 TypeList.resize(ID+1);
393
394 return TypeList[ID];
395}
396
397
Chris Lattner48c85b82007-05-04 03:30:17 +0000398//===----------------------------------------------------------------------===//
399// Functions for parsing blocks from the bitcode file
400//===----------------------------------------------------------------------===//
401
Devang Patel05988662008-09-25 21:00:45 +0000402bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000403 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000404 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000405
Devang Patel19c87462008-09-26 22:53:05 +0000406 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000407 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000408
Chris Lattner48c85b82007-05-04 03:30:17 +0000409 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000410
Devang Patel05988662008-09-25 21:00:45 +0000411 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000412
Chris Lattner48c85b82007-05-04 03:30:17 +0000413 // Read all the records.
414 while (1) {
415 unsigned Code = Stream.ReadCode();
416 if (Code == bitc::END_BLOCK) {
417 if (Stream.ReadBlockEnd())
418 return Error("Error at end of PARAMATTR block");
419 return false;
420 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000421
Chris Lattner48c85b82007-05-04 03:30:17 +0000422 if (Code == bitc::ENTER_SUBBLOCK) {
423 // No known subblocks, always skip them.
424 Stream.ReadSubBlockID();
425 if (Stream.SkipBlock())
426 return Error("Malformed block record");
427 continue;
428 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000429
Chris Lattner48c85b82007-05-04 03:30:17 +0000430 if (Code == bitc::DEFINE_ABBREV) {
431 Stream.ReadAbbrevRecord();
432 continue;
433 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000434
Chris Lattner48c85b82007-05-04 03:30:17 +0000435 // Read a record.
436 Record.clear();
437 switch (Stream.ReadRecord(Code, Record)) {
438 default: // Default behavior: ignore.
439 break;
440 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
441 if (Record.size() & 1)
442 return Error("Invalid ENTRY record");
443
Chris Lattner9a6cb152008-10-05 18:22:09 +0000444 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000445 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000446 // to index ~0. Index 0 is used for return value attributes but used to be
447 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000448 Attributes RetAttribute = Attribute::None;
449 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000450 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000451 // FIXME: remove in LLVM 3.0
452 // The alignment is stored as a 16-bit raw value from bits 31--16.
453 // We shift the bits above 31 down by 11 bits.
454
455 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
456 if (Alignment && !isPowerOf2_32(Alignment))
457 return Error("Alignment is not a power of two.");
458
459 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
460 if (Alignment)
461 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
462 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
463 Record[i+1] = ReconstitutedAttr;
464
Devang Patel19c87462008-09-26 22:53:05 +0000465 if (Record[i] == 0)
466 RetAttribute = Record[i+1];
467 else if (Record[i] == ~0U)
468 FnAttribute = Record[i+1];
469 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000470
471 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
472 Attribute::ReadOnly|Attribute::ReadNone);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000473
Chris Lattner9a6cb152008-10-05 18:22:09 +0000474 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
475 (RetAttribute & OldRetAttrs) != 0) {
476 if (FnAttribute == Attribute::None) { // add a slot so they get added.
477 Record.push_back(~0U);
478 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000479 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000480
Chris Lattner9a6cb152008-10-05 18:22:09 +0000481 FnAttribute |= RetAttribute & OldRetAttrs;
482 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000483 }
Chris Lattner461edd92008-03-12 02:25:52 +0000484
Devang Patel19c87462008-09-26 22:53:05 +0000485 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000486 if (Record[i] == 0) {
487 if (RetAttribute != Attribute::None)
488 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
489 } else if (Record[i] == ~0U) {
490 if (FnAttribute != Attribute::None)
491 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
492 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000493 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
494 }
Devang Patel19c87462008-09-26 22:53:05 +0000495
496 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000497 Attrs.clear();
498 break;
499 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000500 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000501 }
502}
503
Chris Lattner86697142007-05-01 05:01:34 +0000504bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000505 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000506 return Error("Malformed block record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000507
508 return ParseTypeTableBody();
509}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000510
Chris Lattner1afcace2011-07-09 17:41:24 +0000511bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000512 if (!TypeList.empty())
513 return Error("Multiple TYPE_BLOCKs found!");
514
515 SmallVector<uint64_t, 64> Record;
516 unsigned NumRecords = 0;
517
Chris Lattner1afcace2011-07-09 17:41:24 +0000518 SmallString<64> TypeName;
519
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000520 // Read all the records for this type table.
521 while (1) {
522 unsigned Code = Stream.ReadCode();
523 if (Code == bitc::END_BLOCK) {
524 if (NumRecords != TypeList.size())
525 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000526 if (Stream.ReadBlockEnd())
527 return Error("Error at end of type table block");
528 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000529 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000530
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000531 if (Code == bitc::ENTER_SUBBLOCK) {
532 // No known subblocks, always skip them.
533 Stream.ReadSubBlockID();
534 if (Stream.SkipBlock())
535 return Error("Malformed block record");
536 continue;
537 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000538
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000539 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000540 Stream.ReadAbbrevRecord();
541 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000542 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000543
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000544 // Read a record.
545 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000546 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000547 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000548 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000549 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
550 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
551 // type list. This allows us to reserve space.
552 if (Record.size() < 1)
553 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000554 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000555 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000556 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000557 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000558 break;
559 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000561 break;
562 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000563 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000564 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000565 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000566 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000567 break;
568 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000569 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000570 break;
571 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000572 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000573 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000574 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000575 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000576 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000577 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000578 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000579 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000580 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
581 ResultTy = Type::getX86_MMXTy(Context);
582 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
584 if (Record.size() < 1)
585 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000586
Owen Anderson1d0be152009-08-13 21:58:54 +0000587 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000588 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000589 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000590 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000591 if (Record.size() < 1)
592 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000593 unsigned AddressSpace = 0;
594 if (Record.size() == 2)
595 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000596 ResultTy = getTypeByID(Record[0]);
597 if (ResultTy == 0) return Error("invalid element type in pointer type");
598 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000599 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000600 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000601 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000602 // FIXME: attrid is dead, remove it in LLVM 3.0
603 // FUNCTION: [vararg, attrid, retty, paramty x N]
604 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000605 return Error("Invalid FUNCTION type record");
Jay Foad5fdd6c82011-07-12 14:06:48 +0000606 std::vector<Type*> ArgTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000607 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
608 if (Type *T = getTypeByID(Record[i]))
609 ArgTys.push_back(T);
610 else
611 break;
612 }
613
614 ResultTy = getTypeByID(Record[2]);
615 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
616 return Error("invalid type in function type");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000617
Chris Lattner1afcace2011-07-09 17:41:24 +0000618 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000619 break;
620 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000621 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000622 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000623 return Error("Invalid STRUCT type record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000624 std::vector<Type*> EltTys;
625 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
626 if (Type *T = getTypeByID(Record[i]))
627 EltTys.push_back(T);
628 else
629 break;
630 }
631 if (EltTys.size() != Record.size()-1)
632 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000633 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000634 break;
635 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000636 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
637 if (ConvertToString(Record, 0, TypeName))
638 return Error("Invalid STRUCT_NAME record");
639 continue;
640
641 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
642 if (Record.size() < 1)
643 return Error("Invalid STRUCT type record");
644
645 if (NumRecords >= TypeList.size())
646 return Error("invalid TYPE table");
647
648 // Check to see if this was forward referenced, if so fill in the temp.
649 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
650 if (Res) {
651 Res->setName(TypeName);
652 TypeList[NumRecords] = 0;
653 } else // Otherwise, create a new struct.
654 Res = StructType::createNamed(Context, TypeName);
655 TypeName.clear();
656
657 SmallVector<Type*, 8> EltTys;
658 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
659 if (Type *T = getTypeByID(Record[i]))
660 EltTys.push_back(T);
661 else
662 break;
663 }
664 if (EltTys.size() != Record.size()-1)
665 return Error("invalid STRUCT type record");
666 Res->setBody(EltTys, Record[0]);
667 ResultTy = Res;
668 break;
669 }
670 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
671 if (Record.size() != 1)
672 return Error("Invalid OPAQUE type record");
673
674 if (NumRecords >= TypeList.size())
675 return Error("invalid TYPE table");
676
677 // Check to see if this was forward referenced, if so fill in the temp.
678 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
679 if (Res) {
680 Res->setName(TypeName);
681 TypeList[NumRecords] = 0;
682 } else // Otherwise, create a new struct with no body.
683 Res = StructType::createNamed(Context, TypeName);
684 TypeName.clear();
685 ResultTy = Res;
686 break;
687 }
688 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
689 if (Record.size() < 2)
690 return Error("Invalid ARRAY type record");
691 if ((ResultTy = getTypeByID(Record[1])))
692 ResultTy = ArrayType::get(ResultTy, Record[0]);
693 else
694 return Error("Invalid ARRAY type element");
695 break;
696 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
697 if (Record.size() < 2)
698 return Error("Invalid VECTOR type record");
699 if ((ResultTy = getTypeByID(Record[1])))
700 ResultTy = VectorType::get(ResultTy, Record[0]);
701 else
702 return Error("Invalid ARRAY type element");
703 break;
704 }
705
706 if (NumRecords >= TypeList.size())
707 return Error("invalid TYPE table");
708 assert(ResultTy && "Didn't read a type?");
709 assert(TypeList[NumRecords] == 0 && "Already read type?");
710 TypeList[NumRecords++] = ResultTy;
711 }
712}
713
714// FIXME: Remove in LLVM 3.1
715bool BitcodeReader::ParseOldTypeTable() {
716 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_OLD))
717 return Error("Malformed block record");
718
719 if (!TypeList.empty())
720 return Error("Multiple TYPE_BLOCKs found!");
721
722
723 // While horrible, we have no good ordering of types in the bc file. Just
724 // iteratively parse types out of the bc file in multiple passes until we get
725 // them all. Do this by saving a cursor for the start of the type block.
726 BitstreamCursor StartOfTypeBlockCursor(Stream);
727
728 unsigned NumTypesRead = 0;
729
730 SmallVector<uint64_t, 64> Record;
731RestartScan:
732 unsigned NextTypeID = 0;
733 bool ReadAnyTypes = false;
734
735 // Read all the records for this type table.
736 while (1) {
737 unsigned Code = Stream.ReadCode();
738 if (Code == bitc::END_BLOCK) {
739 if (NextTypeID != TypeList.size())
740 return Error("Invalid type forward reference in TYPE_BLOCK_ID_OLD");
741
742 // If we haven't read all of the types yet, iterate again.
743 if (NumTypesRead != TypeList.size()) {
744 // If we didn't successfully read any types in this pass, then we must
745 // have an unhandled forward reference.
746 if (!ReadAnyTypes)
747 return Error("Obsolete bitcode contains unhandled recursive type");
748
749 Stream = StartOfTypeBlockCursor;
750 goto RestartScan;
751 }
752
753 if (Stream.ReadBlockEnd())
754 return Error("Error at end of type table block");
755 return false;
756 }
757
758 if (Code == bitc::ENTER_SUBBLOCK) {
759 // No known subblocks, always skip them.
760 Stream.ReadSubBlockID();
761 if (Stream.SkipBlock())
762 return Error("Malformed block record");
763 continue;
764 }
765
766 if (Code == bitc::DEFINE_ABBREV) {
767 Stream.ReadAbbrevRecord();
768 continue;
769 }
770
771 // Read a record.
772 Record.clear();
773 Type *ResultTy = 0;
774 switch (Stream.ReadRecord(Code, Record)) {
775 default: return Error("unknown type in type table");
776 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
777 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
778 // type list. This allows us to reserve space.
779 if (Record.size() < 1)
780 return Error("Invalid TYPE_CODE_NUMENTRY record");
781 TypeList.resize(Record[0]);
782 continue;
783 case bitc::TYPE_CODE_VOID: // VOID
784 ResultTy = Type::getVoidTy(Context);
785 break;
786 case bitc::TYPE_CODE_FLOAT: // FLOAT
787 ResultTy = Type::getFloatTy(Context);
788 break;
789 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
790 ResultTy = Type::getDoubleTy(Context);
791 break;
792 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
793 ResultTy = Type::getX86_FP80Ty(Context);
794 break;
795 case bitc::TYPE_CODE_FP128: // FP128
796 ResultTy = Type::getFP128Ty(Context);
797 break;
798 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
799 ResultTy = Type::getPPC_FP128Ty(Context);
800 break;
801 case bitc::TYPE_CODE_LABEL: // LABEL
802 ResultTy = Type::getLabelTy(Context);
803 break;
804 case bitc::TYPE_CODE_METADATA: // METADATA
805 ResultTy = Type::getMetadataTy(Context);
806 break;
807 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
808 ResultTy = Type::getX86_MMXTy(Context);
809 break;
810 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
811 if (Record.size() < 1)
812 return Error("Invalid Integer type record");
813 ResultTy = IntegerType::get(Context, Record[0]);
814 break;
815 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
816 if (NextTypeID < TypeList.size() && TypeList[NextTypeID] == 0)
817 ResultTy = StructType::createNamed(Context, "");
818 break;
819 case bitc::TYPE_CODE_STRUCT_OLD: {// STRUCT_OLD
820 if (NextTypeID >= TypeList.size()) break;
821 // If we already read it, don't reprocess.
822 if (TypeList[NextTypeID] &&
823 !cast<StructType>(TypeList[NextTypeID])->isOpaque())
824 break;
825
826 // Set a type.
827 if (TypeList[NextTypeID] == 0)
828 TypeList[NextTypeID] = StructType::createNamed(Context, "");
829
830 std::vector<Type*> EltTys;
831 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
832 if (Type *Elt = getTypeByIDOrNull(Record[i]))
833 EltTys.push_back(Elt);
834 else
835 break;
836 }
837
838 if (EltTys.size() != Record.size()-1)
839 break; // Not all elements are ready.
840
841 cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]);
842 ResultTy = TypeList[NextTypeID];
843 TypeList[NextTypeID] = 0;
844 break;
845 }
846 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
847 // [pointee type, address space]
848 if (Record.size() < 1)
849 return Error("Invalid POINTER type record");
850 unsigned AddressSpace = 0;
851 if (Record.size() == 2)
852 AddressSpace = Record[1];
853 if ((ResultTy = getTypeByIDOrNull(Record[0])))
854 ResultTy = PointerType::get(ResultTy, AddressSpace);
855 break;
856 }
857 case bitc::TYPE_CODE_FUNCTION: {
858 // FIXME: attrid is dead, remove it in LLVM 3.0
859 // FUNCTION: [vararg, attrid, retty, paramty x N]
860 if (Record.size() < 3)
861 return Error("Invalid FUNCTION type record");
Jay Foad5fdd6c82011-07-12 14:06:48 +0000862 std::vector<Type*> ArgTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000863 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
864 if (Type *Elt = getTypeByIDOrNull(Record[i]))
865 ArgTys.push_back(Elt);
866 else
867 break;
868 }
869 if (ArgTys.size()+3 != Record.size())
870 break; // Something was null.
871 if ((ResultTy = getTypeByIDOrNull(Record[2])))
872 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
873 break;
874 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000875 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
876 if (Record.size() < 2)
877 return Error("Invalid ARRAY type record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000878 if ((ResultTy = getTypeByIDOrNull(Record[1])))
879 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000880 break;
881 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
882 if (Record.size() < 2)
883 return Error("Invalid VECTOR type record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000884 if ((ResultTy = getTypeByIDOrNull(Record[1])))
885 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000886 break;
887 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000888
889 if (NextTypeID >= TypeList.size())
890 return Error("invalid TYPE table");
891
892 if (ResultTy && TypeList[NextTypeID] == 0) {
893 ++NumTypesRead;
894 ReadAnyTypes = true;
895
896 TypeList[NextTypeID] = ResultTy;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000897 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000898
899 ++NextTypeID;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000900 }
901}
902
903
Chris Lattner1afcace2011-07-09 17:41:24 +0000904bool BitcodeReader::ParseOldTypeSymbolTable() {
905 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID_OLD))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000906 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000907
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000908 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000909
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000910 // Read all the records for this type table.
911 std::string TypeName;
912 while (1) {
913 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000914 if (Code == bitc::END_BLOCK) {
915 if (Stream.ReadBlockEnd())
916 return Error("Error at end of type symbol table block");
917 return false;
918 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000919
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000920 if (Code == bitc::ENTER_SUBBLOCK) {
921 // No known subblocks, always skip them.
922 Stream.ReadSubBlockID();
923 if (Stream.SkipBlock())
924 return Error("Malformed block record");
925 continue;
926 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000927
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000928 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000929 Stream.ReadAbbrevRecord();
930 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000931 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000932
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000933 // Read a record.
934 Record.clear();
935 switch (Stream.ReadRecord(Code, Record)) {
936 default: // Default behavior: unknown type.
937 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000938 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000939 if (ConvertToString(Record, 1, TypeName))
940 return Error("Invalid TST_ENTRY record");
941 unsigned TypeID = Record[0];
942 if (TypeID >= TypeList.size())
943 return Error("Invalid Type ID in TST_ENTRY record");
944
Chris Lattner1afcace2011-07-09 17:41:24 +0000945 // Only apply the type name to a struct type with no name.
946 if (StructType *STy = dyn_cast<StructType>(TypeList[TypeID]))
947 if (!STy->isAnonymous() && !STy->hasName())
948 STy->setName(TypeName);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000949 TypeName.clear();
950 break;
951 }
952 }
953}
954
Chris Lattner86697142007-05-01 05:01:34 +0000955bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000956 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000957 return Error("Malformed block record");
958
959 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000960
Chris Lattner0b2482a2007-04-23 21:26:05 +0000961 // Read all the records for this value table.
962 SmallString<128> ValueName;
963 while (1) {
964 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000965 if (Code == bitc::END_BLOCK) {
966 if (Stream.ReadBlockEnd())
967 return Error("Error at end of value symbol table block");
968 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000969 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000970 if (Code == bitc::ENTER_SUBBLOCK) {
971 // No known subblocks, always skip them.
972 Stream.ReadSubBlockID();
973 if (Stream.SkipBlock())
974 return Error("Malformed block record");
975 continue;
976 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000977
Chris Lattner0b2482a2007-04-23 21:26:05 +0000978 if (Code == bitc::DEFINE_ABBREV) {
979 Stream.ReadAbbrevRecord();
980 continue;
981 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000982
Chris Lattner0b2482a2007-04-23 21:26:05 +0000983 // Read a record.
984 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000985 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000986 default: // Default behavior: unknown type.
987 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000988 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000989 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000990 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000991 unsigned ValueID = Record[0];
992 if (ValueID >= ValueList.size())
993 return Error("Invalid Value ID in VST_ENTRY record");
994 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000995
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000996 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000997 ValueName.clear();
998 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000999 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +00001000 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +00001001 if (ConvertToString(Record, 1, ValueName))
1002 return Error("Invalid VST_BBENTRY record");
1003 BasicBlock *BB = getBasicBlock(Record[0]);
1004 if (BB == 0)
1005 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001006
Daniel Dunbar3f53fa92009-07-26 00:34:27 +00001007 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +00001008 ValueName.clear();
1009 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001010 }
Reid Spencerc8f8a242007-05-04 01:43:33 +00001011 }
Chris Lattner0b2482a2007-04-23 21:26:05 +00001012 }
1013}
1014
Devang Patele54abc92009-07-22 17:43:22 +00001015bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +00001016 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +00001017
1018 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1019 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001020
Devang Patele54abc92009-07-22 17:43:22 +00001021 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001022
Devang Patele54abc92009-07-22 17:43:22 +00001023 // Read all the records.
1024 while (1) {
1025 unsigned Code = Stream.ReadCode();
1026 if (Code == bitc::END_BLOCK) {
1027 if (Stream.ReadBlockEnd())
1028 return Error("Error at end of PARAMATTR block");
1029 return false;
1030 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001031
Devang Patele54abc92009-07-22 17:43:22 +00001032 if (Code == bitc::ENTER_SUBBLOCK) {
1033 // No known subblocks, always skip them.
1034 Stream.ReadSubBlockID();
1035 if (Stream.SkipBlock())
1036 return Error("Malformed block record");
1037 continue;
1038 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001039
Devang Patele54abc92009-07-22 17:43:22 +00001040 if (Code == bitc::DEFINE_ABBREV) {
1041 Stream.ReadAbbrevRecord();
1042 continue;
1043 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001044
Victor Hernandez24e64df2010-01-10 07:14:18 +00001045 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +00001046 // Read a record.
1047 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +00001048 Code = Stream.ReadRecord(Code, Record);
1049 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +00001050 default: // Default behavior: ignore.
1051 break;
Devang Patelaa993142009-07-29 22:34:41 +00001052 case bitc::METADATA_NAME: {
1053 // Read named of the named metadata.
1054 unsigned NameLength = Record.size();
1055 SmallString<8> Name;
1056 Name.resize(NameLength);
1057 for (unsigned i = 0; i != NameLength; ++i)
1058 Name[i] = Record[i];
1059 Record.clear();
1060 Code = Stream.ReadCode();
1061
Chris Lattner9d61dd92011-06-17 17:50:30 +00001062 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +00001063 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001064 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +00001065
1066 // Read named metadata elements.
1067 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +00001068 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +00001069 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +00001070 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1071 if (MD == 0)
1072 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +00001073 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +00001074 }
Devang Patelaa993142009-07-29 22:34:41 +00001075 break;
1076 }
Chris Lattner9d61dd92011-06-17 17:50:30 +00001077 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +00001078 IsFunctionLocal = true;
1079 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +00001080 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +00001081 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +00001082 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001083
Devang Patel104cf9e2009-07-23 01:07:34 +00001084 unsigned Size = Record.size();
1085 SmallVector<Value*, 8> Elts;
1086 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001087 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001088 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001089 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +00001090 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +00001091 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +00001092 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1093 else
1094 Elts.push_back(NULL);
1095 }
Jay Foadec9186b2011-04-21 19:59:31 +00001096 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +00001097 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +00001098 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +00001099 break;
1100 }
Devang Patele54abc92009-07-22 17:43:22 +00001101 case bitc::METADATA_STRING: {
1102 unsigned MDStringLength = Record.size();
1103 SmallString<8> String;
1104 String.resize(MDStringLength);
1105 for (unsigned i = 0; i != MDStringLength; ++i)
1106 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +00001107 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +00001108 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +00001109 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +00001110 break;
1111 }
Devang Patele8e02132009-09-18 19:26:43 +00001112 case bitc::METADATA_KIND: {
1113 unsigned RecordLength = Record.size();
1114 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +00001116 SmallString<8> Name;
1117 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +00001118 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +00001119 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001120 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +00001121
Chris Lattner08113472009-12-29 09:01:33 +00001122 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +00001123 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1124 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +00001125 break;
1126 }
Devang Patele54abc92009-07-22 17:43:22 +00001127 }
1128 }
1129}
1130
Chris Lattner0eef0802007-04-24 04:04:35 +00001131/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
1132/// the LSB for dense VBR encoding.
1133static uint64_t DecodeSignRotatedValue(uint64_t V) {
1134 if ((V & 1) == 0)
1135 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001136 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +00001137 return -(V >> 1);
1138 // There is no such thing as -0 with integers. "-0" really means MININT.
1139 return 1ULL << 63;
1140}
1141
Chris Lattner07d98b42007-04-26 02:46:40 +00001142/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1143/// values and aliases that we can.
1144bool BitcodeReader::ResolveGlobalAndAliasInits() {
1145 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1146 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001147
Chris Lattner07d98b42007-04-26 02:46:40 +00001148 GlobalInitWorklist.swap(GlobalInits);
1149 AliasInitWorklist.swap(AliasInits);
1150
1151 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +00001152 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +00001153 if (ValID >= ValueList.size()) {
1154 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +00001155 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +00001156 } else {
1157 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1158 GlobalInitWorklist.back().first->setInitializer(C);
1159 else
1160 return Error("Global variable initializer is not a constant!");
1161 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001162 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001163 }
1164
1165 while (!AliasInitWorklist.empty()) {
1166 unsigned ValID = AliasInitWorklist.back().second;
1167 if (ValID >= ValueList.size()) {
1168 AliasInits.push_back(AliasInitWorklist.back());
1169 } else {
1170 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +00001171 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +00001172 else
1173 return Error("Alias initializer is not a constant!");
1174 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001175 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001176 }
1177 return false;
1178}
1179
Chris Lattner86697142007-05-01 05:01:34 +00001180bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001181 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +00001182 return Error("Malformed block record");
1183
1184 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001185
Chris Lattnere16504e2007-04-24 03:30:34 +00001186 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001187 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +00001188 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +00001189 while (1) {
1190 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +00001191 if (Code == bitc::END_BLOCK)
1192 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001193
Chris Lattnere16504e2007-04-24 03:30:34 +00001194 if (Code == bitc::ENTER_SUBBLOCK) {
1195 // No known subblocks, always skip them.
1196 Stream.ReadSubBlockID();
1197 if (Stream.SkipBlock())
1198 return Error("Malformed block record");
1199 continue;
1200 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001201
Chris Lattnere16504e2007-04-24 03:30:34 +00001202 if (Code == bitc::DEFINE_ABBREV) {
1203 Stream.ReadAbbrevRecord();
1204 continue;
1205 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001206
Chris Lattnere16504e2007-04-24 03:30:34 +00001207 // Read a record.
1208 Record.clear();
1209 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001210 unsigned BitCode = Stream.ReadRecord(Code, Record);
1211 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001212 default: // Default behavior: unknown constant
1213 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001214 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001215 break;
1216 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1217 if (Record.empty())
1218 return Error("Malformed CST_SETTYPE record");
1219 if (Record[0] >= TypeList.size())
1220 return Error("Invalid Type ID in CST_SETTYPE record");
1221 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001222 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001223 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001224 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001225 break;
1226 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001227 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001228 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +00001229 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001230 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001231 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001232 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001233 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001234
Chris Lattner15e6d172007-05-04 19:11:41 +00001235 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +00001236 SmallVector<uint64_t, 8> Words;
1237 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +00001238 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001239 Words[i] = DecodeSignRotatedValue(Record[i]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001240 V = ConstantInt::get(Context,
Owen Andersoneed707b2009-07-24 23:12:02 +00001241 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001242 Words));
Chris Lattner0eef0802007-04-24 04:04:35 +00001243 break;
1244 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001245 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001246 if (Record.empty())
1247 return Error("Invalid FLOAT record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001248 if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001249 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001250 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001251 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001252 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001253 // Bits are not stored the same way as a normal i80 APInt, compensate.
1254 uint64_t Rearrange[2];
1255 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1256 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001257 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001258 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001259 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001260 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001261 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001262 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001263 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001264 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001265 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001266
Chris Lattner15e6d172007-05-04 19:11:41 +00001267 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1268 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001269 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001270
Chris Lattner15e6d172007-05-04 19:11:41 +00001271 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +00001272 std::vector<Constant*> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001273
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001274 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001275 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001276 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001277 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001278 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001279 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1280 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001281 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001282 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001283 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001284 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1285 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001286 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001287 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001288 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001289 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001290 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001291 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001292 break;
1293 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001294 case bitc::CST_CODE_STRING: { // STRING: [values]
1295 if (Record.empty())
1296 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001297
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001298 ArrayType *ATy = cast<ArrayType>(CurTy);
1299 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001300
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001301 unsigned Size = Record.size();
1302 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001303 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001304 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Anderson1fd70962009-07-28 18:32:17 +00001305 V = ConstantArray::get(ATy, Elts);
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001306 break;
1307 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001308 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1309 if (Record.empty())
1310 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001311
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001312 ArrayType *ATy = cast<ArrayType>(CurTy);
1313 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001314
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001315 unsigned Size = Record.size();
1316 std::vector<Constant*> Elts;
1317 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001318 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Andersona7235ea2009-07-31 20:28:14 +00001319 Elts.push_back(Constant::getNullValue(EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001320 V = ConstantArray::get(ATy, Elts);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001321 break;
1322 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001323 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1324 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1325 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001326 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001327 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001328 } else {
1329 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1330 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001331 unsigned Flags = 0;
1332 if (Record.size() >= 4) {
1333 if (Opc == Instruction::Add ||
1334 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001335 Opc == Instruction::Mul ||
1336 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001337 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1338 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1339 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1340 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001341 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001342 Opc == Instruction::UDiv ||
1343 Opc == Instruction::LShr ||
1344 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001345 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001346 Flags |= SDivOperator::IsExact;
1347 }
1348 }
1349 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001350 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001351 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001352 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001353 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1354 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1355 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001356 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001357 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001358 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001359 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001360 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001361 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001362 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001363 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001364 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001365 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001366 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001367 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001368 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001369 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001370 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001371 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001372 if (!ElTy) return Error("Invalid CE_GEP record");
1373 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1374 }
Jay Foaddab3d292011-07-21 14:31:17 +00001375 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001376 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1377 BitCode ==
1378 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001379 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001380 }
1381 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1382 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001383 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001384 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001385 ValueList.getConstantFwdRef(Record[1],CurTy),
1386 ValueList.getConstantFwdRef(Record[2],CurTy));
1387 break;
1388 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1389 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001390 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001391 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1392 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1393 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001394 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001395 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001396 break;
1397 }
1398 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001399 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001400 if (Record.size() < 3 || OpTy == 0)
1401 return Error("Invalid CE_INSERTELT record");
1402 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1403 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1404 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001405 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001406 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001407 break;
1408 }
1409 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001410 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001411 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001412 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001413 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1414 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001415 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001416 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001417 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001418 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001419 break;
1420 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001421 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001422 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1423 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001424 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001425 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1426 return Error("Invalid CE_SHUFVEC_EX record");
1427 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1428 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001429 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001430 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001431 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001432 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001433 break;
1434 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001435 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1436 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001437 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001438 if (OpTy == 0) return Error("Invalid CE_CMP record");
1439 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1440 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1441
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001442 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001443 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001444 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001445 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001446 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001447 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001448 case bitc::CST_CODE_INLINEASM: {
1449 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1450 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001451 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001452 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001453 unsigned AsmStrSize = Record[1];
1454 if (2+AsmStrSize >= Record.size())
1455 return Error("Invalid INLINEASM record");
1456 unsigned ConstStrSize = Record[2+AsmStrSize];
1457 if (3+AsmStrSize+ConstStrSize > Record.size())
1458 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001459
Chris Lattner2bce93a2007-05-06 01:58:20 +00001460 for (unsigned i = 0; i != AsmStrSize; ++i)
1461 AsmStr += (char)Record[2+i];
1462 for (unsigned i = 0; i != ConstStrSize; ++i)
1463 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001464 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001465 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001466 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001467 break;
1468 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001469 case bitc::CST_CODE_BLOCKADDRESS:{
1470 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001471 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001472 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1473 Function *Fn =
1474 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1475 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1476
1477 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1478 Type::getInt8Ty(Context),
1479 false, GlobalValue::InternalLinkage,
1480 0, "");
1481 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1482 V = FwdRef;
1483 break;
1484 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001485 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001486
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001487 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001488 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001489 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001490
Chris Lattnerea693df2008-08-21 02:34:16 +00001491 if (NextCstNo != ValueList.size())
1492 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001493
Chris Lattnerea693df2008-08-21 02:34:16 +00001494 if (Stream.ReadBlockEnd())
1495 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001496
Chris Lattnerea693df2008-08-21 02:34:16 +00001497 // Once all the constants have been read, go through and resolve forward
1498 // references.
1499 ValueList.ResolveConstantForwardRefs();
1500 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001501}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001502
Chris Lattner980e5aa2007-05-01 05:52:21 +00001503/// RememberAndSkipFunctionBody - When we see the block for a function body,
1504/// remember where it is and then skip it. This lets us lazily deserialize the
1505/// functions.
1506bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001507 // Get the function we are talking about.
1508 if (FunctionsWithBodies.empty())
1509 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001510
Chris Lattner48f84872007-05-01 04:59:48 +00001511 Function *Fn = FunctionsWithBodies.back();
1512 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001513
Chris Lattner48f84872007-05-01 04:59:48 +00001514 // Save the current stream state.
1515 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001516 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001517
Chris Lattner48f84872007-05-01 04:59:48 +00001518 // Skip over the function block for now.
1519 if (Stream.SkipBlock())
1520 return Error("Malformed block record");
1521 return false;
1522}
1523
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001524bool BitcodeReader::ParseModule() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001525 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001526 return Error("Malformed block record");
1527
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001528 SmallVector<uint64_t, 64> Record;
1529 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001530 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001531
1532 // Read all the records for this module.
1533 while (!Stream.AtEndOfStream()) {
1534 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001535 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001536 if (Stream.ReadBlockEnd())
1537 return Error("Error at end of module block");
1538
1539 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001540 ResolveGlobalAndAliasInits();
1541 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001542 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001543 if (!FunctionsWithBodies.empty())
1544 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001545
Chandler Carruth69940402007-08-04 01:51:18 +00001546 // Look for intrinsic functions which need to be upgraded at some point
1547 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1548 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001549 Function* NewFn;
1550 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001551 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1552 }
1553
Bill Wendlingde49f362010-09-10 18:51:56 +00001554 // Look for global variables which need to be renamed.
1555 for (Module::global_iterator
1556 GI = TheModule->global_begin(), GE = TheModule->global_end();
1557 GI != GE; ++GI)
1558 UpgradeGlobalVariable(GI);
1559
Chris Lattner980e5aa2007-05-01 05:52:21 +00001560 // Force deallocation of memory for these vectors to favor the client that
1561 // want lazy deserialization.
1562 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1563 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1564 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001565 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001566 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001567
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001568 if (Code == bitc::ENTER_SUBBLOCK) {
1569 switch (Stream.ReadSubBlockID()) {
1570 default: // Skip unknown content.
1571 if (Stream.SkipBlock())
1572 return Error("Malformed block record");
1573 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001574 case bitc::BLOCKINFO_BLOCK_ID:
1575 if (Stream.ReadBlockInfoBlock())
1576 return Error("Malformed BlockInfoBlock");
1577 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001578 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001579 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001580 return true;
1581 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001582 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001583 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001584 return true;
1585 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001586 case bitc::TYPE_BLOCK_ID_OLD:
1587 if (ParseOldTypeTable())
1588 return true;
1589 break;
1590 case bitc::TYPE_SYMTAB_BLOCK_ID_OLD:
1591 if (ParseOldTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001592 return true;
1593 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001594 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001595 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001596 return true;
1597 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001598 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001599 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001600 return true;
1601 break;
Devang Patele54abc92009-07-22 17:43:22 +00001602 case bitc::METADATA_BLOCK_ID:
1603 if (ParseMetadata())
1604 return true;
1605 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001606 case bitc::FUNCTION_BLOCK_ID:
1607 // If this is the first function body we've seen, reverse the
1608 // FunctionsWithBodies list.
1609 if (!HasReversedFunctionsWithBodies) {
1610 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1611 HasReversedFunctionsWithBodies = true;
1612 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001613
Chris Lattner980e5aa2007-05-01 05:52:21 +00001614 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001615 return true;
1616 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001617 }
1618 continue;
1619 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001620
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001621 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001622 Stream.ReadAbbrevRecord();
1623 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001624 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001625
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001626 // Read a record.
1627 switch (Stream.ReadRecord(Code, Record)) {
1628 default: break; // Default behavior, ignore unknown content.
1629 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1630 if (Record.size() < 1)
1631 return Error("Malformed MODULE_CODE_VERSION");
1632 // Only version #0 is supported so far.
1633 if (Record[0] != 0)
1634 return Error("Unknown bitstream version!");
1635 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001636 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001637 std::string S;
1638 if (ConvertToString(Record, 0, S))
1639 return Error("Invalid MODULE_CODE_TRIPLE record");
1640 TheModule->setTargetTriple(S);
1641 break;
1642 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001643 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001644 std::string S;
1645 if (ConvertToString(Record, 0, S))
1646 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1647 TheModule->setDataLayout(S);
1648 break;
1649 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001650 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001651 std::string S;
1652 if (ConvertToString(Record, 0, S))
1653 return Error("Invalid MODULE_CODE_ASM record");
1654 TheModule->setModuleInlineAsm(S);
1655 break;
1656 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001657 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001658 std::string S;
1659 if (ConvertToString(Record, 0, S))
1660 return Error("Invalid MODULE_CODE_DEPLIB record");
1661 TheModule->addLibrary(S);
1662 break;
1663 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001664 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001665 std::string S;
1666 if (ConvertToString(Record, 0, S))
1667 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1668 SectionTable.push_back(S);
1669 break;
1670 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001671 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001672 std::string S;
1673 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001674 return Error("Invalid MODULE_CODE_GCNAME record");
1675 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001676 break;
1677 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001678 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001679 // linkage, alignment, section, visibility, threadlocal,
1680 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001681 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001682 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001683 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001684 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001685 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001686 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001687 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001688 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001689 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001690
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001691 bool isConstant = Record[1];
1692 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1693 unsigned Alignment = (1 << Record[4]) >> 1;
1694 std::string Section;
1695 if (Record[5]) {
1696 if (Record[5]-1 >= SectionTable.size())
1697 return Error("Invalid section ID");
1698 Section = SectionTable[Record[5]-1];
1699 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001700 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001701 if (Record.size() > 6)
1702 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001703 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001704 if (Record.size() > 7)
1705 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001706
Rafael Espindolabea46262011-01-08 16:42:36 +00001707 bool UnnamedAddr = false;
1708 if (Record.size() > 8)
1709 UnnamedAddr = Record[8];
1710
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001711 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001712 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001713 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001714 NewGV->setAlignment(Alignment);
1715 if (!Section.empty())
1716 NewGV->setSection(Section);
1717 NewGV->setVisibility(Visibility);
1718 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001719 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattner0b2482a2007-04-23 21:26:05 +00001721 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001722
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001723 // Remember which value to use for the global initializer.
1724 if (unsigned InitID = Record[2])
1725 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001726 break;
1727 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001728 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001729 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001730 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001731 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001732 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001733 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001734 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001735 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001736 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001737 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001738 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1739 if (!FTy)
1740 return Error("Function not a pointer to function type!");
1741
Gabor Greif051a9502008-04-06 20:25:17 +00001742 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1743 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001744
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001745 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001746 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001747 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001748 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001749
Chris Lattnera9bb7132007-05-08 05:38:01 +00001750 Func->setAlignment((1 << Record[5]) >> 1);
1751 if (Record[6]) {
1752 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001753 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001754 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001755 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001756 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001757 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001758 if (Record[8]-1 > GCTable.size())
1759 return Error("Invalid GC ID");
1760 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001761 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001762 bool UnnamedAddr = false;
1763 if (Record.size() > 9)
1764 UnnamedAddr = Record[9];
1765 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001766 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001767
Chris Lattner48f84872007-05-01 04:59:48 +00001768 // If this is a function with a body, remember the prototype we are
1769 // creating now, so that we can match up the body with them later.
1770 if (!isProto)
1771 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001772 break;
1773 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001774 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001775 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001776 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001777 if (Record.size() < 3)
1778 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001779 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001780 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001781 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001782 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001783
Chris Lattner07d98b42007-04-26 02:46:40 +00001784 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1785 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001786 // Old bitcode files didn't have visibility field.
1787 if (Record.size() > 3)
1788 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001789 ValueList.push_back(NewGA);
1790 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1791 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001792 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001793 /// MODULE_CODE_PURGEVALS: [numvals]
1794 case bitc::MODULE_CODE_PURGEVALS:
1795 // Trim down the value list to the specified size.
1796 if (Record.size() < 1 || Record[0] > ValueList.size())
1797 return Error("Invalid MODULE_PURGEVALS record");
1798 ValueList.shrinkTo(Record[0]);
1799 break;
1800 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001801 Record.clear();
1802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001803
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001804 return Error("Premature end of bitstream");
1805}
1806
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001807bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001808 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001809
Chris Lattnerc453f762007-04-29 07:54:31 +00001810 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001811 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001812
Dan Gohmana4ae3a12010-04-02 00:03:51 +00001813 if (Buffer->getBufferSize() & 3) {
1814 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1815 return Error("Invalid bitcode signature");
1816 else
1817 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1818 }
1819
Chris Lattner6fa6a322008-07-09 05:14:23 +00001820 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1821 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnere2a466b2009-04-06 20:54:32 +00001822 if (isBitcodeWrapper(BufPtr, BufEnd))
1823 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner6fa6a322008-07-09 05:14:23 +00001824 return Error("Invalid bitcode wrapper header");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001825
Chris Lattner962dde32009-04-26 20:59:02 +00001826 StreamFile.init(BufPtr, BufEnd);
1827 Stream.init(StreamFile);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001828
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001829 // Sniff for the signature.
1830 if (Stream.Read(8) != 'B' ||
1831 Stream.Read(8) != 'C' ||
1832 Stream.Read(4) != 0x0 ||
1833 Stream.Read(4) != 0xC ||
1834 Stream.Read(4) != 0xE ||
1835 Stream.Read(4) != 0xD)
1836 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001837
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001838 // We expect a number of well-defined blocks, though we don't necessarily
1839 // need to understand them all.
1840 while (!Stream.AtEndOfStream()) {
1841 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001842
Rafael Espindolac9687b32011-05-26 18:59:54 +00001843 if (Code != bitc::ENTER_SUBBLOCK) {
1844
1845 // The ranlib in xcode 4 will align archive members by appending newlines to the
1846 // end of them. If this file size is a multiple of 4 but not 8, we have to read and
1847 // ignore these final 4 bytes :-(
1848 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1849 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1850 Stream.AtEndOfStream())
1851 return false;
1852
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001853 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001854 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001855
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001856 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001857
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001858 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001859 switch (BlockID) {
1860 case bitc::BLOCKINFO_BLOCK_ID:
1861 if (Stream.ReadBlockInfoBlock())
1862 return Error("Malformed BlockInfoBlock");
1863 break;
1864 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001865 // Reject multiple MODULE_BLOCK's in a single bitstream.
1866 if (TheModule)
1867 return Error("Multiple MODULE_BLOCKs in same stream");
1868 TheModule = M;
1869 if (ParseModule())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001870 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001871 break;
1872 default:
1873 if (Stream.SkipBlock())
1874 return Error("Malformed block record");
1875 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001876 }
1877 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001878
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001879 return false;
1880}
Chris Lattnerc453f762007-04-29 07:54:31 +00001881
Bill Wendling34711742010-10-06 01:22:42 +00001882bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1883 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1884 return Error("Malformed block record");
1885
1886 SmallVector<uint64_t, 64> Record;
1887
1888 // Read all the records for this module.
1889 while (!Stream.AtEndOfStream()) {
1890 unsigned Code = Stream.ReadCode();
1891 if (Code == bitc::END_BLOCK) {
1892 if (Stream.ReadBlockEnd())
1893 return Error("Error at end of module block");
1894
1895 return false;
1896 }
1897
1898 if (Code == bitc::ENTER_SUBBLOCK) {
1899 switch (Stream.ReadSubBlockID()) {
1900 default: // Skip unknown content.
1901 if (Stream.SkipBlock())
1902 return Error("Malformed block record");
1903 break;
1904 }
1905 continue;
1906 }
1907
1908 if (Code == bitc::DEFINE_ABBREV) {
1909 Stream.ReadAbbrevRecord();
1910 continue;
1911 }
1912
1913 // Read a record.
1914 switch (Stream.ReadRecord(Code, Record)) {
1915 default: break; // Default behavior, ignore unknown content.
1916 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1917 if (Record.size() < 1)
1918 return Error("Malformed MODULE_CODE_VERSION");
1919 // Only version #0 is supported so far.
1920 if (Record[0] != 0)
1921 return Error("Unknown bitstream version!");
1922 break;
1923 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1924 std::string S;
1925 if (ConvertToString(Record, 0, S))
1926 return Error("Invalid MODULE_CODE_TRIPLE record");
1927 Triple = S;
1928 break;
1929 }
1930 }
1931 Record.clear();
1932 }
1933
1934 return Error("Premature end of bitstream");
1935}
1936
1937bool BitcodeReader::ParseTriple(std::string &Triple) {
1938 if (Buffer->getBufferSize() & 3)
1939 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1940
1941 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1942 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1943
1944 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1945 // The magic number is 0x0B17C0DE stored in little endian.
1946 if (isBitcodeWrapper(BufPtr, BufEnd))
1947 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1948 return Error("Invalid bitcode wrapper header");
1949
1950 StreamFile.init(BufPtr, BufEnd);
1951 Stream.init(StreamFile);
1952
1953 // Sniff for the signature.
1954 if (Stream.Read(8) != 'B' ||
1955 Stream.Read(8) != 'C' ||
1956 Stream.Read(4) != 0x0 ||
1957 Stream.Read(4) != 0xC ||
1958 Stream.Read(4) != 0xE ||
1959 Stream.Read(4) != 0xD)
1960 return Error("Invalid bitcode signature");
1961
1962 // We expect a number of well-defined blocks, though we don't necessarily
1963 // need to understand them all.
1964 while (!Stream.AtEndOfStream()) {
1965 unsigned Code = Stream.ReadCode();
1966
1967 if (Code != bitc::ENTER_SUBBLOCK)
1968 return Error("Invalid record at top-level");
1969
1970 unsigned BlockID = Stream.ReadSubBlockID();
1971
1972 // We only know the MODULE subblock ID.
1973 switch (BlockID) {
1974 case bitc::MODULE_BLOCK_ID:
1975 if (ParseModuleTriple(Triple))
1976 return true;
1977 break;
1978 default:
1979 if (Stream.SkipBlock())
1980 return Error("Malformed block record");
1981 break;
1982 }
1983 }
1984
1985 return false;
1986}
1987
Devang Patele8e02132009-09-18 19:26:43 +00001988/// ParseMetadataAttachment - Parse metadata attachments.
1989bool BitcodeReader::ParseMetadataAttachment() {
1990 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1991 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001992
Devang Patele8e02132009-09-18 19:26:43 +00001993 SmallVector<uint64_t, 64> Record;
1994 while(1) {
1995 unsigned Code = Stream.ReadCode();
1996 if (Code == bitc::END_BLOCK) {
1997 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001998 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001999 break;
2000 }
2001 if (Code == bitc::DEFINE_ABBREV) {
2002 Stream.ReadAbbrevRecord();
2003 continue;
2004 }
2005 // Read a metadata attachment record.
2006 Record.clear();
2007 switch (Stream.ReadRecord(Code, Record)) {
2008 default: // Default behavior: ignore.
2009 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00002010 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00002011 unsigned RecordLength = Record.size();
2012 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002013 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00002014 Instruction *Inst = InstructionList[Record[0]];
2015 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00002016 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00002017 DenseMap<unsigned, unsigned>::iterator I =
2018 MDKindMap.find(Kind);
2019 if (I == MDKindMap.end())
2020 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002021 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00002022 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00002023 }
2024 break;
2025 }
2026 }
2027 }
2028 return false;
2029}
Chris Lattner48f84872007-05-01 04:59:48 +00002030
Chris Lattner980e5aa2007-05-01 05:52:21 +00002031/// ParseFunctionBody - Lazily parse the specified function body block.
2032bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00002033 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00002034 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002035
Nick Lewycky9a49f152010-02-25 08:30:17 +00002036 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002037 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00002038 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002039
Chris Lattner980e5aa2007-05-01 05:52:21 +00002040 // Add all the function arguments to the value table.
2041 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2042 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002043
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002044 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00002045 BasicBlock *CurBB = 0;
2046 unsigned CurBBNo = 0;
2047
Chris Lattnera6245242010-04-03 02:17:50 +00002048 DebugLoc LastLoc;
2049
Chris Lattner980e5aa2007-05-01 05:52:21 +00002050 // Read all the records.
2051 SmallVector<uint64_t, 64> Record;
2052 while (1) {
2053 unsigned Code = Stream.ReadCode();
2054 if (Code == bitc::END_BLOCK) {
2055 if (Stream.ReadBlockEnd())
2056 return Error("Error at end of function block");
2057 break;
2058 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002059
Chris Lattner980e5aa2007-05-01 05:52:21 +00002060 if (Code == bitc::ENTER_SUBBLOCK) {
2061 switch (Stream.ReadSubBlockID()) {
2062 default: // Skip unknown content.
2063 if (Stream.SkipBlock())
2064 return Error("Malformed block record");
2065 break;
2066 case bitc::CONSTANTS_BLOCK_ID:
2067 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002068 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002069 break;
2070 case bitc::VALUE_SYMTAB_BLOCK_ID:
2071 if (ParseValueSymbolTable()) return true;
2072 break;
Devang Patele8e02132009-09-18 19:26:43 +00002073 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002074 if (ParseMetadataAttachment()) return true;
2075 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00002076 case bitc::METADATA_BLOCK_ID:
2077 if (ParseMetadata()) return true;
2078 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002079 }
2080 continue;
2081 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002082
Chris Lattner980e5aa2007-05-01 05:52:21 +00002083 if (Code == bitc::DEFINE_ABBREV) {
2084 Stream.ReadAbbrevRecord();
2085 continue;
2086 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002087
Chris Lattner980e5aa2007-05-01 05:52:21 +00002088 // Read a record.
2089 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002090 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00002091 unsigned BitCode = Stream.ReadRecord(Code, Record);
2092 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002093 default: // Default behavior: reject
2094 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002095 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002096 if (Record.size() < 1 || Record[0] == 0)
2097 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002098 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00002099 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002100 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00002101 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002102 CurBB = FunctionBBs[0];
2103 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00002104
2105 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2106 // This record indicates that the last instruction is at the same
2107 // location as the previous instruction with a location.
2108 I = 0;
2109
2110 // Get the last instruction emitted.
2111 if (CurBB && !CurBB->empty())
2112 I = &CurBB->back();
2113 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2114 !FunctionBBs[CurBBNo-1]->empty())
2115 I = &FunctionBBs[CurBBNo-1]->back();
2116
2117 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2118 I->setDebugLoc(LastLoc);
2119 I = 0;
2120 continue;
2121
Chris Lattner4f6bab92011-06-17 18:17:37 +00002122 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002123 I = 0; // Get the last instruction emitted.
2124 if (CurBB && !CurBB->empty())
2125 I = &CurBB->back();
2126 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2127 !FunctionBBs[CurBBNo-1]->empty())
2128 I = &FunctionBBs[CurBBNo-1]->back();
2129 if (I == 0 || Record.size() < 4)
2130 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2131
2132 unsigned Line = Record[0], Col = Record[1];
2133 unsigned ScopeID = Record[2], IAID = Record[3];
2134
2135 MDNode *Scope = 0, *IA = 0;
2136 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2137 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2138 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2139 I->setDebugLoc(LastLoc);
2140 I = 0;
2141 continue;
2142 }
2143
Chris Lattnerabfbf852007-05-06 00:21:25 +00002144 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2145 unsigned OpNum = 0;
2146 Value *LHS, *RHS;
2147 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2148 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002149 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002150 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002151
Dan Gohman1224c382009-07-20 21:19:07 +00002152 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002153 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002154 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002155 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002156 if (OpNum < Record.size()) {
2157 if (Opc == Instruction::Add ||
2158 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002159 Opc == Instruction::Mul ||
2160 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002161 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002162 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002163 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002164 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002165 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002166 Opc == Instruction::UDiv ||
2167 Opc == Instruction::LShr ||
2168 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002169 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002170 cast<BinaryOperator>(I)->setIsExact(true);
2171 }
2172 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002173 break;
2174 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002175 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2176 unsigned OpNum = 0;
2177 Value *Op;
2178 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2179 OpNum+2 != Record.size())
2180 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002181
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002182 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002183 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2184 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002185 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002186 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002187 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002188 break;
2189 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002190 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002191 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002192 unsigned OpNum = 0;
2193 Value *BasePtr;
2194 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002195 return Error("Invalid GEP record");
2196
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002197 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002198 while (OpNum != Record.size()) {
2199 Value *Op;
2200 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002201 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002202 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002203 }
2204
Jay Foada9203102011-07-25 09:48:08 +00002205 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002206 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002207 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002208 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002209 break;
2210 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002211
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002212 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2213 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002214 unsigned OpNum = 0;
2215 Value *Agg;
2216 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2217 return Error("Invalid EXTRACTVAL record");
2218
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002219 SmallVector<unsigned, 4> EXTRACTVALIdx;
2220 for (unsigned RecSize = Record.size();
2221 OpNum != RecSize; ++OpNum) {
2222 uint64_t Index = Record[OpNum];
2223 if ((unsigned)Index != Index)
2224 return Error("Invalid EXTRACTVAL index");
2225 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002226 }
2227
Jay Foadfc6d3a42011-07-13 10:26:04 +00002228 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002229 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002230 break;
2231 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002232
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002233 case bitc::FUNC_CODE_INST_INSERTVAL: {
2234 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002235 unsigned OpNum = 0;
2236 Value *Agg;
2237 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2238 return Error("Invalid INSERTVAL record");
2239 Value *Val;
2240 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2241 return Error("Invalid INSERTVAL record");
2242
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002243 SmallVector<unsigned, 4> INSERTVALIdx;
2244 for (unsigned RecSize = Record.size();
2245 OpNum != RecSize; ++OpNum) {
2246 uint64_t Index = Record[OpNum];
2247 if ((unsigned)Index != Index)
2248 return Error("Invalid INSERTVAL index");
2249 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002250 }
2251
Jay Foadfc6d3a42011-07-13 10:26:04 +00002252 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002253 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002254 break;
2255 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002256
Chris Lattnerabfbf852007-05-06 00:21:25 +00002257 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002258 // obsolete form of select
2259 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002260 unsigned OpNum = 0;
2261 Value *TrueVal, *FalseVal, *Cond;
2262 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2263 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002264 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002265 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002266
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002267 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002268 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002269 break;
2270 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002271
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002272 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2273 // new form of select
2274 // handles select i1 or select [N x i1]
2275 unsigned OpNum = 0;
2276 Value *TrueVal, *FalseVal, *Cond;
2277 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2278 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2279 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2280 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002281
2282 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002283 if (VectorType* vector_type =
2284 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002285 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002286 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002287 return Error("Invalid SELECT condition type");
2288 } else {
2289 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002290 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002291 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002292 }
2293
Gabor Greif051a9502008-04-06 20:25:17 +00002294 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002295 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002296 break;
2297 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002298
Chris Lattner01ff65f2007-05-02 05:16:49 +00002299 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002300 unsigned OpNum = 0;
2301 Value *Vec, *Idx;
2302 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002303 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002304 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002305 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002306 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002307 break;
2308 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002309
Chris Lattner01ff65f2007-05-02 05:16:49 +00002310 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002311 unsigned OpNum = 0;
2312 Value *Vec, *Elt, *Idx;
2313 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002314 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002315 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002316 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002317 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002318 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002319 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002320 break;
2321 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002322
Chris Lattnerabfbf852007-05-06 00:21:25 +00002323 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2324 unsigned OpNum = 0;
2325 Value *Vec1, *Vec2, *Mask;
2326 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2327 getValue(Record, OpNum, Vec1->getType(), Vec2))
2328 return Error("Invalid SHUFFLEVEC record");
2329
Mon P Wangaeb06d22008-11-10 04:46:22 +00002330 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002331 return Error("Invalid SHUFFLEVEC record");
2332 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002333 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002334 break;
2335 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002336
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002337 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2338 // Old form of ICmp/FCmp returning bool
2339 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2340 // both legal on vectors but had different behaviour.
2341 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2342 // FCmp/ICmp returning bool or vector of bool
2343
Chris Lattner7337ab92007-05-06 00:00:00 +00002344 unsigned OpNum = 0;
2345 Value *LHS, *RHS;
2346 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2347 getValue(Record, OpNum, LHS->getType(), RHS) ||
2348 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002349 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002350
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002351 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002352 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002353 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002354 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002355 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002356 break;
2357 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002358
Chris Lattner231cbcb2007-05-02 04:27:25 +00002359 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002360 {
2361 unsigned Size = Record.size();
2362 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002363 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002364 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002365 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002366 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002367
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002368 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002369 Value *Op = NULL;
2370 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2371 return Error("Invalid RET record");
2372 if (OpNum != Record.size())
2373 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002374
Chris Lattner96a74c52011-06-17 18:09:11 +00002375 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002376 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002377 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002378 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002379 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002380 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002381 return Error("Invalid BR record");
2382 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2383 if (TrueDest == 0)
2384 return Error("Invalid BR record");
2385
Devang Patele8e02132009-09-18 19:26:43 +00002386 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002387 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002388 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002389 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002390 else {
2391 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002392 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002393 if (FalseDest == 0 || Cond == 0)
2394 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002395 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002396 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002397 }
2398 break;
2399 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002400 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002401 if (Record.size() < 3 || (Record.size() & 1) == 0)
2402 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002403 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002404 Value *Cond = getFnValueByID(Record[1], OpTy);
2405 BasicBlock *Default = getBasicBlock(Record[2]);
2406 if (OpTy == 0 || Cond == 0 || Default == 0)
2407 return Error("Invalid SWITCH record");
2408 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002409 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002410 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002411 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002412 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002413 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2414 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2415 if (CaseVal == 0 || DestBB == 0) {
2416 delete SI;
2417 return Error("Invalid SWITCH record!");
2418 }
2419 SI->addCase(CaseVal, DestBB);
2420 }
2421 I = SI;
2422 break;
2423 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002424 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002425 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002426 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002427 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002428 Value *Address = getFnValueByID(Record[1], OpTy);
2429 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002430 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002431 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002432 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002433 InstructionList.push_back(IBI);
2434 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2435 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2436 IBI->addDestination(DestBB);
2437 } else {
2438 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002439 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002440 }
2441 }
2442 I = IBI;
2443 break;
2444 }
2445
Duncan Sandsdc024672007-11-27 13:23:08 +00002446 case bitc::FUNC_CODE_INST_INVOKE: {
2447 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002448 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002449 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002450 unsigned CCInfo = Record[1];
2451 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2452 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002453
Chris Lattnera9bb7132007-05-08 05:38:01 +00002454 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002455 Value *Callee;
2456 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002457 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002458
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002459 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2460 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002461 dyn_cast<FunctionType>(CalleeTy->getElementType());
2462
2463 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002464 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2465 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002466 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002467
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002468 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002469 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2470 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2471 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002472 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002473
Chris Lattner7337ab92007-05-06 00:00:00 +00002474 if (!FTy->isVarArg()) {
2475 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002476 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002477 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002478 // Read type/value pairs for varargs params.
2479 while (OpNum != Record.size()) {
2480 Value *Op;
2481 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2482 return Error("Invalid INVOKE record");
2483 Ops.push_back(Op);
2484 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002485 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002486
Jay Foada3efbb12011-07-15 08:37:34 +00002487 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002488 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002489 cast<InvokeInst>(I)->setCallingConv(
2490 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002491 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002492 break;
2493 }
Bill Wendling772fe172011-07-27 20:18:04 +00002494 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2495 unsigned Idx = 0;
2496 Value *Val = 0;
2497 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2498 return Error("Invalid RESUME record");
2499 I = ResumeInst::Create(Context, Val);
2500 break;
2501 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002502 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
Owen Anderson1d0be152009-08-13 21:58:54 +00002503 I = new UnwindInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002504 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002505 break;
2506 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002507 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002508 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002509 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002510 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002511 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002512 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002513 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002514 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002515
Jay Foad3ecfc862011-03-30 11:28:46 +00002516 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002517 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002518
Chris Lattner15e6d172007-05-04 19:11:41 +00002519 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2520 Value *V = getFnValueByID(Record[1+i], Ty);
2521 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002522 if (!V || !BB) return Error("Invalid PHI record");
2523 PN->addIncoming(V, BB);
2524 }
2525 I = PN;
2526 break;
2527 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002528
Bill Wendling772fe172011-07-27 20:18:04 +00002529 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2530 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2531 unsigned Idx = 0;
2532 if (Record.size() < 4)
2533 return Error("Invalid LANDINGPAD record");
2534 Type *Ty = getTypeByID(Record[Idx++]);
2535 if (!Ty) return Error("Invalid LANDINGPAD record");
2536 Value *PersFn = 0;
2537 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2538 return Error("Invalid LANDINGPAD record");
2539
2540 bool IsCleanup = !!Record[Idx++];
2541 unsigned NumClauses = Record[Idx++];
2542 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2543 LP->setCleanup(IsCleanup);
2544 for (unsigned J = 0; J != NumClauses; ++J) {
2545 LandingPadInst::ClauseType CT =
2546 LandingPadInst::ClauseType(Record[Idx++]);
2547 Value *Val = 0;
2548 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2549 delete LP;
2550 return Error("Invalid LANDINGPAD record");
2551 }
2552
2553 LP->addClause(CT, Val);
2554 }
2555
2556 I = LP;
2557 break;
2558 }
2559
Chris Lattner96a74c52011-06-17 18:09:11 +00002560 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2561 if (Record.size() != 4)
2562 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002563 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002564 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002565 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002566 Value *Size = getFnValueByID(Record[2], OpTy);
2567 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002568 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002569 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002570 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002571 break;
2572 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002573 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002574 unsigned OpNum = 0;
2575 Value *Op;
2576 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2577 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002578 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002579
Chris Lattner7337ab92007-05-06 00:00:00 +00002580 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002581 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002582 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002583 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002584 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002585 unsigned OpNum = 0;
2586 Value *Val, *Ptr;
2587 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002588 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002589 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2590 OpNum+2 != Record.size())
2591 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002592
Christopher Lambfe63fb92007-12-11 08:59:05 +00002593 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002594 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002595 break;
2596 }
Eli Friedman47f35132011-07-25 23:16:38 +00002597 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2598 if (2 != Record.size())
2599 return Error("Invalid FENCE record");
2600 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2601 if (Ordering == NotAtomic || Ordering == Unordered ||
2602 Ordering == Monotonic)
2603 return Error("Invalid FENCE record");
2604 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2605 I = new FenceInst(Context, Ordering, SynchScope);
2606 InstructionList.push_back(I);
2607 break;
2608 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002609 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002610 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2611 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002612 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002613
Devang Patel05988662008-09-25 21:00:45 +00002614 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002615 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002616
Chris Lattnera9bb7132007-05-08 05:38:01 +00002617 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002618 Value *Callee;
2619 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2620 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002621
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002622 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2623 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002624 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002625 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002626 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002627
Chris Lattner0579f7f2007-05-03 22:04:19 +00002628 SmallVector<Value*, 16> Args;
2629 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002630 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002631 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002632 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002633 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002634 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002635 if (Args.back() == 0) return Error("Invalid CALL record");
2636 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002637
Chris Lattner0579f7f2007-05-03 22:04:19 +00002638 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002639 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002640 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002641 return Error("Invalid CALL record");
2642 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002643 while (OpNum != Record.size()) {
2644 Value *Op;
2645 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2646 return Error("Invalid CALL record");
2647 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002648 }
2649 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002650
Jay Foada3efbb12011-07-15 08:37:34 +00002651 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002652 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002653 cast<CallInst>(I)->setCallingConv(
2654 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002655 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002656 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002657 break;
2658 }
2659 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2660 if (Record.size() < 3)
2661 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002662 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002663 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002664 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002665 if (!OpTy || !Op || !ResTy)
2666 return Error("Invalid VAARG record");
2667 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002668 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002669 break;
2670 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002671 }
2672
2673 // Add instruction to end of current BB. If there is no current BB, reject
2674 // this file.
2675 if (CurBB == 0) {
2676 delete I;
2677 return Error("Invalid instruction with no BB");
2678 }
2679 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002680
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002681 // If this was a terminator instruction, move to the next block.
2682 if (isa<TerminatorInst>(I)) {
2683 ++CurBBNo;
2684 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2685 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002686
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002687 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002688 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002689 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002690 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002691
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002692 // Check the function list for unresolved values.
2693 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2694 if (A->getParent() == 0) {
2695 // We found at least one unresolved value. Nuke them all to avoid leaks.
2696 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002697 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002698 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002699 delete A;
2700 }
2701 }
Chris Lattner35a04702007-05-04 03:50:29 +00002702 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002703 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002704 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002705
Dan Gohman064ff3e2010-08-25 20:23:38 +00002706 // FIXME: Check for unresolved forward-declared metadata references
2707 // and clean up leaks.
2708
Chris Lattner50b136d2009-10-28 05:53:48 +00002709 // See if anything took the address of blocks in this function. If so,
2710 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002711 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2712 BlockAddrFwdRefs.find(F);
2713 if (BAFRI != BlockAddrFwdRefs.end()) {
2714 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2715 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2716 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002717 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002718 return Error("Invalid blockaddress block #");
2719
2720 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002721 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002722 FwdRef->eraseFromParent();
2723 }
2724
2725 BlockAddrFwdRefs.erase(BAFRI);
2726 }
2727
Chris Lattner980e5aa2007-05-01 05:52:21 +00002728 // Trim the value list down to the size it was before we parsed this function.
2729 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002730 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002731 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002732 return false;
2733}
2734
Chris Lattnerb348bb82007-05-18 04:02:46 +00002735//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002736// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002737//===----------------------------------------------------------------------===//
2738
2739
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002740bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2741 if (const Function *F = dyn_cast<Function>(GV)) {
2742 return F->isDeclaration() &&
2743 DeferredFunctionInfo.count(const_cast<Function*>(F));
2744 }
2745 return false;
2746}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002747
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002748bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2749 Function *F = dyn_cast<Function>(GV);
2750 // If it's not a function or is already material, ignore the request.
2751 if (!F || !F->isMaterializable()) return false;
2752
2753 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002754 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002755
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002756 // Move the bit stream to the saved position of the deferred function body.
2757 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002758
Chris Lattnerb348bb82007-05-18 04:02:46 +00002759 if (ParseFunctionBody(F)) {
2760 if (ErrInfo) *ErrInfo = ErrorString;
2761 return true;
2762 }
Chandler Carruth69940402007-08-04 01:51:18 +00002763
2764 // Upgrade any old intrinsic calls in the function.
2765 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2766 E = UpgradedIntrinsics.end(); I != E; ++I) {
2767 if (I->first != I->second) {
2768 for (Value::use_iterator UI = I->first->use_begin(),
2769 UE = I->first->use_end(); UI != UE; ) {
2770 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2771 UpgradeIntrinsicCall(CI, I->second);
2772 }
2773 }
2774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002775
Chris Lattnerb348bb82007-05-18 04:02:46 +00002776 return false;
2777}
2778
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002779bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2780 const Function *F = dyn_cast<Function>(GV);
2781 if (!F || F->isDeclaration())
2782 return false;
2783 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2784}
2785
2786void BitcodeReader::Dematerialize(GlobalValue *GV) {
2787 Function *F = dyn_cast<Function>(GV);
2788 // If this function isn't dematerializable, this is a noop.
2789 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002790 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002791
Chris Lattnerb348bb82007-05-18 04:02:46 +00002792 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002793
Chris Lattnerb348bb82007-05-18 04:02:46 +00002794 // Just forget the function body, we can remat it later.
2795 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002796}
2797
2798
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002799bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2800 assert(M == TheModule &&
2801 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002802 // Iterate over the module, deserializing any functions that are still on
2803 // disk.
2804 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2805 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002806 if (F->isMaterializable() &&
2807 Materialize(F, ErrInfo))
2808 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002809
Daniel Dunbara279bc32009-09-20 02:20:51 +00002810 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2811 // delete the old functions to clean up. We can't do this unless the entire
2812 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002813 // with calls to the old function.
2814 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2815 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2816 if (I->first != I->second) {
2817 for (Value::use_iterator UI = I->first->use_begin(),
2818 UE = I->first->use_end(); UI != UE; ) {
2819 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2820 UpgradeIntrinsicCall(CI, I->second);
2821 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002822 if (!I->first->use_empty())
2823 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002824 I->first->eraseFromParent();
2825 }
2826 }
2827 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002828
2829 // Check debug info intrinsics.
2830 CheckDebugInfoIntrinsics(TheModule);
2831
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002832 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002833}
2834
Chris Lattner48f84872007-05-01 04:59:48 +00002835
Chris Lattnerc453f762007-04-29 07:54:31 +00002836//===----------------------------------------------------------------------===//
2837// External interface
2838//===----------------------------------------------------------------------===//
2839
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002840/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002841///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002842Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2843 LLVMContext& Context,
2844 std::string *ErrMsg) {
2845 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002846 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002847 M->setMaterializer(R);
2848 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002849 if (ErrMsg)
2850 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002851
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002852 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002853 return 0;
2854 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002855 // Have the BitcodeReader dtor delete 'Buffer'.
2856 R->setBufferOwned(true);
2857 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002858}
2859
2860/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2861/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002862Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002863 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002864 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2865 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002866
2867 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2868 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002869 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002870
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002871 // Read in the entire module, and destroy the BitcodeReader.
2872 if (M->MaterializeAllPermanently(ErrMsg)) {
2873 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002874 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002875 }
Bill Wendling34711742010-10-06 01:22:42 +00002876
Chris Lattnerc453f762007-04-29 07:54:31 +00002877 return M;
2878}
Bill Wendling34711742010-10-06 01:22:42 +00002879
2880std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2881 LLVMContext& Context,
2882 std::string *ErrMsg) {
2883 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2884 // Don't let the BitcodeReader dtor delete 'Buffer'.
2885 R->setBufferOwned(false);
2886
2887 std::string Triple("");
2888 if (R->ParseTriple(Triple))
2889 if (ErrMsg)
2890 *ErrMsg = R->getErrorString();
2891
2892 delete R;
2893 return Triple;
2894}